text
stringlengths 184
4.48M
|
---|
//
// Copyright © Uber Technologies, Inc. All rights reserved.
//
import Foundation
enum Parameter: CaseIterable {
case clientID
case codeChallenge
case codeChallengeMethod
case redirectURI
case resposeType
var identifier: String {
switch self {
case .clientID: return "client_id"
case .codeChallenge: return "code_challenge"
case .codeChallengeMethod: return "code_challenge_method"
case .redirectURI: return "redirect_uri"
case .resposeType: return "response_type"
}
}
var title: String {
switch self {
case .clientID: return "Client ID [Required]"
case .codeChallenge: return "Code Challenge [Optional]"
case .codeChallengeMethod: return "Code Challenge Method [Optional]"
case .redirectURI: return "Redirect URI [Required]"
case .resposeType: return "Response Type [Required]"
}
}
var description: String {
switch self {
case .clientID:
return "The client identifier found in the developer portal. (developer.uber.com)"
case .redirectURI:
return "The url that should be opened after fetching the authorization code. If response_type == \"code\", this url will be called with the code appended as a query parameter. redirect_uri?code=123"
case .resposeType:
return "The type of identifier the Uber authentication service should respond with. `code` is the only supported option."
case.codeChallenge:
return "A unique identifier to be used when exchanging the auth code for an auth token. Use this to verify the /token request is coming from the same party as the original sender. This parameter is not required to make a successful /authorize request, but is required to exchange for a token on the client."
case .codeChallengeMethod:
return "The method used to generate the code challenge identifier."
}
}
var isRequired: Bool {
switch self {
case .clientID,
.redirectURI,
.resposeType,
.codeChallenge,
.codeChallengeMethod:
return true
}
}
var isEditable: Bool {
switch self {
case .clientID,
.redirectURI:
return true
case .resposeType,
.codeChallenge,
.codeChallengeMethod:
return false
}
}
} |
import React from "react";
import SearchBar from "../components/ui/SearchBar";
import PokemonList from "../components/pokemon/PokemonList";
import RegionFilter from "../components/ui/RegionFilter";
import { PokemonProvider } from "../context/PokemonContext";
import { QueryClient, QueryClientProvider } from "react-query";
import ScrollToTop from "../components/ui/ScrollToTop";
const queryClient = new QueryClient();
function Home() {
return (
<PokemonProvider>
<div className="flex items-center mx-auto my-16 place-content-center">
<SearchBar />
<RegionFilter />
<ScrollToTop />
</div>
<QueryClientProvider client={queryClient}>
<PokemonList />
</QueryClientProvider>
</PokemonProvider>
);
}
export default Home; |
val f = (_: Int) + (_: Int)
f(2, 4)
def sum(a: Int, b: Int) = a + b
val b = sum _
b.apply(1, 2)
b(1, 2)
def sum2(a: Int)(b: Int) = a + b
val b2 = sum2(2) _
b2.apply(1)
b2(1)
def sum3(a: Int, b: Int, c: Int) = a + b + c
val b3 = sum3(1, _: Int, 2)
b3(0)
b3(1)
def x(f: Int => Int) = f(2)
x(sum2(3))
//closure
var more = 1
val p = (x: Int) => x + more
p(2)
more = 3
p(2)
val p2 = (x: Int) => {
more = -1;
x + more;
}
p2(3)
more
def makeIncreaser(m: Int) = (x: Int) => x + m
val mi1 = makeIncreaser(1)
val mi2 = makeIncreaser(1000)
mi1(1)
mi2(1)
def echo(args: String*) = {
args foreach (println)
args.length
}
echo()
echo("one")
echo("2", "3")
val arr = Array("hi", "there")
echo(arr: _*)
def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) |
import {
AfterViewInit,
Component,
EventEmitter,
Input,
OnInit,
Output,
} from '@angular/core';
import {
FormBuilder,
FormControl,
FormGroup,
Validators,
} from '@angular/forms';
import { MsFormalFeature } from '../ms-formal-features-part';
@Component({
selector: 'tgr-ms-formal-feature',
templateUrl: './ms-formal-feature.component.html',
styleUrls: ['./ms-formal-feature.component.css'],
})
export class MsFormalFeatureComponent implements OnInit, AfterViewInit {
private _model: MsFormalFeature | undefined;
@Input()
public get model(): MsFormalFeature | undefined {
return this._model;
}
public set model(value: MsFormalFeature | undefined) {
if (this._model === value) {
return;
}
this._model = value;
this.updateForm(value);
}
@Output()
public modelChange: EventEmitter<MsFormalFeature>;
@Output()
public editorClose: EventEmitter<any>;
public form: FormGroup;
public handId: FormControl<string | null>;
public description: FormControl<string | null>;
constructor(formBuilder: FormBuilder) {
this.modelChange = new EventEmitter<MsFormalFeature>();
this.editorClose = new EventEmitter<any>();
// form
this.handId = formBuilder.control(null, Validators.maxLength(50));
this.description = formBuilder.control(null, [
Validators.required,
Validators.maxLength(50000),
]);
this.form = formBuilder.group({
handId: this.handId,
description: this.description,
});
}
ngOnInit(): void {}
ngAfterViewInit(): void {
this.updateForm(this.model);
}
private updateForm(model: MsFormalFeature | undefined): void {
if (!model) {
this.form.reset();
return;
}
this.handId.setValue(model.handId);
this.description.setValue(model.description);
this.form.markAsPristine();
}
private getModel(): MsFormalFeature {
return {
handId: this.handId.value?.trim() || '',
description: this.description.value?.trim() || '',
};
}
public cancel(): void {
this.editorClose.emit();
}
public save(): void {
if (this.form.invalid) {
return;
}
this._model = this.getModel();
this.modelChange.emit(this._model);
}
} |
#' @title Clean up reference address tables
#'
#' @description \code{deduplicate_addresses} removes duplicate addresses in the ref tables and synchronize.
#'
#' @details This function brings in all addresses currently in the reference tables
#' and deduplicates them. Because there is a stage -> final workflow, the stage version
#' of each table also needs to be deduplicated. Also, the reference tables are currently
#' synchronized between two different servers. In order to avoid reintroducing
#' duplicates, both servers must be deduplicated (and synchronized at the same time).
#' Server and table names are currently hard coded but could be made more generalized if needed.
#'
#' @param conn_hhsaw SQL server connection to the HHSAW server, created using \code{odbc} package.
#' @param conn_phclaims SQL server connection to the PHClaims server, created using \code{odbc} package.
#'
#' @importFrom data.table data.table ":=" .I .N .SD setDT setorder
#'
#'
#' @export
deduplicate_addresses <- function(conn_hhsaw = NULL,
conn_phclaims = NULL) {
# Set up functions to avoid duplicating code ----
sql_loader <- function(df, conn = NULL, to_schema = "ref", to_table = NULL, overwrite = T) {
start <- 1L
max_rows <- 50000L
cycles <- ceiling(nrow(df)/max_rows)
initial_append <- ifelse(overwrite == TRUE, FALSE, TRUE)
lapply(seq(start, cycles), function(i) {
start_row <- ifelse(i == 1, 1L, max_rows * (i-1) + 1)
end_row <- min(nrow(df), max_rows * i)
message("Loading cycle ", i, " of ", cycles)
if (i == 1) {
DBI::dbWriteTable(conn,
name = DBI::Id(schema = to_schema, table = to_table),
value = as.data.frame(df[start_row:end_row, ]),
overwrite = overwrite, append = initial_append)
} else {
DBI::dbWriteTable(conn,
name = DBI::Id(schema = to_schema, table = to_table),
value = as.data.frame(df[start_row:end_row ,]),
overwrite = F, append = T)
}
})
}
dedup <- function(conn = NULL, to_schema = "ref", to_table = NULL,
grouping = c("geo_hash_raw", "geo_hash_geocode")) {
grouping <- match.arg(grouping)
# Bring in data
message("Bringing in data from ", to_schema, ".", to_table)
adds <- data.table::setDT(DBI::dbGetQuery(conn,
glue::glue_sql("select * from {`to_schema`}.{`to_table`}",
.con = conn)))
# Deduplicate
adds[, row_cnt := .N, by = grouping]
print(dplyr::count(adds, row_cnt))
# See how many duplicates need to be removed
adds_dups <- nrow(adds[row_cnt > 1])
if (adds_dups > 1) {
adds_rows <- nrow(adds)
message(adds_dups, " rows in ", to_schema, ".", to_table, " will be deduplicated")
# Sort so that the newer row is prioritized (assume improvements to address cleaning/geocoding)
order_cols <- c(grouping, "last_run")
data.table::setorderv(adds, order_cols)
# Take the first row of each geo_hash
adds <- adds[adds[, .I[1], by = grouping]$V1]
message(adds_rows - nrow(adds), " duplicate rows were removed from ", to_schema, ".", to_table)
} else {
message("No duplicate rows found in ", to_schema, ".", to_table)
}
# Load data back to SQL
if (adds_dups > 1) {
adds[, row_cnt := NULL] # Remove column used to find duplicates
sql_loader(df = adds, conn = conn, to_schema = to_schema, to_table = to_table, overwrite = T)
}
# Return the data frame to use it in synchronizing across servers
return(adds)
}
sync <- function(conn_hhsaw, conn_phclaims,
df_hhsaw, df_phclaims,
to_schema_hhsaw, to_table_hhsaw,
to_schema_phclaims, to_table_phclaims,
grouping = c("geo_hash_raw", "geo_hash_geocode")) {
grouping <- match.arg(grouping)
# Compare and find differences
update_hhsaw <- dplyr::anti_join(df_phclaims, df_hhsaw, by = grouping)
update_phclaims <- dplyr::anti_join(df_hhsaw, df_phclaims, by = grouping)
# Update tables so they are in sync
if (nrow(update_hhsaw) > 0) {
message(nrow(update_hhsaw), " address rows to be loaded from PHClaims to HHSAW")
print(str(update_hhsaw))
sql_loader(df = update_hhsaw, conn = conn_hhsaw,
to_schema = to_schema_hhsaw, to_table = to_table_hhsaw,
overwrite = F)
} else {
message("No rows to add to HHSAW table")
}
if (nrow(update_phclaims) > 0) {
message(nrow(update_phclaims), " address rows to be loaded from HHSAW to PHClaims")
print(str(update_phclaims))
sql_loader(df = update_phclaims, conn = conn_phclaims,
to_schema = to_schema_phclaims, to_table = to_table_phclaims,
overwrite = F)
} else {
message("No rows to add to PHClaims table")
}
}
# ref.address_clean ----
## Deduplicate ----
### HHSAW data ----
message("Deduplicating HHSAW tables")
adds_stage_hhsaw <- dedup(conn = conn_hhsaw, to_schema = "ref", to_table = "stage_address_clean", grouping = "geo_hash_raw")
adds_hhsaw <- dedup(conn = conn_hhsaw, to_schema = "ref", to_table = "address_clean", grouping = "geo_hash_raw")
### PHClaims data ----
message("Deduplicating PHClaims tables")
adds_stage_phclaims <- dedup(conn = conn_phclaims, to_schema = "stage", to_table = "address_clean", grouping = "geo_hash_raw")
adds_phclaims <- dedup(conn = conn_phclaims, to_schema = "ref", to_table = "address_clean", grouping = "geo_hash_raw")
## Compare and find differences ----
message("Synchronizing address tables")
### Stage table ----
sync(conn_hhsaw = conn_hhsaw, conn_phclaims = conn_phclaims,
df_hhsaw = adds_stage_hhsaw, df_phclaims = adds_stage_phclaims,
to_schema_hhsaw = "ref", to_table_hhsaw = "stage_address_clean",
to_schema_phclaims = "stage", to_table_phclaims = "address_clean",
grouping = "geo_hash_raw")
### Final table ----
sync(conn_hhsaw = conn_hhsaw, conn_phclaims = conn_phclaims,
df_hhsaw = adds_hhsaw, df_phclaims = adds_phclaims,
to_schema_hhsaw = "ref", to_table_hhsaw = "address_clean",
to_schema_phclaims = "ref", to_table_phclaims = "address_clean",
grouping = "geo_hash_raw")
# ref.address_geocode ----
## Deduplicate ----
### HHSAW data ----
adds_stage_hhsaw <- dedup(conn = conn_hhsaw,
to_schema = "ref", to_table = "stage_address_geocode",
grouping = "geo_hash_geocode")
adds_hhsaw <- dedup(conn = conn_hhsaw,
to_schema = "ref", to_table = "address_geocode",
grouping = "geo_hash_geocode")
### PHClaims data ----
adds_stage_phclaims <- dedup(conn = conn_phclaims,
to_schema = "stage", to_table = "address_geocode",
grouping = "geo_hash_geocode")
adds_phclaims <- dedup(conn = conn_phclaims,
to_schema = "ref", to_table = "address_geocode",
grouping = "geo_hash_geocode")
## Compare and find differences ----
message("Synchronizing geocode tables")
### Stage table ----
sync(conn_hhsaw = conn_hhsaw, conn_phclaims = conn_phclaims,
df_hhsaw = adds_stage_hhsaw, df_phclaims = adds_stage_phclaims,
to_schema_hhsaw = "ref", to_table_hhsaw = "stage_address_geocode",
to_schema_phclaims = "stage", to_table_phclaims = "address_geocode",
grouping = "geo_hash_geocode")
### Final table ----
sync(conn_hhsaw = conn_hhsaw, conn_phclaims = conn_phclaims,
df_hhsaw = adds_hhsaw, df_phclaims = adds_phclaims,
to_schema_hhsaw = "ref", to_table_hhsaw = "address_geocode",
to_schema_phclaims = "ref", to_table_phclaims = "address_geocode",
grouping = "geo_hash_geocode")
} |
import { CustomScalar, Scalar } from '@nestjs/graphql'
import { Kind, ValueNode } from 'graphql'
export class LowerCase extends String {}
@Scalar('LowerCase', () => LowerCase)
export class LowerCaseScalar implements CustomScalar<string, LowerCase> {
description = 'Lower string custom scalar type'
parseValue(value: string): LowerCase {
return value.toLowerCase()
}
serialize(value: LowerCase): string {
return value.toString()
}
parseLiteral(ast: ValueNode): LowerCase | null {
if (ast.kind === Kind.STRING) {
return ast.value.toLowerCase()
}
return null
}
} |
package org.patterns.behavioral.state.states;
import org.patterns.behavioral.state.ui.Player;
public class PlayingState extends State {
/**
* Контекст передаёт себя в конструктор состояния, чтобы состояние могло
* обращаться к его данным и методам в будущем, если потребуется.
*
* @param player
*/
PlayingState(Player player) {
super(player);
}
@Override
public String onLock() {
player.changeState(new LockedState(player));
player.setCurrentTrackAfterStop();
return "Stop playing";
}
@Override
public String onPlay() {
player.changeState(new ReadyState(player));
return "Paused...";
}
@Override
public String onNext() {
return player.nextTrack();
}
@Override
public String onPrevious() {
return player.previousTrack();
}
} |
;;; fibs.el --- Play backgammon with FIBS in Emacs -*- lexical-binding: t; -*-
;;; Commentary:
;; FIBS (The First Internet Backgammon Server) is a popular server for playing
;; backgammon online. Its interface is driven through telnet, which Emacs has
;; included in its distribution. This package includes a number of niceties for
;; making playing backgammon on FIBS easier.
;;; Code:
(require 'telnet)
(require 'comint)
;;; Customization options
(defgroup fibs nil
"Customizations for FIBS, the First Internet Backgammon Server."
:group 'games)
(defcustom fibs-server "fibs.com"
"The server to connect to FIBS with."
:type 'string)
(defcustom fibs-port 4321
"The port to connect to FIBS with."
:type 'number)
(defcustom fibs-autologin nil
"Whether to autologin to FIBS."
:type 'boolean)
(defcustom fibs-user nil
"The user for FIBS."
:type 'string)
(defcustom fibs-password nil
"The password for `fibs-user'."
:type 'string)
;;; Variables
(defvar fibs--process nil
"The process connected to FIBS.")
(defvar fibs--buffer nil
"The buffer connected to the FIBS process.")
;;; Functions
(defalias 'fibs-send 'telnet-simple-send)
;;;###autoload
(defun fibs-connect (host &optional port)
"Open a network connection to HOST and PORT.
Return the buffer created."
;; I'm basically re-writing `telnet' here because it's stupid.
(interactive (list (read-string "Open connection to host: "
nil nil fibs-server)
(cond ((null current-prefix-arg) nil)
((consp current-prefix-arg) (read-string "Port: "
nil nil
fibs-port))
(t (prefix-numeric-value current-prefix-arg)))))
(let* ((comint-delimiter-argument-list '(?\ ?\t))
(properties (alist-get host telnet-host-properties))
(telnet-program (if properties (car properties) telnet-program))
(hname (if port (format "%s:%s" host port) host))
(name (format "%s-%s" telnet-program (comint-arguments hname 0 nil)))
(buffer (get-buffer name))
(telnet-options (when (cdr properties) (cons "-l" (cdr properties)))))
;; Clean up zombies
(when (not (or (process-live-p fibs--process)
(buffer-live-p fibs--buffer)
(eq fibs--process (get-buffer-process fibs--buffer))))
(fibs-kill))
(setq fibs--buffer (apply #'make-comint-in-buffer name "*FIBS*"
telnet-program nil telnet-options))
(unless fibs--process
(setq fibs--process (get-buffer-process fibs--buffer))
(with-current-buffer fibs--buffer
(set-process-filter fibs--process (if fibs-password
#'fibs--initial-filter
#'telnet-initial-filter))
;; Don't sent `open' til telnet is ready for it.
(accept-process-output fibs--process)
(erase-buffer)
(process-send-string fibs--process (format "open %s%s%s\n"
host (if port " " "")
(or port "")))
(fibs-mode)
(setq-local telnet-connect-command (list 'telnet host port))
(setq comint-input-sender #'fibs-send)
(setq telnet-count telnet-initial-count)))))
(defun fibs--initial-filter (proc string)
"Process filter for FIBS buffers."
;; Rewritten from `telnet-initial-filter'. I don't need to check for a
;; password from the user. (At least right now. I might want to change the
;; logic here.)
(save-current-buffer
(set-buffer (process-buffer proc))
(let ((case-fold-search t))
(cond ((string-match-p "No such host" string)
(kill-buffer (process-buffer proc))
(error "No such host"))
((and (string-match-p "login:" string)
fibs-autologin fibs-user)
(fibs-send fibs--process fibs-user))
((and (string-match-p "password:" string)
fibs-autologin fibs-password)
(fibs-send fibs--process fibs-password)
(set-process-filter proc #'telnet-filter))
(t (telnet-check-software-type-initialize string)
(telnet-filter proc string)
(cond ((> telnet-count telnet-maximum-count)
(set-process-filter proc #'telnet-filter))
(t (setq telnet-count (1+ telnet-count)))))))))
;;;###autoload
(defun fibs ()
"Connect to the FIBS server."
(interactive)
(fibs-connect fibs-server fibs-port)
(switch-to-buffer fibs--buffer))
(defun fibs-kill ()
"Kill everything associated with fibs."
(interactive)
(let ((kill-buffer-query-functions nil))
(condition-case nil
(kill-process fibs--process)
(t (setq fibs--process nil)))
(condition-case nil
(with-current-buffer fibs--buffer
(remove-hook 'kill-buffer-hook #'fibs-kill t)
(kill-buffer fibs--buffer))
(t (setq fibs--buffer nil)))))
(define-derived-mode fibs-mode telnet-mode "FIBS"
"This mode is for connecting to the First Internet Backgammon Server."
(add-hook 'kill-buffer-hook #'fibs-kill nil t))
(provide 'fibs)
;;; fibs.el ends here |
import { motion } from 'framer-motion'
import { fetchPokemon } from '../utils'
import { useRequest } from '../useRequest'
const Pokemon: React.FC<{ name: string; timeout: number }> = ({
name,
timeout
}) => {
// NOTE: timeout can vary per Pokemon, but we'll always wait for the last request to complete
// before rendering all the Pokemon cards
// (as per our Suspense fallback in App.tsx when isGlobal is true)
const fetcher = fetchPokemon(timeout)
const { data, error } = useRequest(`/pokemon`, fetcher, name.toLowerCase())
if (error) return <pre>{error.message}</pre>
const capitalize = (word: string) => word[0].toUpperCase() + word.slice(1)
const variants = {
hidden: { opacity: 0 },
visible: { opacity: 1 }
}
const transition = {
duration: 0.5,
ease: 'easeInOut'
}
return (
<>
<motion.div
variants={variants}
transition={transition}
initial="hidden"
animate="visible"
style={{ marginBottom: '-20px' }}
>
<p>{capitalize(data.name)}!</p>
<p>Pokedex #: {data.id}</p>
<motion.img
variants={variants}
transition={transition}
src={data.sprites['front_default']}
height={150}
/>
</motion.div>
</>
)
}
export default Pokemon |
package cli_test
import (
"errors"
"strings"
"testing"
"github.com/golang/mock/gomock"
"github.com/greenplum-db/gpdb/gp/cli"
"github.com/greenplum-db/gpdb/gp/hub"
"github.com/greenplum-db/gpdb/gp/idl"
"github.com/greenplum-db/gpdb/gp/idl/mock_idl"
)
func TestWaitAndRetryHubConnect(t *testing.T) {
setupTest(t)
defer teardownTest()
t.Run("WaitAndRetryHubConnect returns success on success", func(t *testing.T) {
defer resetCLIVars()
cli.ConnectToHub = func(conf *hub.Config) (idl.HubClient, error) {
return nil, nil
}
err := cli.WaitAndRetryHubConnect()
if err != nil {
t.Fatalf("unexpected error: %#v", err)
}
})
t.Run("WaitAndRetryHubConnect returns failure upon failure to connect", func(t *testing.T) {
defer resetCLIVars()
expectedErr := "failed to connect to hub service. Check hub service log for details."
cli.ConnectToHub = func(conf *hub.Config) (idl.HubClient, error) {
return nil, errors.New(expectedErr)
}
err := cli.WaitAndRetryHubConnect()
if !strings.Contains(err.Error(), expectedErr) {
t.Fatalf("got %v, want %v", err, expectedErr)
}
})
}
func TestStartAgentsAll(t *testing.T) {
setupTest(t)
defer teardownTest()
t.Run("starts all agents without any error", func(t *testing.T) {
defer resetCLIVars()
cli.ConnectToHub = func(conf *hub.Config) (idl.HubClient, error) {
hubClient := mock_idl.NewMockHubClient(ctrl)
hubClient.EXPECT().StartAgents(gomock.Any(), gomock.Any())
return hubClient, nil
}
_, err := cli.StartAgentsAll(cli.Conf)
if err != nil {
t.Fatalf("unexpected error: %#v", err)
}
})
t.Run("start all agents fails on error connecting hub", func(t *testing.T) {
defer resetCLIVars()
expectedStr := "error connecting hub"
cli.ConnectToHub = func(conf *hub.Config) (idl.HubClient, error) {
return nil, errors.New(expectedStr)
}
_, err := cli.StartAgentsAll(cli.Conf)
if !strings.Contains(err.Error(), expectedStr) {
t.Fatalf("got %v, want %v", err, expectedStr)
}
})
t.Run("start all agent fails when error starting agents", func(t *testing.T) {
defer resetCLIVars()
expectedStr := "TEST: Agent Start ERROR"
cli.ConnectToHub = func(conf *hub.Config) (idl.HubClient, error) {
hubClient := mock_idl.NewMockHubClient(ctrl)
hubClient.EXPECT().StartAgents(gomock.Any(), gomock.Any()).Return(nil, errors.New(expectedStr))
return hubClient, nil
}
_, err := cli.StartAgentsAll(cli.Conf)
if !strings.Contains(err.Error(), expectedStr) {
t.Fatalf("got %v, want %v", err, expectedStr)
}
})
}
func TestRunStartService(t *testing.T) {
setupTest(t)
defer teardownTest()
t.Run("Run services when there's no error", func(t *testing.T) {
defer resetCLIVars()
cli.StartHubService = func(serviceName string) error {
return nil
}
cli.WaitAndRetryHubConnect = funcNilError()
cli.StartAgentsAll = func(hubConfig *hub.Config) (idl.HubClient, error) {
return nil, nil
}
err := cli.RunStartService(nil, nil)
if err != nil {
t.Fatalf("unexpected error: %#v", err)
}
})
t.Run("Run services when there's error starting hub", func(t *testing.T) {
defer resetCLIVars()
expectedStr := "TEST ERROR Starting Hub service"
cli.StartHubService = func(serviceName string) error {
return errors.New(expectedStr)
}
err := cli.RunStartService(nil, nil)
if !strings.Contains(err.Error(), expectedStr) {
t.Fatalf("got %v, want %v", err, expectedStr)
}
})
t.Run("Run services when there's error connecting Hub", func(t *testing.T) {
defer resetCLIVars()
expectedStr := "TEST ERROR while connecting Hub service"
cli.StartHubService = func(serviceName string) error {
return nil
}
cli.WaitAndRetryHubConnect = funcErrorMessage(expectedStr)
err := cli.RunStartService(nil, nil)
if !strings.Contains(err.Error(), expectedStr) {
t.Fatalf("got %v, want %v", err, expectedStr)
}
})
t.Run("Run services when there's error starting agents", func(t *testing.T) {
defer resetCLIVars()
expectedStr := "TEST ERROR while starting agents"
cli.StartHubService = func(serviceName string) error {
return nil
}
cli.WaitAndRetryHubConnect = funcNilError()
cli.StartAgentsAll = func(hubConfig *hub.Config) (idl.HubClient, error) {
return nil, errors.New(expectedStr)
}
err := cli.RunStartService(nil, nil)
if !strings.Contains(err.Error(), expectedStr) {
t.Fatalf("got %v, want %v", err, expectedStr)
}
})
}
func TestRunStartAgent(t *testing.T) {
setupTest(t)
defer teardownTest()
t.Run("Run start agent starts agents when no failure", func(t *testing.T) {
defer resetCLIVars()
cli.StartAgentsAll = func(hubConfig *hub.Config) (idl.HubClient, error) {
return nil, nil
}
err := cli.RunStartAgent(nil, nil)
if err != nil {
t.Fatalf("unexpected error: %#v", err)
}
})
t.Run("Run start agent starts agents when starting agents fails", func(t *testing.T) {
defer resetCLIVars()
expectedStr := "TEST Error when starting agents"
cli.StartAgentsAll = func(hubConfig *hub.Config) (idl.HubClient, error) {
return nil, errors.New(expectedStr)
}
err := cli.RunStartAgent(nil, nil)
if !strings.Contains(err.Error(), expectedStr) {
t.Fatalf("got %v, want %v", err, expectedStr)
}
})
}
func TestRunStartHub(t *testing.T) {
setupTest(t)
defer teardownTest()
t.Run("Run Start Hub throws no error when there none", func(t *testing.T) {
defer resetCLIVars()
cli.StartHubService = func(serviceName string) error {
return nil
}
cli.ShowHubStatus = func(conf *hub.Config, skipHeader bool) (bool, error) {
return true, nil
}
cli.WaitAndRetryHubConnect = funcNilError()
err := cli.RunStartHub(nil, nil)
if err != nil {
t.Fatalf("unexpected error: %#v", err)
}
})
t.Run("Run Start Hub throws error when start hub service fails", func(t *testing.T) {
defer resetCLIVars()
expectedStr := "TEST Error: Failed to start Hub service"
cli.StartHubService = func(serviceName string) error {
return errors.New(expectedStr)
}
err := cli.RunStartHub(nil, nil)
if !strings.Contains(err.Error(), expectedStr) {
t.Fatalf("got %v, want %v", err, expectedStr)
}
})
t.Run("Run Start Hub throws no error when there none in verbose mode", func(t *testing.T) {
defer resetCLIVars()
expectedStr := "Test Error in ShowHubStatus"
cli.StartHubService = func(serviceName string) error {
return nil
}
cli.Verbose = true
cli.ShowHubStatus = func(conf *hub.Config, skipHeader bool) (bool, error) {
return false, errors.New(expectedStr)
}
cli.WaitAndRetryHubConnect = funcNilError()
err := cli.RunStartHub(nil, nil)
if !strings.Contains(err.Error(), expectedStr) {
t.Fatalf("got %v, want %v", err, expectedStr)
}
})
} |
package com.atguigu.gmall.order.config;
import com.atguigu.gmall.common.constant.SysRedisConst;
import com.atguigu.gmall.rabbit.constant.MqConst;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* 创建订单用的所有交换机和对列
*/
@Configuration
public class OrderEventMqConfiguration {
/**
* 项目启动自动创建交换机
* @return
*/
@Bean
public Exchange orderEventExchange(){
/**
* String name,
* boolean durable,
* boolean autoDelete,
* Map<String, Object> arguments
*/
TopicExchange exchange = new TopicExchange(
MqConst.EXCHANGE_ORDER_EVENT,
true,
false,
null);
return exchange;
}
/**
* 订单延迟队列
* @return
*/
@Bean
public Queue orderDelayQueue(){
/**
* String name, boolean durable,
* boolean durable
* boolean exclusive,
* boolean autoDelete,
* @Nullable Map<String, Object> arguments
*/
Map<String, Object> arguments = new HashMap<>();
//设置延迟队列参数
arguments.put("x-message-ttl", SysRedisConst.ORDER_CLOSE_TTL*1000);
// arguments.put("x-message-ttl", 10000);
arguments.put("x-dead-letter-exchange",MqConst.EXCHANGE_ORDER_EVENT);
arguments.put("x-dead-letter-routing-key",MqConst.RK_ORDER_DEAD);
return new Queue(
MqConst.QUEUE_ORDER_DELAY,
true,
false,
false,
arguments
);
}
/**
* 延迟队列和交换机绑定
* @return
*/
@Bean
public Binding orderDelayQueueBinding(){
/**
* String destination, 目的地
* Binding.DestinationType destinationType, 目的地类型
* String exchange, 交换机
* String routingKey, 路由键
* @Nullable Map<String, Object> arguments
*/
return new Binding(
MqConst.QUEUE_ORDER_DELAY,
Binding.DestinationType.QUEUE,
MqConst.EXCHANGE_ORDER_EVENT,
MqConst.RK_ORDER_CREATED,
null
);
}
/**
* 死单对列,保存所有过期订单,进行关单
* @return
*/
@Bean
public Queue orderDeadQueue(){
/**
* String name, boolean durable,
* boolean durable
* boolean exclusive,
* boolean autoDelete,
* @Nullable Map<String, Object> arguments
*/
return new Queue(
MqConst.QUEUE_ORDER_DEAD,
true,
false,
false,
null
);
}
/**
* 死单队列和交换机绑定
* @return
*/
@Bean
public Binding orderDeadQueueBinding(){
/**
* String destination, 目的地
* Binding.DestinationType destinationType, 目的地类型
* String exchange, 交换机
* String routingKey, 路由键
* @Nullable Map<String, Object> arguments
*/
return new Binding(
MqConst.QUEUE_ORDER_DEAD,
Binding.DestinationType.QUEUE,
MqConst.EXCHANGE_ORDER_EVENT,
MqConst.RK_ORDER_DEAD,
null
);
}
/**
* 支付成功单对列
* @return
*/
@Bean
public Queue payedQueue(){
/**
* String name, boolean durable,
* boolean durable
* boolean exclusive,
* boolean autoDelete,
* @Nullable Map<String, Object> arguments
*/
return new Queue(
MqConst.QUEUE_ORDER_PAYED,
true,
false,
false,
null
);
}
@Bean
public Binding payedQueueBinding(){
/**
* String destination, 目的地
* Binding.DestinationType destinationType, 目的地类型
* String exchange, 交换机
* String routingKey, 路由键
* @Nullable Map<String, Object> arguments
*/
return new Binding(
MqConst.QUEUE_ORDER_PAYED,
Binding.DestinationType.QUEUE,
MqConst.EXCHANGE_ORDER_EVENT,
MqConst.RK_ORDER_PAYED,
null
);
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Order</title>
<style>
.container{
display: flex;
max-width: 350px;
border: 1px solid black;
margin-bottom: 20px;
}
.item{
flex: 1;
background: brown;
color: white;
text-align: center;
font-size: 24px;
margin: 5px;
}
.order_1{
order: 1;
}
.order_2{
order: 2;
}
.order_3{
order: 3;
}
.order_4{
order: 4;
}
.direction{
flex-direction: column;
}
</style>
</head>
<body>
<h2>row</h2>
<p>order = 0</p>
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
<p>order = diferentes</p>
<div class="container">
<div class="item order_3">1</div>
<div class="item order_2">2</div>
<div class="item order_3">3</div>
<div class="item order_1">4</div>
</div>
<h2>column</h2>
<p>order = 0</p>
<div class="container direction">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
<p>order = diferentes</p>
<div class="container direction">
<div class="item order_3">1</div>
<div class="item order_2">2</div>
<div class="item order_3">3</div>
<div class="item order_1">4</div>
</div>
</body>
</html> |
import { useState } from "react";
import { useParams, Link, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { toast } from "react-toastify";
import { useTranslation } from "react-i18next";
import {
useGetProductDetailsQuery,
useCreateReviewMutation,
} from "../../redux/api/productApiSlice";
import { addToCart } from "../../redux/features/cart/cartSlice";
import Loader from "../../components/Loader";
import Message from "../../components/Message";
import HeartIcon from "./HeartIcon";
import Ratings from "./Ratings";
import ProductTabs from "./ProductTabs";
import Button from "../../components/Button";
const ProductDetails = () => {
const { id: productId } = useParams();
const navigate = useNavigate();
const dispatch = useDispatch();
const { t } = useTranslation();
const [qty, setQty] = useState(1);
const [rating, setRating] = useState(0);
const [comment, setComment] = useState("");
const {
data: product,
isLoading,
refetch,
error,
} = useGetProductDetailsQuery(productId);
const { userInfo } = useSelector((state) => state.auth);
const [createReview, { isLoading: loadingProductReview }] =
useCreateReviewMutation();
const submitHandler = async (e) => {
e.preventDefault();
try {
await createReview({
productId,
rating,
comment,
}).unwrap();
refetch();
toast.success("Review created successfully");
} catch (error) {
toast.error(error?.data || error.message);
}
};
const addToCartHandler = () => {
dispatch(addToCart({ ...product, qty }));
navigate("/cart");
};
return (
<>
<section>
{isLoading ? (
<Loader />
) : error ? (
<Message variant="danger">
{error?.data?.message || error.message}
</Message>
) : (
<>
<div className=" p-8">
<div className="max-w-4xl mx-auto">
<Link to="/" className="text-sm font-semibold text-gray-700 hover:underline mb-4 inline-block">
{t('go_back')}
</Link>
{isLoading ? (
<Loader />
) : error ? (
<Message variant="danger">
{error?.data?.message || error.message}
</Message>
) : (
<>
<div className="overflow-hidden py-12">
<div className="md:flex">
<div className="md:w-1/3">
<img src={product?.image} alt={product?.name} className="w-full h-auto object-cover" />
</div>
<div className="md:w-2/3 p-4">
<div className="flex justify-between items-start">
<h1 className="text-2xl font-bold text-gray-900 dark:text-slate-50">{product.name}</h1>
<HeartIcon />
</div>
<Ratings value={product.rating} text={`${product.numReviews} reviews`} />
<p className="text-gray-600 dark:text-slate-100 my-2">{product.description}</p>
<p className="text-lg font-semibold text-green-600">${product.price}</p>
{product.countInStock > 0 && (
<div className="my-4">
<label htmlFor="quantity" className="block mb-2 text-sm font-medium text-gray-700">Quantity</label>
<select id="quantity" value={qty} onChange={e => setQty(e.target.value)} className="block w-full p-2 border border-gray-300 rounded-md shadow-sm">
{[...Array(product.countInStock).keys()].map(x => (
<option key={x + 1} value={x + 1}>{x + 1}</option>
))}
</select>
</div>
)}
<div className="flex space-x-4">
<Button onClick={addToCartHandler} className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-md">
{t("add_to_cart")}
</Button>
</div>
</div>
</div>
<div className="mt-[5rem] container flex flex-wrap items-start justify-between">
<ProductTabs
loadingProductReview={loadingProductReview}
userInfo={userInfo}
submitHandler={submitHandler}
rating={rating}
setRating={setRating}
comment={comment}
setComment={setComment}
product={product}
/>
</div>
</div>
</>
)}
</div>
</div>
</>
)}
</section>
</>
);
};
export default ProductDetails; |
# RAII
## 背景:资源管理问题
操作系统的资源是有限的,当我们使用完资源后必须将该资源归还操作系统,因此使用资源的步骤包括:
* 获取资源
* 使用资源
* 释放资源
### 1. 堆内存
```c++
void foo() {
int *pBuf = new int[256];
if (!condition1) {
return; // 提前 return 存在内存泄漏风险
}
if (!condition2) {
bar(); // bar()抛出异常时可能导致资源未及时释放
}
delete []pBuf;
}
```
### 2. 文件句柄
```c++
void foo() {
FILE *pf = open("a.txt", "w");
// 写文件
fclose(pf);
}
```
### 3. 互斥量
```c++
void foo(void) {
static std::mutex m;
m.lock();
// 业务逻辑
m.unlock();
}
```
可以看到上述三种使用场景都遵循了获取-使用-释放的资源使用顺序,在使用资源过程中可能存在某个分支提前返回或者调用某个函数产生异常并抛出时导致资源未及时释放。
## 解决方案
对于上述三种情况,C++ 标准库提供了对应的解决方案,它们无一例外都是使用类来管理资源的:
* 内存管理使用智能指针:`std::unique_ptr`和`std::shared_ptr`
* 文件句柄管理使用文件流对象:`ifstream`、`ofstream`和`fstream`
* 互斥量管理:`std::lock_guard`、`std::unique_guard`和`std::shared_guard`
当离开作用域或者异常抛出时,栈上的对象会自动析构。对于上述实例,我们基于 RAII 的原则通过类来管理资源,并在栈上创建其对象,这样类构造的时候便会自动获取资源,而析构的时候会自动释放资源。
## RAII
### 1. 原理
RAII 全称是 Resource Acquisition Is Initialization,翻译为“资源获取就是初始化”,是 C++ 语言中的一种避免内存泄漏的最佳资源管理方法。由于 C++ 的语言机制保证了当一个对象创建时自动调用构造函数,当对象超出作用域时自动调用析构函数,RAII 要求我们使用类来管理资源,将资源与对象的生命周期绑定在一起(构造函数获取资源而析构函数释放资源)。
> 这里提到的系统资源指的都是受限资源,包括堆内存、文件句柄、线程、数据库链接、网络链接和互斥锁等,这些资源的数量不是无限的(甚至是独一份的),因此我们在使用资源后必须释放资源。
RAII 进行资源管理的步骤是:
* 构造一个资源管理类
* 在构造函数中获取资源
* 在析构函数中释放资源
* 在栈上创建类对象
* 离开作用域或异常抛出时,当前栈回溯从而析构对象释放资源
### 2. 与 GC 区别
和垃圾回收 GC 不同的是,RAII 可管理广义的资源,而 GC 算法只关心内存泄漏。不关心诸如文件句柄、互斥量等一些系统资源的泄漏问题。
## Reference
[1] <https://blog.csdn.net/quinta_2018_01_09/article/details/93638251>
[2] <https://www.cnblogs.com/jiangbin/p/6986511.html>
[3] <https://www.jianshu.com/p/3edd59f05174> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Yarno Bruggink</title>
<link rel="stylesheet" href="assets/css/styles.css" />
</head>
<body>
<nav class="navbar">
<div class="navbar-container">
<div class="navbar-links">
<a href="#" id="about-me-link">About Me</a>
<a href="#" id="portfolio-link">Portfolio</a>
</div>
</div>
</nav>
<div class="animated-background">
<div class="center">
<h1>
Hi <span class="h1-wave">👋</span>, I'm <span class="name">Yarno Bruggink</span>
</h1>
<p>
I'm a <span id="typed-text"></span><span class="blink">|</span>
</p>
<div class="social-icons">
<a href="https://github.com/Evoltr" target="_blank">
<img src="assets/icons/github.svg" alt="github">
</a>
<a href="https://www.linkedin.com/in/yarno-bruggink-698b1116b/" target="_blank">
<img src="assets/icons/linkedin.svg" alt="linkedin">
</a>
<a href="mailto:me@yarnobruggink.nl" target="_blank">
<img src="assets/icons/email.svg" alt="mail">
</a>
</div>
</div>
</div>
<div id="about-me-modal" class="modal">
<div class="modal-content">
<span class="close" id="close-about-me">×</span>
<h2>About Me</h2>
<p>
Hi, I'm Yarno Bruggink, a 24 year old tech enthusiast from the Netherlands with expertise in creating
modern and responsive websites.
With a strong foundation in front-end development, I enjoy transforming creative ideas into beautiful,
user-friendly digital experiences.
I love working with new technologies and constantly strive to improve my skills.
</p>
<h3>Programming Languages</h3>
<ul class="skills-list">
<li>
<div class="icon-text">
<img src="assets/icons/html.svg" alt="HTML Icon"> HTML
</div>
<div class="progress-bar">
<div class="progress" style="width: 80%;"></div>
</div>
</li>
<li>
<div class="icon-text">
<img src="assets/icons/css.svg" alt="CSS Icon"> CSS
</div>
<div class="progress-bar">
<div class="progress" style="width: 75%;"></div>
</div>
</li>
<li>
<div class="icon-text">
<img src="assets/icons/javascript.svg" alt="JavaScript Icon"> JavaScript
</div>
<div class="progress-bar">
<div class="progress" style="width: 60%;"></div>
</div>
</li>
<li>
<div class="icon-text">
<img src="assets/icons/java.svg" alt="Java Icon"> Java
</div>
<div class="progress-bar">
<div class="progress" style="width: 60%;"></div>
</div>
</li>
</ul>
<h3>Tools</h3>
<ul class="tools-list">
<li><img src="assets/icons/visual-studio-code.svg" alt="VSCode Icon"> VSCode</li>
<li><img src="assets/icons/git.svg" alt="Git Icon"> git</li>
<li><img src="assets/icons/npm.svg" alt="npm Icon"> npm</li>
<li><img src="assets/icons/chatgpt.svg" alt="AI Icon"> AI</li>
<li><img src="assets/icons/mysql.svg" alt="MySQL Icon"> MySQL</li>
<li><img src="assets/icons/nodejs.svg" alt="AI Icon"> NodeJS</li>
<li><img src="assets/icons/centos.svg" alt="CentOS Icon">CentOS</li>
<li><img src="assets/icons/bootstrap.svg" alt="Bootstrap Icon">Bootstrap</li>
</ul>
<p class="contact-text">
Want to work with me? I'm always up for a new challenge! <a href="mailto:me@yarnobruggink.nl">Contact
me</a>.
</p>
</div>
</div>
<div id="portfolio-modal" class="modal">
<div class="modal-content">
<span class="close" id="close-portfolio">×</span>
<h2>Portfolio</h2>
<p>Coming soonTM</p>
</div>
</div>
<script src="assets/js/script.js"></script>
</body>
</html> |
/*
* This file is part of ACE View.
* Copyright 2008-2009, Attempto Group, University of Zurich (see http://attempto.ifi.uzh.ch).
*
* ACE View is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* ACE View is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ACE View.
* If not, see http://www.gnu.org/licenses/.
*/
package ch.uzh.ifi.attempto.aceview.ui.view;
import java.awt.BorderLayout;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import org.protege.editor.owl.ui.view.AbstractOWLViewComponent;
import ch.uzh.ifi.attempto.aceview.ACETextManager;
import ch.uzh.ifi.attempto.aceview.lexicon.TokenMapper;
import ch.uzh.ifi.attempto.aceview.model.event.ACEViewEvent;
import ch.uzh.ifi.attempto.aceview.model.event.ACEViewListener;
import ch.uzh.ifi.attempto.aceview.model.event.TextEventType;
import ch.uzh.ifi.attempto.aceview.ui.util.ComponentFactory;
/**
* <p>This view component shows the ACE lexicon in the
* ACE lexicon format (which is understood by the ACE parser).</p>
*
* @author Kaarel Kaljurand
*
*/
public class ACELexiconFormatViewComponent extends AbstractOWLViewComponent {
private JTextArea textareaLexicon;
private final ACEViewListener<ACEViewEvent<TextEventType>> aceTextManagerListener = new ACEViewListener<ACEViewEvent<TextEventType>>() {
public void handleChange(ACEViewEvent<TextEventType> event) {
if (event.isType(TextEventType.ACELEXICON_CHANGED)) {
showLexicon();
}
else if (event.isType(TextEventType.ACTIVE_ACETEXT_CHANGED)) {
showLexicon();
}
}
};
@Override
protected void initialiseOWLView() throws Exception {
textareaLexicon = ComponentFactory.makeTextArea();
textareaLexicon.setLineWrap(true);
textareaLexicon.setWrapStyleWord(true);
setLayout(new BorderLayout());
add(BorderLayout.CENTER, new JScrollPane(textareaLexicon));
ACETextManager.getInstance().addListener(aceTextManagerListener);
showLexicon();
}
private void showLexicon() {
TokenMapper aceLexicon = ACETextManager.getInstance().getActiveACELexicon();
textareaLexicon.setText(aceLexicon.toACELexiconFormat());
int numberOfEntries = aceLexicon.size();
if (numberOfEntries == 1) {
setHeaderText("1 entry");
}
else {
setHeaderText(numberOfEntries + " entries");
}
}
@Override
protected void disposeOWLView() {
ACETextManager.getInstance().removeListener(aceTextManagerListener);
}
} |
import React from "react";
import styled from "styled-components";
const Wrap = styled.div`
display: grid;
width: 280px;
height: 280px;
grid-template-columns: 1fr 1fr 1fr;
border: solid 2px black;
`;
const InnerBox = styled.div`
border: solid 1px black;
display: flex;
justify-content: center;
align-items: center;
vertical-align: middle;
`;
const Input = styled.textarea`
font-family: "Poppins-Bold";
width: 100%;
height: 100%;
text-align: center;
border: 1px solid #000;
resize: none;
font-size: 12px;
font-weight: bold;
position: relative;
border: none;
outline: none;
`;
const Cover = styled.div`
height: 58%;
`;
function MainTable({ onKeyUp }) {
return (
<Wrap>
{Array(9)
.fill(1)
.map((_, i) => {
if (i === 4) {
return (
<InnerBox key={i}>
<Cover>
<Input placeholder="메인 목표" maxLength={14} />
</Cover>
</InnerBox>
);
} else {
return (
<InnerBox key={i}>
<Cover>
<Input
placeholder="세부 목표"
maxLength={14}
onKeyUp={(event) => {
onKeyUp(event, i);
}}
/>
</Cover>
</InnerBox>
);
}
})}
</Wrap>
);
}
export default MainTable; |
from dataclasses import dataclass, field
from ts3l.utils import BaseConfig
from typing import Any, List, Optional
@dataclass
class DAEConfig(BaseConfig):
""" Configuration class for initializing components of the DAELightning Module, including hyperparameters of Denoising AutoEncoder,
optimizers, learning rate schedulers, and loss functions, along with their respective hyperparameters.
Inherits Attributes:
task (str): Specify whether the problem is regression or classification.
input_dim (int): The dimension of the input.
output_dim (int): The dimension of output.
loss_fn (str): Name of the loss function to be used. Must be an attribute of 'torch.nn'.
optim (str): Name of the optimizer to be used. Must be an attribute of 'torch.optim'. Default is 'AdamW'.
optim_hparams (Dict[str, Any]): Hyperparameters for the optimizer. Default is {'lr': 0.0001, 'weight_decay': 0.00005}.
scheduler (str): Name of the learning rate scheduler to be used. Must be an attribute of 'torch.optim.lr_scheduler' or None. Default is None.
scheduler_hparams (Dict[str, Any]): Hyperparameters for the scheduler. Default is None, indicating no scheduler is used.
loss_hparams (Dict[str, Any]): Hyperparameters for the loss function. Default is empty dictionary.
metric (str): Name of the metric to be used. Must be an attribute of 'torchmetrics.functional' or 'sklearn.metrics'. Default is None.
metric_hparams (Dict[str, Any]): Hyperparameters for the metric. Default is an empty dictionary.
random_seed (int): Seed for random number generators to ensure reproducibility. Defaults to 42.
New Attributes:
hidden_dim (int): The dimension of hidden layer. Default is 256.
encoder_depth (bool): The depth of encoder. Default is 4.
head_depth (bool): The depth of head. Default is 2.
noise_type (str): The type of noise to apply. Choices are ["Swap", "Gaussian", "Zero_Out"].
noise_level (float): Intensity of Gaussian noise to be applied.
noise_ratio (float): A hyperparameter that is to control the noise ratio during the first phase learning. Default is 0.3.
mask_loss_weight (float): The special token for unlabeled samples.
dropout_rate (bool): A hyperparameter that is to control dropout layer. Default is 0.04.
num_categoricals (int): The number of categorical features.
num_continuous (int): The number of continuous features.
Raises:
ValueError: Inherited from `BaseConfig` to indicate that a configuration for the task, optimizer, scheduler, loss function, or metric is either invalid or not specified.
ValueError: If the specified 'noise_type' is not in ["Swap", "Gaussian", "Zero_Out"].
ValueError: If the specified 'noise_level' is not a valid value.
ValueError: Raised if both `num_categoricals` and `num_continuous` are None, indicating that at least one attribute must be specified.
"""
hidden_dim: int = field(default=256)
encoder_depth: int = field(default=4)
head_depth: int = field(default=2)
noise_type: str = field(default="Swap")
noise_level: float = field(default=0)
noise_ratio: float = field(default=0.3)
mask_loss_weight: float = field(default=1.0)
dropout_rate: float = field(default=0.04)
num_categoricals: Optional[int] = field(default=None)
num_continuous: Optional[int] = field(default=None)
def __post_init__(self):
super().__post_init__()
if self.noise_type not in ["Swap", "Gaussian", "Zero_Out"]:
raise ValueError('The noise type must be one of ["Swap", "Gaussian", "Zero_Out"], but %s.' % self.noise_type)
if (self.noise_type == "Gaussian") and ((self.noise_level == None) or (self.noise_level <= 0)):
raise ValueError("The noise level must be a float that is > 0 when the noise type is Gaussian.")
if self.num_categoricals is None and self.num_continuous is None:
raise ValueError("At least one attribute (num_categorical or num_continuous) must be specified.")
else:
self.num_categoricals = self.num_categoricals if self.num_categoricals is not None else 0
self.num_continuous = self.num_continuous if self.num_continuous is not None else 0 |
import { effect, stop } from "../src/effect"
import { reactive } from "../src/reactive"
import { vi } from 'vitest'
describe('effect', () => {
it('happy path', () => {
const obj = reactive({ foo: 1 })
let num
let doubleNum
// init
effect(() => {
num = obj.foo + 1
})
effect(() => {
doubleNum = obj.foo * 2
})
expect(num).toBe(2)
expect(doubleNum).toBe(2)
// update
obj.foo = 10
expect(num).toBe(11)
expect(doubleNum).toBe(20)
})
it("should return runner when call effect", () => {
let a = 1
const runner = effect(() => {
a++
return 'hello effect runner'
})
expect(a).toBe(2)
const r = runner()
expect(a).toBe(3)
expect(r).toBe('hello effect runner')
})
it('scheduler', () => {
let x = 0
const obj = reactive({ a: 1 })
let run: Function = () => { }
const scheduler = vi.fn(() => {
run = runner
})
const runner = effect(
() => {
x = obj.a
},
{ scheduler }
)
// init
expect(x).toBe(1)
expect(scheduler).not.toHaveBeenCalled()
// update
obj.a++
expect(x).toBe(1)
expect(scheduler).toHaveBeenCalledTimes(1)
// call update
run()
expect(x).toBe(2)
expect(scheduler).toHaveBeenCalledTimes(1)
// update
obj.a++
expect(x).toBe(2)
expect(scheduler).toHaveBeenCalledTimes(2)
})
it('stop', () => {
let res = 0
const obj = reactive({ a: 1 })
const runner = effect(() => {
res = obj.a
})
expect(res).toBe(1)
obj.a = 10
expect(res).toBe(10)
stop(runner)
obj.a = 100
expect(res).toBe(10)
obj.a++
expect(res).toBe(10)
runner()
expect(res).toBe(101)
})
it('onStop', () => {
let res = 0
const obj = reactive({ a: 1 })
const onStop = vi.fn()
const runner = effect(
() => { res = obj.a },
{ onStop }
)
expect(res).toBe(1)
obj.a = 10
expect(res).toBe(10)
expect(onStop).not.toHaveBeenCalled()
stop(runner)
obj.a = 100
expect(res).toBe(10)
expect(onStop).toBeCalledTimes(1)
runner()
expect(res).toBe(100)
expect(onStop).toBeCalledTimes(1)
})
}) |
import { createContext, useReducer, useState } from "react";
export const cartContext = createContext({
items: [],
totalAmount: 0,
});
export const CartProvider = ({ children }) => {
const [cartState, setCartState] = useState([]);
const amount = cartState.reduce((prev, current) => prev + current.amount, 0);
const totalPrice = cartState.reduce(
(prev, current) => prev + current.price * current.amount,
0
);
function addItem(data) {
if (!cartState.length) {
return setCartState([data]);
}
const isExist = cartState.find((item) => item.title === data.title);
if (!isExist) {
return setCartState([...cartState, data]);
}
const updateItem = cartState.map((item) => {
if (item.id === data.id) {
return {
...item,
amount: item.amount + data.amount,
};
}
return item;
});
setCartState([...updateItem]);
}
console.log(cartState);
function increment(id) {
const updateItem = cartState.map((item) => {
if (item.id === id) {
return {
...item,
amount: item.amount + 1,
};
}
return item;
});
setCartState([...updateItem]);
}
function decrement(id) {
const updateItem = cartState.map((item) => {
if (item.id === id && item.amount !== 0) {
return {
...item,
amount: item.amount - 1,
};
}
return item;
});
setCartState([...updateItem]);
}
const cartValue = {
items: cartState,
totalAmount: amount,
totalPrice: totalPrice,
addItem,
increment,
decrement,
};
return (
<cartContext.Provider value={cartValue}>{children}</cartContext.Provider>
);
}; |
<div class="form_title text-center">
{% if section.settings.title != blank %}
<h1 class="text-5xl text-center py-40 mb-8 bg-gray-700 text-white">
{{ section.settings.title }}
</h1>
{% endif %}
</div>
<div class="container mx-auto flex flex-col items center my-9 h-full justify-center ">
{% form 'contact' %}
<div class="max-w-6xl mx-auto justify-center flex-1 items-center px-4">
{% comment %} error show {% endcomment %}
{% if form.errors %}
<div class="border p-5 ">
<div class="flex flex-row items-center w-full my-3 justify-center">
<div class="text-red-500">
{% render 'icon-failed' %}
</div>
<div class="text-sm font-medium ml-3">
Your Message Was Not Posted
</div>
</div>
<ul class="px-4 flex justify-center my-3">
{% for error in form.errors %}
<li class="font-bold">{{ form.errors.messages[error] }}</li>
{% endfor %}
</ul>
</div>
{% elsif form.posted_successfully? %}
<div class=" p-5">
<div class="flex flex-row items-center w-full my-3 justify-center">
<div class="text-red-500">
{% render 'icon-success' %}
</div>
<div class="text-sm font-medium ml-3">
Your Message Was Posted Successfully
</div>
</div>
</div>
{% endif %}
{% comment %} error show {% endcomment %}
<div class="flex px-1 mb-3">
<div class="px-3 md:w-1/2">
<label class="uppercase text-xs text-gray-500 font-medium" for="contact_name">Name</label>
<input
class="border py-3 px-4 mb-3 text-gray-700 w-full"
type="text"
name="contact[name]"
id="contact_name">
</div>
<div class="px-3 md:w-1/2">
<label class="uppercase text-xs text-gray-500 font-medium" for="contact_email">Email address</label>
<input
class="border py-3 px-4 mb-3 text-gray-700 w-full"
type="email"
name="contact[email]"
id="contact_email">
</div>
</div>
<div class="flex px-1 mb-3">
<div class="w-full px-3">
<label class="uppercase text-xs text-gray-500 font-medium" for="contact_message">Message</label>
<textarea
class="border py-3 px-4 mb-3 text-gray-700 w-full"
name="contact[body]"
id="contact_message"></textarea>
</div>
</div>
<div class="flex px-1 mb-3">
<div class="w-full px-3">
<input
type="submit"
class="w-full cursor-pointer px-4 py-2 border text-base font-medium bg-gray-900 text-white hover:bg-gray-700"
value="Submit message">
</div>
</div>
</div>
{% endform %}
</div>
{% schema %}
{
"name": "contact form",
"settings": [
{
"type": "text",
"id": "title",
"label": "Contact Form"
}
],
"presets": [
{
"name": "contact form"
}
]
}
{% endschema %} |
/* eslint-disable */
import React, {Component, Fragment} from 'react';
import PropTypes from 'prop-types'
import vmsg from 'vmsg';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
import {faMicrophone, faFileUpload, faStop, faTrashAlt} from '@fortawesome/free-solid-svg-icons'
import {isEmpty} from 'lodash'
import {CreateSequenceInstructions} from '../CreateSequenceInstructions'
import {step3Skipped} from '../../actions/create2'
import {audioAdded} from '../../actions/create2'
import HeaderWithNavigationContainer from '../../containers/Shared/HeaderWithNavigationContainer'
import {Headers} from '../../constants/attributes'
import {goToCreatePhotoPage} from '../../actions/navigation'
import connect from 'react-redux/es/connect/connect'
const recorder = new vmsg.Recorder({
wasmURL: 'https://unpkg.com/vmsg@0.3.0/vmsg.wasm'
});
class AudioPage2 extends Component {
static propTypes = {
loadAudio: PropTypes.func,
}
constructor(props) {
super(props)
this.state = {
readyToSubmit: false,
isLoading: false,
isRecording: false,
recording: this.props.audioSrc,
file: null
}
}
record = async () => {
this.setState({isLoading: true});
if (this.state.isRecording) {
const blob = await recorder.stopRecording();
const file = new File([blob], 'blob.mp3', {type: 'audio/mpeg', lastModified: Date.now()});
this.setState({
isLoading: false,
isRecording: false,
recording: URL.createObjectURL(blob),
file: file,
readyToSubmit: true
})
return this.props.loadAudio(this.state.recording)
} else {
try {
await recorder.initAudio();
await recorder.initWorker();
recorder.startRecording();
this.setState({isLoading: false, isRecording: true});
} catch (e) {
console.error(e);
this.setState({isLoading: false});
}
}
}
onAudioChosen = (e) => {
const file = e.target.files[0];
this.setState({
recording: URL.createObjectURL(file),
readyToSubmit: true,
file: file
})
return this.props.loadAudio(URL.createObjectURL(file))
}
render() {
const {isRecording, recording} = this.state;
const recordingElement = isRecording ?
//TODO INSERT TIMER HERE//
<a className='button is-medium is-danger is-inverted is-fullwidth' onClick={this.record}>
<span className="icon is-large">
<FontAwesomeIcon icon={faStop}/>
STOP RECORDING
</span>
</a>
:
<a className='button is-medium is-light is-fullwidth' onClick={this.record}>
<span className="icon is-large">
<FontAwesomeIcon icon={faMicrophone}/>
RECORD
</span>
</a>
const uploadElement = isEmpty(recording) ?
<div>
<input className="file-input" type="file" accept="audio/*" onChange={this.onAudioChosen} capture
id="recorder"/>
<span className="file-cta icon is-large">
<span className="icon is-large">
<FontAwesomeIcon icon={faFileUpload}/>
</span>
<span className="file-label">UPLOAD AUDIO</span>
</span>
</div>
: null
return (
<Fragment>
<HeaderWithNavigationContainer
displayBackButton={true}
displayNextButton={true}
title={Headers.DEEPMAPPER}
readyToSubmit={this.state.readyToSubmit}
onBack={goToCreatePhotoPage()}
onNext={dispatch => (dispatch(step3Skipped()))}/>
<CreateSequenceInstructions stepNumber='3'/>
{recordingElement}
{uploadElement}
</Fragment>
)
}
}
export const mapDispatchToProps = (dispatch) => {
return {
loadAudio: (file) => dispatch(audioAdded(file)),
}
}
export default connect(null, mapDispatchToProps)(AudioPage2); |
/*
Filename: MainMenuScreen.h
Author: Miguel Angel Quinones (mikeskywalker007@gmail.com)
Description: Implementation of a screen in game - MAINMENUSCREEN
Comments: Dependant of IndieLib Graphics library - derived from abtract class "GameScreen"
Attribution:
License: You are free to use as you want... but it can destroy your computer, so dont blame me about it ;)
Nevertheless it would be nice if you tell me you are using something I made, just for curiosity
*/
#ifndef _MAINMENUSCREEN
#define _MAINMENUSCREEN
//Library dependencies
//Class dependencies
#include "GameScreen.h"
#include "HighScores.h"
class MainMenuScreen : public GameScreen
{
protected:
typedef enum ScreenSelection{SEL1,SEL2,SEL3,SEL4,NOTHING}ScreenSelection;
public:
//----- CONSTRUCTORS/DESTRUCTORS -----
MainMenuScreen(IndieLibManager* pIlib):GameScreen(pIlib),mSelection(NOTHING)
{
_init();
SingletonLogMgr::Instance()->AddNewLine("MainMenuScreen","MainMenuScreen screen loaded",DEBUG);
}
virtual ~MainMenuScreen()
{
_release();
SingletonLogMgr::Instance()->AddNewLine("MainMenuScreen","MainMenuScreen screen released",DEBUG);
}
//----- GET/SET FUNCTIONS -----
//----- OTHER FUNCTIONS -----
//Implementations from base class
virtual void ExecuteEnter();
virtual void ExecuteLogicUpdate(float dt);
virtual void ExecuteRender();
virtual void ExecuteExit();
virtual GameState IsExit();
//----- PUBLIC VARIABLES ------
protected:
//----- INTERNAL VARIABLES -----
ScreenSelection mSelection;
char mHighScores[NUMBEROFHIGHSCORES*10];
//----- INTERNAL FUNCTIONS -----
void _init();//Internal init
void _release(); //Internal release
void _readHighScores(); //Read high scores from file
};
#endif |
import { Injectable, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
/* observe destroy服务*/
/* 使用方式:*/
/*
@Component({
selector: 'app-search-route',
templateUrl: './search-route.component.html',
styleUrls: ['./search-route.component.less'],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [DestroyService]
})
* constructor( private destroy$: DestroyService ) {}
* some$.pipe( takeUntil(this.destroy$)).subscribe(...)
*
* */
@Injectable()
export class DestroyService extends Subject<void> implements OnDestroy {
ngOnDestroy(): void {
this.next();
this.complete();
}
} |
import { ButtonHTMLAttributes, DetailedHTMLProps, FC, ReactNode } from "react"
interface ButtonProps {
children?: ReactNode
className?: String
onClick?: () => void
disabled?: boolean
buttonProps?: DetailedHTMLProps<
ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement
>
}
const Button: FC<ButtonProps> = ({
children,
className,
disabled,
buttonProps,
onClick,
}) => {
return (
<button
{...buttonProps}
className={
"active:translate-y-0 text-white font-bold py-2 px-4 rounded focus:outline-none hover:-translate-y-1 transition-transform shadow-md hover:shadow-lg active:shadow-md " +
(className ?? "")
}
disabled={disabled ?? false}
onClick={onClick}
>
<div className={`flex gap-2 items-center justify-center `}>
{children}
</div>
</button>
)
}
export default Button |
import org.junit.Test;
import static org.junit.Assert.*;
public class BenutzerPoolTest {
@Test
public void testAddBenutzer() {
BenutzerPool benutzerPool = new BenutzerPool();
Spieler spieler = new Spieler("Benutzer1");
benutzerPool.addBenutzer(spieler);
assertEquals(1, benutzerPool.getBenutzer().size());
assertTrue(benutzerPool.getBenutzer().contains(spieler));
}
@Test
public void testRemoveBenutzer() {
BenutzerPool benutzerPool = new BenutzerPool();
Spieler spieler1 = new Spieler("Benutzer1");
Spieler spieler2 = new Spieler("Benutzer2");
benutzerPool.addBenutzer(spieler1);
benutzerPool.addBenutzer(spieler2);
benutzerPool.removeBenutzer(spieler1);
assertEquals(1, benutzerPool.getBenutzer().size());
assertFalse(benutzerPool.getBenutzer().contains(spieler1));
assertTrue(benutzerPool.getBenutzer().contains(spieler2));
}
}
Dokumentation:
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Die Klasse "BenutzerPoolTest" enthält JUnit-Tests für die Klasse "BenutzerPool".
*/
public class BenutzerPoolTest {
/**
* Testet die Methode "addBenutzer" der Klasse "BenutzerPool".
* Überprüft, ob ein Spieler erfolgreich zur Liste hinzugefügt wird.
*/
@Test
public void testAddBenutzer() {
BenutzerPool benutzerPool = new BenutzerPool();
Spieler spieler = new Spieler("Benutzer1");
benutzerPool.addBenutzer(spieler);
assertEquals(1, benutzerPool.getBenutzer().size());
assertTrue(benutzerPool.getBenutzer().contains(spieler));
}
/**
* Testet die Methode "removeBenutzer" der Klasse "BenutzerPool".
* Überprüft, ob ein Spieler erfolgreich aus der Liste entfernt wird.
*/
@Test
public void testRemoveBenutzer() {
BenutzerPool benutzerPool = new BenutzerPool();
Spieler spieler1 = new Spieler("Benutzer1");
Spieler spieler2 = new Spieler("Benutzer2");
benutzerPool.addBenutzer(spieler1);
benutzerPool.addBenutzer(spieler2);
benutzerPool.removeBenutzer(spieler1);
assertEquals(1, benutzerPool.getBenutzer().size());
assertFalse(benutzerPool.getBenutzer().contains(spieler1));
assertTrue(benutzerPool.getBenutzer().contains(spieler2));
}
}
Diese Dokumentation enthält eine Beschreibung der Testklasse "BenutzerPoolTest" sowie der einzelnen Testmethoden "testAddBenutzer" und "testRemoveBenutzer". Die Tests überprüfen, ob die Methoden "addBenutzer" und "removeBenutzer" der Klasse "BenutzerPool" wie erwartet funktionieren. Die JUnit-Assert-Methoden werden verwendet, um die erwarteten Ergebnisse zu überprüfen. |
-- Passwort-Check fuer BA-User gemaess BA-Richtlinien
-- gsi 29.7.2015
--
-- mindestens 8 Zeichen
-- mindestens 1 Zahl
-- mindestens 1 Sonderzeichen
-- mindestens 1 Grossbuchstabe
-- mindestens 1 Kleinbuchstabe
-- Add_on:
-- Passwort nicht gleich User-Id
--> funktioniert nicht weil create/alter user die User-ID in GROSSBUCHSTABEN uebergibt
-- Passwort nicht gleich altem Passwort
--> wird schon vom profile abgefangen, nicht notwendig in der Funktion
-- Passwort muss sich in mindestens 3 Stellen vom alten Passwort unterscheiden
--> funktioniert nicht weil create/alter user das alte Passwort nicht uebergibt!!!!
set serveroutput on;
CREATE OR REPLACE FUNCTION pw_verify_ba_user (
username IN VARCHAR2,
password IN VARCHAR2,
old_password IN VARCHAR2)
RETURN BOOLEAN
IS
chararraylower VARCHAR2(52);
chararrayupper VARCHAR2(52);
differ INTEGER;
digitarray VARCHAR2(20);
ischarlower BOOLEAN;
ischarupper BOOLEAN;
isdigit BOOLEAN;
ispunct BOOLEAN;
m INTEGER;
n BOOLEAN;
punctarray VARCHAR2(25);
BEGIN
digitarray := '0123456789';
chararraylower := 'abcdefghijklmnopqrstuvwxyz';
chararrayupper := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
punctarray := '!"#$%&()''*+,-/:;<=>?_';
-- check for password identical with userid
IF password = username THEN
DBMS_OUTPUT.PUT_LINE('--> Das Passwort ist identisch zur User-Id');
raise_application_error(-20001, 'Das Passwort ist identisch zur User-Id');
END IF;
-- check for new password identical with old password
IF UPPER(password) = UPPER(old_password) THEN
DBMS_OUTPUT.PUT_LINE('--> Das neue Passwort muss sich vom alten Passwort unterscheiden');
raise_application_error(-20002, 'Das neue Passwort muss sich vom alten Passwort unterscheiden');
END IF;
-- check for minimum password length
IF LENGTH(password) < 8 THEN
DBMS_OUTPUT.PUT_LINE('--> Das Passwort muss aus mindestens 8 Zeichen bestehen');
raise_application_error(-20003, 'Das Passwort muss aus mindestens 8 Zeichen bestehen',FALSE);
END IF;
<<finddigit>>
isdigit := FALSE;
m := LENGTH(password);
FOR i IN 1..10 LOOP
FOR j IN 1..m LOOP
IF SUBSTR(password,j,1) = SUBSTR(digitarray,i,1) THEN
isdigit := TRUE;
GOTO findcharlower;
END IF;
END LOOP;
END LOOP;
IF isdigit = FALSE THEN
DBMS_OUTPUT.PUT_LINE('--> Das Passwort muss mindestens 1 Ziffer enthalten');
raise_application_error(-20004, 'Das Passwort muss mindestens 1 Ziffer enthalten');
END IF;
<<findcharlower>>
ischarlower := FALSE;
FOR i IN 1..LENGTH(chararraylower) LOOP
FOR j IN 1..m LOOP
IF SUBSTR(password,j,1) = SUBSTR(chararraylower,i,1) THEN
ischarlower := TRUE;
GOTO findcharupper;
END IF;
END LOOP;
END LOOP;
IF ischarlower = FALSE THEN
DBMS_OUTPUT.PUT_LINE('--> Das Passwort muss mindestens einen Kleinbuchstaben enthalten');
raise_application_error(-20005, 'Das Passwort muss mindestens einen Kleinbuchstaben enthalten');
END IF;
<<findcharupper>>
ischarupper := FALSE;
FOR i IN 1..LENGTH(chararrayupper) LOOP
FOR j IN 1..m LOOP
IF SUBSTR(password,j,1) = SUBSTR(chararrayupper,i,1) THEN
ischarupper := TRUE;
GOTO findpunct;
END IF;
END LOOP;
END LOOP;
IF ischarupper = FALSE THEN
DBMS_OUTPUT.PUT_LINE('--> Das Passwort muss mindestens einen Grossbuchstaben enthalten');
raise_application_error(-20006, 'Das Passwort muss mindestens einen Grossbuchstaben enthalten');
END IF;
<<findpunct>>
ispunct := FALSE;
FOR i IN 1..LENGTH(punctarray) LOOP
FOR j IN 1..m LOOP
IF SUBSTR(password,j,1) = SUBSTR(punctarray,i,1) THEN
ispunct := TRUE;
GOTO endsearch;
END IF;
END LOOP;
END LOOP;
IF ispunct = FALSE THEN
DBMS_OUTPUT.PUT_LINE('--> Das Passwort muss mindestens 1 Sonderzeichen enthalten');
raise_application_error(-20007, 'Das Passwort muss mindestens 1 Sonderzeichen enthalten');
END IF;
<<endsearch>>
-- Make sure new password differs from old by at least three characters
IF old_password = '' THEN
raise_application_error(-20008, 'Das alte Passwort ist leer');
END IF;
differ := LENGTH(old_password) - LENGTH(password);
IF ABS(differ) < 3 THEN
IF LENGTH(password) < LENGTH(old_password) THEN
m := LENGTH(password);
ELSE
m := LENGTH(old_password);
END IF;
differ := ABS(differ);
FOR i IN 1..m LOOP
IF SUBSTR(password,i,1) != SUBSTR(old_password,i,1) THEN
differ := differ + 1;
END IF;
END LOOP;
IF differ < 3 THEN
DBMS_OUTPUT.PUT_LINE('--> Die Passworte muessen sich mindestens in 3 Stellen unterscheiden');
raise_application_error(-20009, 'Die Passworte muessen sich mindestens in 3 Stellen unterscheiden');
END IF;
END IF;
-- Everything is fine; return TRUE
DBMS_OUTPUT.PUT_LINE('--> Das Passwort entspricht den BA-Richtlinien');
RETURN(TRUE);
--EXCEPTION WHEN OTHERS THEN
-- RETURN(FALSE);
END;
/ |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment15
{
internal class Program
{
public static void BubbleSort(int[] arr)
{
int n = arr.Length;
int noSwap = 0;
for (int i = 0; i < n - 1; i++)
{
bool swapped = false;
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] < arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
noSwap++;
}
if (!swapped)
{
break;
}
}
}
public static void print(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i] + " ");
}
Console.WriteLine("\n");
}
static bool IsSorted(int[] arr)
{
for (int i = 0; i < arr.Length - 1; i++)
{
if (arr[i] < arr[i + 1])
return false;
}
return true;
}
static int BinarySearch(int[] arr, int target)
{
int left = 0;
int right = arr.Length - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == target)
{
return mid;
}
else if (arr[mid] > target)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
static void Main(string[] args)
{
Console.Write("Enter the size of the array: ");
int size = int.Parse(Console.ReadLine());
int[] arr = new int[size];
Console.WriteLine("Enter the elements of the array:");
for (int i = 0; i < size; i++)
{
Console.Write($"Element {i + 1}: ");
arr[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Print Array without Sort");
print(arr);
BubbleSort(arr);
Console.WriteLine("After Bubble Sort");
print(arr);
bool isSorted = IsSorted(arr);
Console.WriteLine($"\nIs the array sorted correctly? {isSorted}");
Console.Write("\nEnter the element to search: ");
int searchElement = int.Parse(Console.ReadLine());
int index = BinarySearch(arr, searchElement);
if (index != -1)
{
Console.WriteLine($"\nElement {searchElement} found at index {index}.");
}
else
{
Console.WriteLine($"\nElement {searchElement} not found in the array.");
}
Console.ReadKey();
}
}
} |
import { useMemo, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { actions as eventActions } from "../../features/events";
import { actions as selectedActions } from "../../features/selected";
import { Button, IconButton, TextField, Typography } from "@mui/material";
import { LocalizationProvider } from "@mui/x-date-pickers";
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { TimePicker } from '@mui/x-date-pickers/TimePicker';
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import DeleteIcon from '@mui/icons-material/Delete';
import dayjs from "dayjs";
import _ from 'lodash';
import './EventForm.scss'
export const EventForm = ({ closeModal }) => {
const dispatch = useDispatch();
const selected = useSelector(state => state.selected);
const [title, setTitle] = useState(selected.title || '');
const [description, setDescription] = useState(selected.description || '');
const [dateTime, setDateTime] = useState(dayjs(selected.dateTime) || dayjs())
const isValid = useMemo(() => {
if (!title) {
return false;
}
if (!dateTime) {
console.log('null')
return false
}
if (!dateTime.isValid()) {
console.log('not valid')
return false;
}
return true;
}, [title, dateTime]);
const isSelected = useMemo(() => {
return !_.isEmpty(selected);
}, [selected])
const clearForm = () => {
setTitle('')
setDescription('')
setDateTime(dayjs())
};
const removeEvent = (eventId) => {
dispatch(selectedActions.removeSelected());
dispatch(eventActions.deleteEvent(eventId));
closeModal();
};
const addEvent = () => {
const newEvent = {
id: selected.id || dayjs().valueOf(),
title,
description,
dateTime: dateTime.valueOf(),
};
dispatch(eventActions.addEvent(newEvent));
clearForm();
closeModal();
};
const updateEvent = () => {
const updatedEvent = {
id: selected.id,
title,
description,
dateTime: dateTime.valueOf(),
};
dispatch(eventActions.updateEvent(updatedEvent));
clearForm();
closeModal();
};
return (
<form className="event-form">
<Typography
variant="h5"
component="h2"
>
{isSelected ? 'Update event' : 'Create event'}
</Typography>
<TextField
label="Title *"
value={title}
onChange={e => setTitle(e.target.value)}
variant="standard"
fullWidth
/>
<TextField
label="Description"
value={description}
onChange={e => setDescription(e.target.value)}
variant="standard"
fullWidth
multiline
/>
<div className="event-form__date-time-group">
<LocalizationProvider
dateAdapter={AdapterDayjs}
>
<DatePicker
label="Date *"
inputFormat="DD.MM.YYYY"
value={dateTime}
minDate={dayjs()}
onChange={setDateTime}
renderInput={(params) => <TextField {...params} />}
/>
<TimePicker
label="Time"
value={dateTime}
onChange={setDateTime}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
</div>
<div className="event-form__buttons">
{isSelected && (
<IconButton
aria-label="delete"
onClick={() => {removeEvent(selected.id)}}
>
<DeleteIcon />
</IconButton>
)}
<Button
variant="contained"
disabled={!isValid}
onClick={isSelected ? updateEvent : addEvent}
>
{isSelected ? 'Update' : 'Save'}
</Button>
</div>
</form>
);
}; |
import React from "react";
import { View, Text, StyleSheet } from "react-native";
import { useDispatch } from "react-redux";
import { resetResponse, setResponse } from "../redux/appReducer";
import { IResponse } from "../models/interfaces/Response";
interface SnackbarProps {
response: IResponse;
}
const Snackbar: React.FC<SnackbarProps> = (props) => {
const [isVisible, setIsVisible] = React.useState<boolean>(true);
const dispatch = useDispatch();
const duration = 2000;
const reponse = props.response;
React.useEffect(() => {
setIsVisible(true);
const timer = setTimeout(() => {
setIsVisible(false);
dispatch(resetResponse());
}, duration);
return () => clearTimeout(timer);
}, [props.response]);
return (
<React.Fragment>
{isVisible && props.response.message !== "" && (
<View
style={[
styles.snackbar,
{
backgroundColor:
props.response.status === "success"
? "green"
: props.response.status === "error"
? "red"
: "yellow",
},
]}
>
<Text>{props.response.message}</Text>
</View>
)}
</React.Fragment>
);
};
const styles = StyleSheet.create({
snackbar: {
backgroundColor: "red",
width: "100%",
height: 60,
position: "absolute",
bottom: 0,
},
});
export default Snackbar; |
import Banner from "@/components/Banner";
import SectionName from "@/components/SectionName";
import OurTeam from "@/components/aboutpage/OurTeam";
import OurValues from "@/components/aboutpage/OurValues";
import Image from "next/image";
import React from "react";
import { FaArrowRight } from "react-icons/fa6";
const data = [
{
id: 1,
text: "Transforming Digital Landscapes, One Innovation",
},
{
id: 2,
text: "Pioneering Digital Excellence for Impact",
},
{
id: 3,
text: "Unleashing Possibilities in the Digital Realm",
},
];
const About = () => {
return (
<main
className="w-full mb-20 pt-[119px]"
style={{
backgroundImage:
"linear-gradient(180deg, #1E1E1E 12.88%, rgba(0, 0, 0, 0) 100%)",
backgroundSize: "100% 860px",
backgroundRepeat: "no-repeat",
}}
>
{/* HEADER */}
<div className="w-full lg:mb-[60px] text-center ">
<h1 className="text-2xl md:text-[50px] font-monument mb-3.5">
About <span className="text-accent">Us</span>
</h1>
<p className="font-medium lg:text-lg">
Any question or remarks? React out to us!
</p>
</div>
{/* WHO WE ARE */}
<div className="w-full mt-20 pb-5 relative lg:mb-[73px]">
<SectionName>who we are</SectionName>
<div className="flex md:w-[90%] w-[85%] mx-auto">
{/* <svg
className="w-4 h-40 mr-1.5 md:w-8 md:h-72 lg:hidden"
viewBox="0 0 30 304"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M0 14.6582C0 14.6582 5.61655 11.4155 8.51603 8.51604C11.4155 5.61656 14.6582 6.90328e-06 14.6582 6.90328e-06C14.6582 6.90328e-06 17.9009 5.61656 20.8004 8.51604C23.6998 11.4155 29.3164 14.6582 29.3164 14.6582C29.3164 14.6582 23.6998 17.9009 20.8004 20.8004C17.9009 23.6998 14.6582 29.3164 14.6582 29.3164C14.6582 29.3164 11.4155 23.6998 8.51603 20.8004C5.61655 17.9009 0 14.6582 0 14.6582Z"
fill="#A3A3A3"
/>
<path
d="M14.5001 49.3164L16 140.949L14.5 303.949L13 140.949L14.5001 49.3164Z"
fill="#E5E5E5"
/>
</svg> */}
<div className="w-full lg:flex">
<h1 className="text-2xl md:text-5xl leading-[1.32] md:leading-[1.32] font-monument lg:w-[55%]">
We offer several <span className="text-accent">Services</span> for
you
</h1>
<hr className="my-3" />
<div className="flex w-full justify-between items-center lg:block lg:w-[45%]">
<p className="line-clamp-3 text-xs md:text-lg font-medium w-4/6 lg:w-full lg:mb-5">
Lorem ipsum dolor sit amet consectetur. Lacus orci cursus ut
magnis quam ullamcorper eget leo. Sed diam lacus ultrices
egestas elit ultrices nisl vitae.
</p>
<button className="rounded-full bg-white-20 px-3 py-2 md:py-3.5 md:px-4 flex items-center text-[7px] md:text-sm font-medium text-nowrap shadow transition duration-200 ease-in-out transform hover:bg-white/10 active:scale-95">
Explore Our Service
<span className="ml-1.5 nd:ml-3">
<FaArrowRight />
</span>
</button>
</div>
</div>
</div>
</div>
{/* CARD */}
<div
className="mx-auto max-w-7xl w-[90%] mb-[61px] rounded-t-[20px] overflow-hidden"
style={{
background:
"linear-gradient(180deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0) 100%)",
}}
>
<div className="relative w-full h-[259px] mb-5 ">
<Image
src={"/aboutus.png"}
fill
alt="about"
className="object-cover"
style={{ objectFit: "cover" }}
/>
{/* OVERLAY OVER IMAGE */}
<div
className="absolute top-0 left-0 right-0 bottom-0"
style={{
background:
"linear-gradient(180deg, rgba(0,0,0,0.8) 2.67%, rgba(0,0,0,0.48)) 100%",
}}
></div>
</div>
<div className="lg:flex lg:gap-12 px-8 max-w-7xl mx-auto">
<div className="min-w-[300px]">
<h2 className="font-monument text-xl md:text-4xl text-center mb-6">
Our Vision
</h2>
<p className="font-medium text-xs md:text-sm text-justify">
To be a leading digital agency, empowering businesses with
innovative solutions that transcend the digital realm. We envision
a future where our strategic insights, creative brilliance, and
technological expertise converge to drive unparalleled success for
our clients.
</p>
</div>
<div className="mt-8 lg:mt-0">
<h2 className="font-monument text-xl md:text-4xl text-center mb-6">
Our Mission
</h2>
<div className="flex justify-center gap-5 md:gap-7 lg:gap-11 relative">
{data.map((item) => (
<div
className="flex items-center bg-white-20 w-[203px] px-[18px] py-6 gap-3 rounded-lg"
key={item.id}
>
<div
style={{
width: "28px",
height: "28px",
background: "#FFF2ED",
flex: "none",
}}
className="hidden md:flex"
></div>
<p className="font-medium text-xs md:text-sm">{item.text}</p>
</div>
))}
</div>
</div>
</div>
</div>
{/* END OF CARD */}
<OurValues />
<OurTeam />
<Banner />
</main>
);
};
export default About; |
// Import necessary Truffle libraries and the contract artifacts
const LendingContract = artifacts.require("LendingContract");
contract("LendingContract", (accounts) => {
let lendingContract;
const user = accounts[1];
const borrowAmount = web3.utils.toWei("15", "ether"); // Borrow more than the deposited balance
beforeEach(async () => {
lendingContract = await LendingContract.new({ from: accounts[0] });
});
it("should prevent borrowing more than available balance", async () => {
const depositAmount = web3.utils.toWei("10", "ether");
await lendingContract.deposit({ from: user, value: depositAmount });
try {
await lendingContract.borrow(borrowAmount, { from: user });
assert.fail("Borrowing more than deposited balance should fail");
} catch (error) {
// Ensure that the error message contains "Not enough balance to borrow"
assert.include(
error.message,
"Not enough balance to borrow",
"Error message should indicate insufficient balance"
);
}
const loanBalance = await lendingContract.getLoanBalance({ from: user });
assert.equal(
loanBalance.toString(),
"0",
"Loan balance should remain zero"
);
});
}); |
import { useState } from 'react'
export const useLocalStorage = <T>(keyname: string, defaultValue: T): [T, (value: T) => void] => {
const [storedValue, setStoreValue] = useState<T>(() => {
try {
const value = window.localStorage.getItem(keyname)
if (value) {
return JSON.parse(value)
} else {
window.localStorage.setItem(keyname, JSON.stringify(defaultValue))
return defaultValue
}
} catch (err) {
return defaultValue
}
})
const setValue = (value: T) => {
try {
window.localStorage.setItem(keyname, JSON.stringify(value))
setStoreValue(value)
} catch (err) {
setStoreValue(value)
}
}
return [storedValue, setValue]
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>reveal.js</title>
<link rel="stylesheet" href="dist/reset.css">
<link rel="stylesheet" href="dist/reveal.css">
<link rel="stylesheet" href="dist/theme/conference-dark.css">
<link rel="stylesheet" href="dist/theme/life-after-lombok.css">
<!-- Theme used for syntax highlighted code -->
<link rel="stylesheet" href="plugin/highlight/darcula-adjusted.css">
</head>
<body>
<div class="reveal">
<div class="slides">
<!-- Opening ------------------------------------------------------------------------------------------>
<section data-transition="none">
<div class="centered-content">
<h1 class="title">Is there life after Lombok?</h1>
<p>Jaap Coomans</p>
</div>
<p style="position: absolute; left: 30px; bottom: 90px;">
<img src="images/twitter-logo.png" style="height: 50px; display: inline; vertical-align: middle;" alt="Twitter Logo"/>
@JaapCoomans
</p>
<p style="position: absolute; left: 30px; bottom: 10px;">
<img src="images/mastodon-logo.png" style="height: 50px; display: inline; vertical-align: middle;" alt="Mastodon Logo"/>
@JaapCoomans@mastodon.online
</p>
<div style="position: absolute; bottom: 30px; right: 30px;">
<img src="images/group9_common_top_png.png" alt="group9 logo" style="height: 200px;"/>
</div>
</section>
<section data-background="images/backgrounds/devoxx.jpg" data-background-opacity="0.3" data-transition="none">
<div class="centered-content">
<h1 class="huge">It's 2010...</h1>
</div>
<div class="cc-by-sa">
Author: Stephan Janssen<br/>
https://commons.wikimedia.org/wiki/File:Ask_the_architect_during_Devoxx_Belgium_2018.jpg
</div>
</section>
<section data-background="images/backgrounds/devoxx.jpg" data-background-opacity="0.3" data-transition="none">
<audio src="media/ghostbusters-theme-intro.mp3" data-autoplay></audio>
<div class="cc-by-sa">
Author: Stephan Janssen<br/>
https://commons.wikimedia.org/wiki/File:Ask_the_architect_during_Devoxx_Belgium_2018.jpg
</div>
</section>
<!-- Introducing myself ------------------------------------------------------------------------------->
<section data-transition="none">
<h2>about:me</h2>
<p style="position: relative; left: 30px; text-align: left; line-height: 1.7em; font-size: 1.1em; color:#666666;">
🏷️ Jaap Coomans<br/>
🏠 Tilburg, The Netherlands<br/>
📅 Java since 2002<br/>
🧑💻 Software Architect at group9<br/>
🧑🏫 Trainer at alpha1 academy<br/>
🚩 Founder of BrabantJUG<br/>
👨👩👧👧 Husband, Father of 2 girls<br/>
🎲 Boardgame player<br/>
🍺 Craft beer sampler
</p>
<p style="position: absolute; left: 30px; bottom: 90px;">
<img src="images/twitter-logo.png" style="height: 50px; display: inline; vertical-align: middle;" alt="Twitter Logo"/>
@JaapCoomans
</p>
<p style="position: absolute; left: 30px; bottom: 10px;">
<img src="images/mastodon-logo.png" style="height: 50px; display: inline; vertical-align: middle;" alt="Mastodon Logo"/>
@JaapCoomans@mastodon.online
</p>
<div style="position: absolute; right: 150px; top: 100px;">
<img src="images/jaap-devoxx22-square.jpg" alt="Jaap Coomans" style="width: 400px; border-radius: 50%;"/>
</div>
<div style="position: absolute; bottom: 30px; right: 30px;">
<img src="images/brabantjug-logo.png" alt="BrabantJUG logo" style="height: 200px; padding-right: 50px;"/>
<img src="images/group9_common_top_png.png" alt="group9 logo" style="height: 200px;"/>
<img src="images/a1_academy_common_top_png.png" alt="alpha1 academy logo" style="height: 200px;"/>
</div>
</section>
<!-- Audience poll -->
<section data-transition="none">
<h1 class="centered-content huge">And how about you?</h1>
</section>
<!-- Lombok under the hood -->
<section data-background="images/backgrounds/voodoo-magic.jpg" data-transition="none">
<div class="cc-by-nc-sa" >
Author: Dragon Papillon Photography<br/>
https://www.flickr.com/photos/paloetic/4797683715/
</div>
</section>
<section data-background="images/backgrounds/car-hood-up.jpg" data-background-opacity="0.2" data-transition="none">
<div class="centered-content">
<h1 class="huge">How does it work under the hood?</h1>
</div>
<div class="cc-by-nc">
Author: Francisco Daum<br/>
https://flickr.com/photos/franciscodaum/8013498128/
</div>
</section>
<section data-transition="none">
<h3>Launching the annotation processor</h3>
<div class="centered-content">
<div class="fragment fade-in-then-semi-out">
<p><code>META-INF/services/javax.annotation.processing.Processor</code></p>
<pre>
<code class="language-java hljs large-code-sample" data-trim data-line-numbers>
lombok.launch.AnnotationProcessorHider$AnnotationProcessor
</code>
</pre>
</div>
<div class="fragment fade-in-then-semi-out">
<p style="font-size: 2em;">⬇️</p>
<p><code>lombok.launch.ShadowClassLoader</code></p>
<p>🤫 <code>.SCL.lombok</code> 🤫</p>
</div>
<div class="fragment fade-in-then-semi-out">
<p style="font-size: 2em;">⬇️</p>
<p><code>lombok.core.AnnotationProcessor</code></p>
</div>
<div class="fragment fade-in-then-semi-out">
<p style="font-size: 2em;">⬇️</p>
<p><code>lombok.javac.apt.LombokProcessor</code></p>
</div>
</div>
</section>
<section data-background="images/backgrounds/cameleon-camouflage.jpg" data-transition="none">
<div class="cc-by-nc-sa" >
Author: Chris Penrose<br/>
https://flickr.com/photos/95366033@N00/21448779922/
</div>
</section>
<section data-transition="none" data-visibility="hidden">
<h3>Round and round it goes</h3>
<div class="centered-content" style="font-size: 15em;">🔁</div>
</section>
<!-- No-brainers -------------------------------------------------------------------------------------->
<section>
<!-- BlANK SLIDE -->
</section>
<section data-background="images/backgrounds/scared-frankenstein.jpg" data-background-opacity="0.7" data-transition="none">
<h1 class="large shadowed">@NoArgsConstructor</h1>
<div class="cc0">
https://www.flickr.com/photos/51514834@N00/51952528729/
</div>
</section>
<section data-transition="none">
<h3>@NoArgsConstructor</h3>
<div class="centered-content">
<div class="fragment fade-in-then-semi-out">
<h4>With Lombok</h4>
<strong>49 characters</strong> (ex whitespace).
<pre>
<code class="language-java hljs large-code-sample" data-trim>
import lombok.NoArgsConstructor;
@NoArgsConstructor
class LombokNoArgsConstructor {
// snip ...
}
</code>
</pre>
</div>
<div class="fragment">
<h4>Without Lombok</h4>
<strong>10 characters</strong> (+ class name):
<pre>
<code class="language-java hljs large-code-sample" data-trim>
class AFortyCharacterClassNameInOrderToBenefit {
public AFortyCharacterClassNameInOrderToBenefit() {}
// snip ...
}
</code>
</pre>
</div>
</div>
</section>
<section data-background="images/backgrounds/cat-hiding.jpg" data-background-opacity="0.7" data-transition="none">
<h1 class="huge">@Slf4j</h1>
<div class="cc-by-nc-sa">
Author: Kerri Lee SMith<br/>
https://flickr.com/photos/77654185@N07/41504551702/
</div>
</section>
<section data-transition="none">
<h3>@Slf4j</h3>
<div class="centered-content">
<div class="fragment">
Made possible by > 1000 lines of code
<pre>
<code class="language-java hljs large-code-sample" data-trim data-line-numbers="1,3">
import lombok.extern.slf4j.Slf4j;
@Slf4j
class LoggerExample {
void logSomething() {
log.info("Something");
}
}
</code>
</pre>
</div>
<div class="fragment">
Just 1 line of code
<pre>
<code class="language-java hljs large-code-sample" data-trim data-line-numbers="1,2,5">
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class LoggerExample {
private static final Logger log = LoggerFactory.getLogger(LoggerExample.class);
void logSomething() {
log.info("Something");
}
}
</code>
</pre>
</div>
</div>
</section>
<section data-transition="none">
<h3>IntelliJ Live template</h3>
<div class="centered-content">
<video data-autoplay src="media/intellij-live-template-logger.mp4" loop></video>
</div>
</section>
<section data-transition="none">
<h3>IntelliJ Live template</h3>
<div class="centered-content">
<pre class="fragment">
<code class="hljs large-code-sample" data-trim data-line-numbers>
<template name="log"
value="private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger($CLASS_NAME$.class);"
toReformat="false"
toShortenFQNames="true">
<variable name="CLASS_NAME" expression="className()" defaultValue="" alwaysStopAt="true" />
<context>
<option name="JAVA_CODE" value="true" />
</context>
</template>
</code>
</pre>
<img class="fragment" src="images/intellij-live-template-logger.png" alt="IntelliJ live template configuration for slf4j"/>
</div>
</section>
<section data-transition="none">
<!-- EMPTY SLIDE -->
</section>
<!-- IDE Usability ------------------------------------------------------------------------------------>
<section>
<h3>Finding usages without Lombok</h3>
<div class="centered-content">
<div class="fragment fade-in-then-semi-out">
<p style="font-size: 2em;">Ctrl + 🖱️</p>
<p style="opacity: 0.5;">(⌘ + 🖱️)</p>
</div>
<img class="fragment fade" src="images/find-uasages-dropdown.png" alt="IntelliJ Find Usages dropdown menu"/>
</div>
</section>
<section>
<h3>Finding usages with Lombok</h3>
<div class="centered-content">
<ul class="centered five-items" >
<li class="fragment fade-in-then-semi-out">Ctrl / ⌘ + F12</li>
<li class="fragment fade-in-then-semi-out">Scroll</li>
<li class="fragment fade-in-then-semi-out">🖱️ / ⏎</li>
<li class="fragment fade-in-then-semi-out">Realize mistake 🤦</li>
<li class="fragment fade-in-then-semi-out">Again: Ctrl / ⌘ + F12</li>
<li class="fragment fade-in-then-semi-out">Scroll</li>
<li class="fragment fade-in-then-semi-out">Alt / ⌥ + F7</li>
</ul>
</div>
</section>
<section data-transition="none">
<!-- EMPTY SLIDE -->
</section>
<!-- Read / write ratio ------------------------------------------------------------------------------->
<section data-transition="none">
<div class="centered-content">
<div style="width: 40%; float: left;">
<h1 class="title" style="font-size: 15em;"><code>1</code></h1>
</div>
<div style="width: 20%; float: left;">
<h1 class="title" style="font-size: 15em;"><code>:</code></h1>
</div>
<div style="width: 40%; float: left;">
<h1 class="title" style="font-size: 15em;"><code>10</code></h1>
</div>
<div class="fragment" style="font-size: 2em;">
<div style="width: 40%; float: left;">
<p>Writing code</p>
</div>
<div style="width: 20%; float: left;">
<p></p>
</div>
<div style="width: 40%; float: left;">
<p>Reading code</p>
</div>
</div>
</div>
</section>
<!-- Working memory / cognitive load ------------------------------------------------------------------>
<section data-background="images/backgrounds/cognitive-load.jpg" data-transition="none" data-visibility="hidden">
<div class="centered-content">
<h1 class="huge">Cognitive load</h1>
</div>
<p class="source">
Image generated by Dall-E 2
</p>
</section>
<section data-transition="none">
<h3>Our working memory</h3>
<div style="margin-top: 10%;">
<div class="working-memory">
<div class="chunk" style="font-size: 8vw;"><span class="fragment fade-in">R</span></div>
<div class="chunk" style="font-size: 8vw;"><span class="fragment fade-in">T</span></div>
<div class="chunk" style="font-size: 8vw;"><span class="fragment fade-in">K</span></div>
<div class="chunk" style="font-size: 8vw;"><span class="fragment fade-in">E</span></div>
<div class="chunk" style="font-size: 8vw;"><span class="fragment fade-in">W</span></div>
<div class="chunk" style="font-size: 8vw;"><span class="fragment fade-in">N</span></div>
<div class="chunk" style="font-size: 8vw;"><span class="fragment fade-in">O</span></div>
</div>
</div>
</section>
<section data-transition="none">
<h3>Our working memory</h3>
<div style="margin-top: 10%;">
<div class="working-memory">
<div class="chunk" style="font-size: 8vw;">N</div>
<div class="chunk" style="font-size: 8vw;">E</div>
<div class="chunk" style="font-size: 8vw;">T</div>
<div class="chunk" style="font-size: 8vw;">W</div>
<div class="chunk" style="font-size: 8vw;">O</div>
<div class="chunk" style="font-size: 8vw;">R</div>
<div class="chunk" style="font-size: 8vw;">K</div>
</div>
</div>
</section>
<section data-transition="none">
<h3>Schemata</h3>
<div style="margin-top: 10%;">
<div class="working-memory">
<div class="chunk" style="font-size: 3vw;">NETWORK</div>
<div class="chunk"></div>
<div class="chunk"></div>
<div class="chunk"></div>
<div class="chunk"></div>
<div class="chunk"></div>
<div class="chunk"></div>
</div>
</div>
</section>
<section data-transition="none">
<div class="centered-content">
<h1 class="large fragment">The code is there.</h1>
<h1 class="large fragment">It's just not on your screen.</h1>
</div>
</section>
<section data-transition="none">
<!-- EMPTY SLIDE -->
</section>
<!-- Sloppy design ------------------------------------------------------------------------------------>
<section data-background="images/backgrounds/builders.jpg" data-background-opacity="0.7" data-transition="none">
<div class="centered-content">
<h1 class="huge">Let's talk Builders...</h1>
</div>
<div class="cc-by-nc-sa">
Author: Jürg Stuker<br/>
https://www.flickr.com/photos/jstuker/15609198570/
</div>
</section>
<section>
<h3>Sloppy Value Objects</h3>
<div class="centered-content">
<pre>
<code class="language-java hljs large-code-sample" data-trim>
public void changePhoneNumber(String phoneNumber) {
this.contactDetails = this.contactDetails.toBuilder()
.phoneNumber(phoneNumber)
.build();
}
</code>
</pre>
</div>
</section>
<section>
<h3>Redundant annotations</h3>
<div class="centered-content">
<pre>
<code class="language-java hljs large-code-sample" data-trim>
@Value
@AllArgsConstructor
@EqualsAndHashCode
public class BoardGame {
String only;
String three;
String fields;
}
</code>
</pre>
</div>
</section>
<section>
<h3>Redundant annotations</h3>
<div class="centered-content">
<pre>
<code class="language-java hljs large-code-sample" data-trim>
@AllArgsConstructor
class Person {
@Getter
private String name;
@Getter
private String alias;
@Getter
private int age;
public String getName() {
return String.format("%s (%s)", name, alias);
}
}
</code>
</pre>
</div>
</section>
<!-- Life after Lombok -------------------------------------------------------------------------------->
<section data-transition="none">
<h1 class="centered-content huge">Life after Lombok</h1>
</section>
<section data-transition="none" data-background="images/backgrounds/boilerplate.jpg" data-background-opacity="0.3">
<h1 class="huge centered-content">Boilerplate <br/>as a solution</h1>
<div class="cc-by">
Author: Paul Trafford<br/>
https://www.flickr.com/photos/paultraf/4208876011/
</div>
</section>
<section data-transition="none">
<h3>Boilerplate as a solution</h3>
<div class="centered-content">
<ul class="centered three-items">
<li class="fragment fade-in-then-semi-out">Physical boilerplate</li>
<li class="fragment fade-in-then-semi-out">Boilerplate text</li>
<li class="fragment fade-in-then-semi-out">Boilerplate contracts</li>
</ul>
</div>
</section>
<section data-transition="none" data-background="images/backgrounds/records.jpg" data-background-opacity="0.3">
<h1 class="centered-content huge">Records FTW?</h1>
<div class="cc-by-nc-sa">
Author: Risa<br/>
https://www.flickr.com/photos/risayv/4514353658/
</div>
</section>
<section data-transition="none">
<h1 class="huge">
records<br/>
!=<br/>
@Value
</h1>
</section>
<section data-transition="none" data-background="images/backgrounds/duke-heart.jpg" data-background-color="rgb(255, 255, 255)" data-background-size="auto 80%">
<h1>Love the language</h1>
<div style="position: absolute; bottom: 30px; right: 30px;">
<p>#lovejava</p>
</div>
</section>
<!-- Closing slide ------------------------------------------------------------------------------------>
<section data-transition="none">
<h1 class="huge">Thank you!</h1>
<div style="position: absolute; text-align: left; width: 50%; -ms-transform: translateX(50%); transform: translateX(50%); padding-top: 100px;">
<h4>Please help me improve:</h4>
<p>
<img src="images/twitter-logo.png" style="height: 50px; display: inline; vertical-align: middle;" alt="Twitter Logo"/>
@JaapCoomans<br/>
<img src="images/mastodon-logo.png" style="height: 50px; display: inline; vertical-align: middle;" alt="Mastodon Logo"/>
@JaapCoomans@mastodon.online
</p>
</div>
<div style="position: absolute; bottom: 30px; right: 30px;">
<img src="images/group9_common_top_png.png" alt="group9 logo" style="height: 200px;"/>
</div>
</section>
</div>
</div>
<script src="dist/reveal.js"></script>
<script src="plugin/notes/notes.js"></script>
<script src="plugin/markdown/markdown.js"></script>
<script src="plugin/highlight/highlight.js"></script>
<script>
// More info about initialization & config:
// - https://revealjs.com/initialization/
// - https://revealjs.com/config/
Reveal.initialize({
hash: true,
width: '100%',
height: '100%',
center: false,
backgroundTransition: 'none',
controls: false,
progress: false,
// Learn about plugins: https://revealjs.com/plugins/
plugins: [ RevealMarkdown, RevealHighlight, RevealNotes ]
});
</script>
</body>
</html> |
/*! @file AgentContainer.H
\brief Contains #AgentContainer class and related structs
*/
#ifndef AGENT_CONTAINER_H_
#define AGENT_CONTAINER_H_
#include <array>
#include <AMReX_BoxArray.H>
#include <AMReX_DistributionMapping.H>
#include <AMReX_Geometry.H>
#include <AMReX_GpuDevice.H>
#include <AMReX_IntVect.H>
#include <AMReX_Particles.H>
#include <AMReX_iMultiFab.H>
#include <AMReX_Vector.H>
#include "AgentDefinitions.H"
#include "DemographicData.H"
#include "DiseaseParm.H"
#include "InteractionModelLibrary.H"
/*! \brief Assigns school by taking a random number between 0 and 100, and using
* default distribution to choose elementary/middle/high school. */
AMREX_GPU_DEVICE AMREX_FORCE_INLINE
int assign_school (const int nborhood, const amrex::RandomEngine& engine) {
int il4 = amrex::Random_int(100, engine);
int school = -1;
if (il4 < 36) {
school = 3 + (nborhood / 2); /* elementary school */
}
else if (il4 < 68) {
school = 2; /* middle school */
}
else if (il4 < 93) {
school = 1; /* high school */
}
else {
school = 0; /* not in school, presumably 18-year-olds or some home-schooled */
}
return school;
}
/*! \brief Derived class from ParticleContainer that defines agents and their functions */
class AgentContainer
: public amrex::ParticleContainer<0, 0, RealIdx::nattribs, IntIdx::nattribs>
{
using PCType = AgentContainer;
using PType = ParticleType;
using PTileType = ParticleTileType;
using PTDType = PTileType::ParticleTileDataType;
using IntModel = InteractionModel<PCType,PTileType,PTDType,PType>;
public:
/*! Constructor:
* + Initializes particle container for agents
* + Read in contact probabilities from command line input file
* + Read in disease parameters from command line input file
*/
AgentContainer (const amrex::Geometry & a_geom, /*!< Physical domain */
const amrex::DistributionMapping & a_dmap, /*!< Distribution mapping */
const amrex::BoxArray & a_ba /*!< Box array */ )
: amrex::ParticleContainer<0, 0, RealIdx::nattribs, IntIdx::nattribs>(a_geom, a_dmap, a_ba)
{
BL_PROFILE("AgentContainer::AgentContainer");
h_parm = new DiseaseParm{};
d_parm = (DiseaseParm*)amrex::The_Arena()->alloc(sizeof(DiseaseParm));
{
amrex::ParmParse pp("agent");
pp.query("symptomatic_withdraw", m_symptomatic_withdraw);
pp.query("shelter_compliance", m_shelter_compliance);
pp.query("symptomatic_withdraw_compliance", m_symptomatic_withdraw_compliance);
}
{
amrex::ParmParse pp("contact");
pp.query("pSC", h_parm->pSC);
pp.query("pCO", h_parm->pCO);
pp.query("pNH", h_parm->pNH);
pp.query("pWO", h_parm->pWO);
pp.query("pFA", h_parm->pFA);
pp.query("pBAR", h_parm->pBAR);
}
{
using namespace ExaEpi;
/* Create the interaction model objects and push to container */
m_interactions.clear();
m_interactions[InteractionNames::generic] = new InteractionModGeneric<PCType,PTileType,PTDType,PType>;
m_interactions[InteractionNames::home] = new InteractionModHome<PCType,PTileType,PTDType,PType>;
m_interactions[InteractionNames::work] = new InteractionModWork<PCType,PTileType,PTDType,PType>;
m_interactions[InteractionNames::school] = new InteractionModSchool<PCType,PTileType,PTDType,PType>;
m_interactions[InteractionNames::nborhood] = new InteractionModNborhood<PCType,PTileType,PTDType,PType>;
}
{
amrex::ParmParse pp("disease");
pp.query("nstrain", h_parm->nstrain);
pp.query("reinfect_prob", h_parm->reinfect_prob);
amrex::Vector<amrex::Real> p_trans(h_parm->nstrain);
amrex::Vector<amrex::Real> p_asymp(h_parm->nstrain);
amrex::Vector<amrex::Real> reduced_inf(h_parm->nstrain);
pp.queryarr("p_trans", p_trans, 0, h_parm->nstrain);
pp.queryarr("p_asymp", p_asymp, 0, h_parm->nstrain);
pp.queryarr("reduced_inf", reduced_inf, 0, h_parm->nstrain);
pp.query("vac_eff", h_parm->vac_eff);
for (int i = 0; i < h_parm->nstrain; ++i) {
h_parm->p_trans[i] = p_trans[i];
h_parm->p_asymp[i] = p_asymp[i];
h_parm->reduced_inf[i] = reduced_inf[i];
}
pp.query("incubation_length_mean", h_parm->incubation_length_mean);
pp.query("infectious_length_mean", h_parm->infectious_length_mean);
pp.query("symptomdev_length_mean", h_parm->symptomdev_length_mean);
pp.query("incubation_length_std", h_parm->incubation_length_std);
pp.query("infectious_length_std", h_parm->infectious_length_std);
pp.query("symptomdev_length_std", h_parm->symptomdev_length_std);
pp.query("mean_immune_time", h_parm->mean_immune_time);
pp.query("immune_time_spread", h_parm->immune_time_spread);
}
h_parm->Initialize();
#ifdef AMREX_USE_GPU
amrex::Gpu::htod_memcpy(d_parm, h_parm, sizeof(DiseaseParm));
#else
std::memcpy(d_parm, h_parm, sizeof(DiseaseParm));
#endif
}
void initAgentsDemo (amrex::iMultiFab& /*num_residents*/,
amrex::iMultiFab& /*unit_mf*/,
amrex::iMultiFab& /*FIPS_mf*/,
amrex::iMultiFab& /*comm_mf*/,
DemographicData& /*demo*/);
void initAgentsCensus (amrex::iMultiFab& num_residents,
amrex::iMultiFab& unit_mf,
amrex::iMultiFab& FIPS_mf,
amrex::iMultiFab& comm_mf,
DemographicData& demo);
void morningCommute(amrex::MultiFab&);
void eveningCommute(amrex::MultiFab&);
void interactDay(amrex::MultiFab&);
void interactEvening(amrex::MultiFab&);
void interactNight(amrex::MultiFab&);
void moveAgentsRandomWalk ();
void moveRandomTravel ();
void updateStatus (amrex::MultiFab& ds);
void infectAgents ();
void shelterStart ();
void shelterStop ();
void generateCellData (amrex::MultiFab& mf) const;
std::array<amrex::Long, 9> getTotals ();
void moveAgentsToWork ();
void moveAgentsToHome ();
/*! \brief Return bin pointer at a given mfi, tile and model name */
inline amrex::DenseBins<PType>* getBins( const std::pair<int,int>& a_idx,
const std::string& a_mod_name )
{
BL_PROFILE("AgentContainer::getBins");
if (a_mod_name == ExaEpi::InteractionNames::home) {
return &m_bins_home[a_idx];
} else if ( (a_mod_name == ExaEpi::InteractionNames::work)
|| (a_mod_name == ExaEpi::InteractionNames::school) ) {
return &m_bins_work[a_idx];
} else if (a_mod_name == ExaEpi::InteractionNames::nborhood) {
if (m_at_work) { return &m_bins_work[a_idx]; }
else { return &m_bins_home[a_idx]; }
} else {
amrex::Abort("Invalid a_mod_name!");
return nullptr;
}
}
/*! \brief Return disease parameters object pointer (host) */
inline const DiseaseParm* getDiseaseParameters_h () const {
return h_parm;
}
/*! \brief Return disease parameters object pointer (device) */
inline const DiseaseParm* getDiseaseParameters_d () const {
return d_parm;
}
protected:
int m_symptomatic_withdraw = 1;
amrex::Real m_shelter_compliance = 0.95_rt;
amrex::Real m_symptomatic_withdraw_compliance = 0.95_rt;
DiseaseParm* h_parm; /*!< Disease parameters */
DiseaseParm* d_parm; /*!< Disease parameters (GPU device) */
/*! Map of home bins (of agents) indexed by MultiFab iterator and tile index;
see AgentContainer::interactAgentsHomeWork() */
std::map<std::pair<int, int>, amrex::DenseBins<PType> > m_bins_home;
/*! Map of work bins (of agents) indexed by MultiFab iterator and tile index;
see AgentContainer::interactAgentsHomeWork() */
std::map<std::pair<int, int>, amrex::DenseBins<PType> > m_bins_work;
std::map<std::string,IntModel*> m_interactions;
/*! Flag to indicate if agents are at work */
bool m_at_work;
/*! \brief queries if a given interaction type (model) is available */
inline bool haveInteractionModel( const std::string& a_mod_name ) const
{
BL_PROFILE("AgentContainer::haveInteractionModel");
std::map<std::string,IntModel*>::const_iterator it(m_interactions.find(a_mod_name));
return (it != m_interactions.end());
}
};
using AgentIterator = typename AgentContainer::ParIterType;
#endif |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get_it/get_it.dart';
import '../../../../core/widgets/custom_card_movement_widget.dart';
import '../../../../core/widgets/empty_widget.dart';
import '../../../../core/widgets/error_widget.dart';
import '../../../../core/widgets/loading_widget.dart';
import '../../../../featuers/Auth/presintation/bloc/auth_bloc.dart';
import '../../models/warehouse_order_model.dart';
import '../bloc/warehouse_orders_bloc.dart';
// ignore: must_be_immutable
class OrderRejectedBody extends StatelessWidget {
OrderRejectedBody({super.key});
List<WarehouseOrdersDataModel>? warehouseRejectedData;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => GetIt.I.get<WarehouseOrdersBloc>(),
child: Scaffold(
body: BlocConsumer<WarehouseOrdersBloc, WarehouseOrdersState>(
listener: (context, state) {
if (state is WarehouseRejectedOrdersSuccess) {
warehouseRejectedData = state.warehouseOrdersModel.data;
print(warehouseRejectedData?.length ?? "SSSSSSSSSS");
}
},
builder: (context, state) {
if (state is WarehouseOrdersInitial) {
context
.read<WarehouseOrdersBloc>()
.add(GetRejectedEvent(context.read<AuthBloc>().token ?? ''));
}
if (state is WarehouseOrdersFailed) {
return FailuerWidget(
errorMessage: state.failure.message,
onPressed: () {
//token: context.read<AuthBloc>().token
context.read<WarehouseOrdersBloc>().add(
GetRejectedEvent(context.read<AuthBloc>().token ?? ''));
},
);
}
return Stack(
children: [
Column(
children: [
SizedBox(
height: 100.h,
),
Expanded(
child: ListView.builder(
itemCount: warehouseRejectedData?.length ?? 0,
itemBuilder: (BuildContext context, int index) {
return Column(
children: [
CustomCardMovementWidget(
height: 250.h,
firstTextField:
warehouseRejectedData?[index]
.investor?[0]
.name ??
"Investor",
secondTextField:
warehouseRejectedData?[index]
.requestDate ??
"20/08/2023",
quantityTextField:
warehouseRejectedData?[index]
.quantity
.toString() ??
"00",
customWidget: const SizedBox.shrink()),
SizedBox(
height: 30.h,
)
],
);
}),
),
],
),
if (state is WarehouseOrdersLoading)
const LoadingWidget(fullScreen: true)
else if (state is WarehouseRejectSuccess &&
warehouseRejectedData!.isEmpty)
EmptyWidget(height: 1.sh - 0.3)
],
);
},
),
),
);
}
} |
<?php
/**
* The main template file
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package Style Outlet
*/
get_header(); ?>
<div id="content" class="site-content">
<div class="container">
<?php $sidebar_position = get_theme_mod( 'sidebar_position', 'right' ); ?>
<?php if( 'left' == $sidebar_position ) :?>
<?php get_sidebar(); ?>
<?php endif; ?>
<div id="primary" class="content-area <?php style_outlet_layout_class(); ?> columns">
<main id="main" class="site-main" role="main">
<?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) : ?>
<header>
<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
</header>
<?php
endif;
/* Start the Loop */
while ( have_posts() ) : the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
if( get_theme_mod ('numeric_pagination',true) ) :
the_posts_pagination();
else :
style_outlet_post_nav();
endif;
?>
<?php else :
get_template_part( 'template-parts/content', 'none' );
endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php if( 'right' == $sidebar_position ) :?>
<?php get_sidebar(); ?>
<?php endif; ?>
<?php get_footer(); ?> |
# 1.用栈实现队列
[力扣题目链接](https://leetcode.cn/problems/implement-queue-using-stacks/)
## 题目
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(`push`、`pop`、`peek`、`empty`):
实现 `MyQueue` 类:
- `void push(int x)` 将元素 x 推到队列的末尾
- `int pop()` 从队列的开头移除并返回元素
- `int peek()` 返回队列开头的元素
- `boolean empty()` 如果队列为空,返回 `true` ;否则,返回 `false`
**说明:**
- 你 **只能** 使用标准的栈操作 —— 也就是只有 `push to top`, `peek/pop from top`, `size`, 和 `is empty` 操作是合法的。
- 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
**示例 1:**
```
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]
解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
```
**提示:**
- `1 <= x <= 9`
- 最多调用 `100` 次 `push`、`pop`、`peek` 和 `empty`
- 假设所有操作都是有效的 (例如,一个空的队列不会调用 `pop` 或者 `peek` 操作)
## 代码
~~~js
var MyQueue = function () {
this._stackIn = [];
this._stackOut = [];
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function (x) {
this._stackIn.push(x);
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function () {
if (this._stackOut.length) {
return this._stackOut.pop();
}
while (this._stackIn.length) {
this._stackOut.push(this._stackIn.pop());
}
return this._stackOut.pop();
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function () {
const x = this.pop();
this._stackOut.push(x);
return x;
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
return !this._stackIn.length && !this._stackOut.length;
};
~~~ |
/**
* @description Locates the first matching elements on the page, even within shadow DOMs, using a complex n-depth selector.
* No need to specify all shadow roots to a button; the tree is traversed to find the correct element.
*
* Author: Roland Ross L. Hadi
* GitHub: https://github.com/rolandhadi/shadow-dom-selector
*/
/**
* Traverses shadow DOMs to find a specific element using a complex selector.
* @param {string} selector - The CSS selector to query.
* @param {Document|ShadowRoot} root - The root element to start the search from.
* @returns {Element|null} - The found element or null if not found.
*
* Example usage:
* xfind('downloads-item:nth-child(4) #remove');
* xfind('#downloads-list .is-active a[href^="https://"]');
*/
function xfind(selector, root = document) {
const element = performQuery(selector, false, root);
console.log(`Found ${element ? 1 : 0} element(s)`);
return element;
}
/**
* Traverses shadow DOMs to find all matching elements using a complex selector.
* @param {string} selector - The CSS selector to query.
* @param {Document|ShadowRoot} root - The root element to start the search from.
* @returns {NodeListOf<Element>|Array<Element>} - A list of found elements.
*
* Example usage:
* xfindAll('downloads-item:nth-child(4) #remove');
* xfindAll('#downloads-list .is-active a[href^="https://"]');
*/
function xfindAll(selector, root = document) {
const elements = performQuery(selector, true, root);
console.log(`Found ${elements.length} element(s)`);
return elements;
}
/**
* Core function to query elements in the shadow DOM.
* @param {string} selector - The CSS selector to query.
* @param {boolean} findMany - Whether to find multiple elements or just one.
* @param {Document|ShadowRoot} root - The root element to start the search from.
* @returns {Element|Array<Element>|null} - The found element(s) or null if not found.
*/
function performQuery(selector, findMany, root) {
validateSelector(selector);
const selectors = selector.split('>>>');
let currentElement = root;
for (let i = 0; i < selectors.length; i++) {
if (i === selectors.length - 1 && findMany) {
return querySelectorAllXFind(selectors[i], currentElement);
}
currentElement = querySelectorXFind(selectors[i], currentElement);
if (currentElement === null) {
console.error(`Selector ${selectors[i]} not found`);
return findMany ? [] : null;
}
}
return currentElement;
}
/**
* Queries all elements matching the selector in the shadow DOM.
* @param {string} selector - The CSS selector to query.
* @param {Document|ShadowRoot} root - The root element to start the search from.
* @returns {NodeListOf<Element>|Array<Element>} - A list of found elements.
*/
function querySelectorAllXFind(selector, root = document) {
return queryInShadowDOM(selector, true, root);
}
/**
* Queries an element in the shadow DOM.
* @param {string} selector - The CSS selector to query.
* @param {Document|ShadowRoot} root - The root element to start the search from.
* @returns {Element|null} - The found element or null if not found.
*/
function querySelectorXFind(selector, root = document) {
return queryInShadowDOM(selector, false, root);
}
/**
* Performs a query within shadow DOM.
* @param {string} selector - The CSS selector to query.
* @param {boolean} findMany - Whether to find multiple elements or just one.
* @param {Document|ShadowRoot} root - The root element to start the search from.
* @returns {Element|Array<Element>|null} - The found element(s) or null if not found.
*/
function queryInShadowDOM(selector, findMany, root) {
let lightDomElement = root.querySelector(selector);
if (document.head.createShadowRoot || document.head.attachShadow) {
if (!findMany && lightDomElement) {
return lightDomElement;
}
const splitSelectors = splitByUnquotedCharacter(selector, ',');
return splitSelectors.reduce((accumulator, sel) => {
if (!findMany && accumulator) return accumulator;
const refinedSelectors = splitByUnquotedCharacter(sel.trim().replace(/\s*([>+~])\s*/g, '$1'), ' ').filter(Boolean);
const lastIndex = refinedSelectors.length - 1;
const elementsToMatch = gatherAllElementsXFind(refinedSelectors[lastIndex], root);
const matchedElements = matchElements(refinedSelectors, lastIndex, root);
if (findMany) {
return accumulator.concat(elementsToMatch.filter(matchedElements));
} else {
return elementsToMatch.find(matchedElements) || null;
}
}, findMany ? [] : null);
} else {
return findMany ? root.querySelectorAll(selector) : lightDomElement;
}
}
/**
* Matches elements based on the refined selector.
* @param {Array<string>} refinedSelectors - The split CSS selector.
* @param {number} lastIndex - The index of the last selector part.
* @param {Document|ShadowRoot} root - The root element to start the search from.
* @returns {Function} - A function to match elements.
*/
function matchElements(refinedSelectors, lastIndex, root) {
return element => {
let position = lastIndex;
let currentElement = element;
while (currentElement) {
const isMatch = currentElement.matches ? currentElement.matches(refinedSelectors[position]) : false;
if (isMatch && position === 0) {
return true;
}
if (isMatch) {
position--;
}
currentElement = getParentOrHost(currentElement, root);
}
return false;
};
}
/**
* Splits a selector by a character, ignoring quoted sections.
* @param {string} selector - The CSS selector to split.
* @param {string} character - The character to split by.
* @returns {Array<string>} - The split selector.
*/
function splitByUnquotedCharacter(selector, character) {
return selector.match(/\\?.|^$/g).reduce((acc, char) => {
if (char === '"' && !acc.singleQuote) {
acc.doubleQuote ^= 1;
acc.strings[acc.strings.length - 1] += char;
} else if (char === '\'' && !acc.doubleQuote) {
acc.singleQuote ^= 1;
acc.strings[acc.strings.length - 1] += char;
} else if (!acc.doubleQuote && !acc.singleQuote && char === character) {
acc.strings.push('');
} else {
acc.strings[acc.strings.length - 1] += char;
}
return acc;
}, { strings: [''], doubleQuote: 0, singleQuote: 0 }).strings;
}
/**
* Gets the parent element or host if within a shadow DOM.
* @param {Element} element - The current element.
* @param {Document|ShadowRoot} root - The root element to start the search from.
* @returns {Element|null} - The parent element or host, or null if at the root.
*/
function getParentOrHost(element, root) {
const parent = element.parentNode;
return parent && parent.host && parent.nodeType === 11 ? parent.host : parent === root ? null : parent;
}
/**
* Collects all elements in the DOM, including those within shadow DOMs.
* @param {string|null} selector - The CSS selector to filter elements by.
* @param {Document|ShadowRoot} root - The root element to start the search from.
* @returns {Array<Element>} - A list of collected elements.
*/
function gatherAllElementsXFind(selector = null, root) {
const elements = [];
const collectElements = nodes => {
for (const node of nodes) {
elements.push(node);
if (node.shadowRoot) {
collectElements(node.shadowRoot.querySelectorAll('*'));
}
}
};
if (root.shadowRoot) {
collectElements(root.shadowRoot.querySelectorAll('*'));
}
collectElements(root.querySelectorAll('*'));
return selector ? elements.filter(el => el.matches(selector)) : elements;
}
/**
* Validates the CSS selector to ensure it is valid.
* @param {string} selector - The CSS selector to validate.
*/
function validateSelector(selector) {
try {
document.createElement('div').querySelector(selector);
} catch {
throw new Error(`Invalid selector: ${selector}`);
}
}
/**
* Highlights the found elements by adding a temporary outline.
* @param {Element|Array<Element>} elements - The element or array of elements to highlight.
*/
function highlightElements(elements) {
const highlight = (el) => {
const originalOutline = el.style.outline;
el.style.outline = '2px solid red';
setTimeout(() => {
el.style.outline = originalOutline;
}, 2000);
};
if (Array.isArray(elements)) {
elements.forEach(highlight);
} else if (elements) {
highlight(elements);
}
}
/**
* Welcome message displayed when the script is run in the browser console.
*/
function showWelcomeMessage() {
console.log("%cWelcome to Shadow DOM Selector!", "color: green; font-size: 16px;");
console.log("%cAuthor: Roland Ross L. Hadi", "color: blue; font-size: 14px;");
console.log("%cGitHub: https://github.com/rolandhadi/shadow-dom-selector", "color: blue; font-size: 14px;");
console.log("%cExample usage: xfind('downloads-item:nth-child(4) #remove');", "color: orange; font-size: 14px;");
}
// Display the welcome message
showWelcomeMessage(); |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UI;
using SuperTiled2Unity;
[System.Serializable]
public class CustomerMove {
public bool Cu_Move;
public string[] direction;
[Range(1, 5)]
public int frequency;
}
public class CustomerManager : MonoBehaviour {
[SerializeField]
private GameObject npcPrefab; // NPC 프리팹
[SerializeField]
// private float moveSpeed = 10f; // 이동 속도
private Animator animator; // 애니메이터 컴포넌트
[SerializeField]
private Sprite redImage; // 빨간색 이미지
private Vector2 moveDirection = Vector2.zero; // 이동 방향
private int num = 0;
public CustomerMove customer;
// [SerializeField] Transform target;
private NavMeshAgent agent;
[SerializeField]
private List<Transform> targets; // 모든 타겟들을 저장하는 리스트
private List<bool> targetsActive; // 각 타겟의 활성 상태를 저장
private bool isBusinessOpen = false; // 영업 상태 변수
public void StartSpawning() {
if (isBusinessOpen) { // 영업 중일 때만 NPC 생성
StartCoroutine(SpawnCustomerRoutine());
}
}
public void StopSpawning() {
StopAllCoroutines(); // 모든 코루틴 중단 (NPC 생성 중단)
}
public void SetBusinessStatus(bool status) {
isBusinessOpen = status;
if (isBusinessOpen) {
StartSpawning();
} else {
StopSpawning();
}
}
void Start() {
animator = GetComponent<Animator>(); // 애니메이터 컴포넌트 할당
agent = GetComponent<NavMeshAgent>();
InitializeTargetsActive();
// StartCoroutine(SpawnCustomerRoutine());
}
void InitializeTargetsActive() {
targetsActive = new List<bool>(); // 이 줄을 추가하여 리스트를 초기화합니다.
foreach (var target in targets) {
targetsActive.Add(target.gameObject.activeSelf);
}
}
<<<<<<< HEAD
IEnumerator SpawnCustomerRoutine() {
while (true) {
yield return new WaitForSeconds(5); // 4초 간격으로 NPC 스폰
if (IsAnyTargetActive() && num < 13) {
num ++;
Debug.Log(num);
SpawnCustomerAtSpawnPoint();
} else {
Debug.Log("모든 타겟이 비활성화되어 NPC를 더 이상 스폰하지 않습니다.");
=======
IEnumerator SpawnCustomerRoutine()
{
while (true)
{
yield return new WaitForSeconds(7); // 4초 간격으로 NPC 스폰
if (IsAnyTargetActive() && num < 25)
{
num++;
// // Debug.Log(num);
SpawnRandomCustomerAtSpawnPoint(); // 랜덤 NPC 생성
}
else
{
// // Debug.Log("모든 타겟이 비활성화되어 NPC를 더 이상 스폰하지 않습니다.");
>>>>>>> BEDev
yield break; // 모든 타겟이 비활성화되면 코루틴 종료
}
}
yield break;
}
bool IsAnyTargetActive() {
return targetsActive.Contains(true);
}
void SpawnCustomerAtSpawnPoint() {
SuperObject[] superObjects = FindObjectsOfType<SuperObject>();
foreach (var obj in superObjects) {
if (obj.name == "Object_44") {
var customProperties = obj.GetComponent<SuperCustomProperties>();
<<<<<<< HEAD
if (customProperties != null ) {
Debug.Log("Spawning NPC at: " + obj.name);
GameObject npc = Instantiate(npcPrefab, obj.transform.position, Quaternion.identity);
var customerScript = npc.GetComponent<CustomerManager>();
if (customerScript != null) {
customerScript.InitializeAgent(); // NavMeshAgent 초기화
}
break;
=======
if (customProperties != null)
{
// Debug.Log("Spawning NPC at: " + obj.name);
// 두 종류의 NPC 프리팹 중 하나를 랜덤으로 선택하여 생성
GameObject npcPrefabToSpawn = Random.Range(0, 2) == 0 ? npcPrefabMale : npcPrefabFemale;
GameObject npc = Instantiate(npcPrefabToSpawn, obj.transform.position, Quaternion.identity);
CustomerManager customerScript = npc.GetComponent<CustomerManager>();
if (customerScript != null)
{
customerScript.spawnPoint = obj.transform.position; // 스폰 위치 저장
customerScript.InitializeAgent(); // NavMeshAgent 초기화
}
break;
>>>>>>> BEDev
}
}
}
}
public void InitializeAgent() {
agent = GetComponent<NavMeshAgent>();
if (agent != null) {
agent.updateRotation = false;
agent.updateUpAxis = false;
MoveToSitArea();
} else {
// Debug.LogError("NavMeshAgent component is not found on the instantiated object.");
}
}
// public void MoveToSitArea()
// {
<<<<<<< HEAD
// // agent.SetDestination(target.position);
// if (agent == null)
// {
// Debug.LogError("NavMeshAgent component is not found.");
// return;
// }
=======
void OnDisable() {
FoodArriveEvent.OnFoodDelivered -= HandleFoodDelivery;
}
private void HandleFoodDelivery(bool isCorrect, GameObject customer) {
if (isCorrect && customer == this.gameObject) {
SpriteRenderer customerSpriteRenderer = customer.transform.Find("Square/status").GetComponent<SpriteRenderer>();
TextMesh customerTextMesh = customer.transform.Find("textstatus")?.GetComponent<TextMesh>();
// 만족하는 텍스트 메시지들의 배열
string[] satisfactionTexts = new string[] {
"맛있네! 또 와야겠어!",
"이렇게 맛있는 집이 있었다고?",
"간만에 맛있게 먹었다!",
"다음에 또 와야지..",
"거 음식 잘하는 양반이네"
};
if (customerSpriteRenderer != null) {
customerSpriteRenderer.enabled = false;
if (customerTextMesh != null) {
// 텍스트 메시지를 랜덤으로 선택하여 설정
StartCoroutine(WaitAndMove(2)); // 2초간 기다리는 것으로 설정
int randomIndex = Random.Range(0, satisfactionTexts.Length);
customerTextMesh.text = satisfactionTexts[randomIndex];
customerTextMesh.gameObject.SetActive(true); // TextMesh를 활성화
ActivateTargetAgain(customer);
}
else {
// Debug.LogError("TextMesh component not found on 'textstatus'.");
}
} else {
// Debug.LogError("No Sprite Renderer found on customer's child object.");
}
} else {
// Debug.Log("Incorrect food delivered.");
}
}
private void ActivateTargetAgain(GameObject customer)
{
// 타겟을 찾아 활성화하는 로직을 여기에 구현합니다.
int targetIndex = targets.IndexOf(customer.transform); // 예시로 사용한 방법입니다. 실제 구현에는 타겟 인덱스를 추적하는 더 나은 방법을 사용해야 할 수 있습니다.
if (targetIndex != -1)
{
targetsActive[targetIndex] = true;
targets[targetIndex].gameObject.SetActive(true);
}
}
private IEnumerator WaitAndMove(float waitTime) {
yield return new WaitForSeconds(waitTime);
MoveToSpawnPoint();
}
public void MoveToSpawnPoint() {
StartCoroutine(MoveToSpawnAndDestroy()); // 코루틴 시작
}
private IEnumerator MoveToSpawnAndDestroy() {
if (agent != null) {
agent.SetDestination(spawnPoint);
// Debug.Log("Returning to spawn point.");
// NavMeshAgent가 목적지에 도착할 때까지 기다립니다.
while (!agent.pathPending && agent.remainingDistance > 0.1f) {
yield return null; // 다음 프레임까지 기다립니다.
}
// 도착 후 2초간 기다립니다.
yield return new WaitForSeconds(2);
// NPC 인스턴스(복제본) 삭제
Destroy(gameObject);
} else {
// Debug.LogError("NavMeshAgent component is not found.");
}
}
>>>>>>> BEDev
// SuperObject[] sitAreas = FindObjectsOfType<SuperObject>();
// foreach (var area in sitAreas)
// {
// var properties = area.GetComponent<SuperCustomProperties>();
// if (properties != null)
// {
// Debug.Log("Moving NPC to area: " + area.transform.position);
// agent.SetDestination(area.transform.position);
// break;
// }
// }
// }
public void MoveToSitArea() {
targetsActive = new List<bool>(); // 이 줄을 추가하여 리스트를 초기화합니다.
foreach (var target in targets) {
targetsActive.Add(target.gameObject.activeSelf);
}
if (agent == null) {
// Debug.LogError("NavMeshAgent component is not found.");
return;
}
if (targets == null) {
// Debug.LogError("Targets list is null.");
return;
}
if (targetsActive == null) {
// Debug.LogError("TargetsActive list is null");
}
List<int> activeTargets = new List<int>();
for (int i = 0; i < targetsActive.Count; i++) {
if (targets[i] == null) {
// Debug.LogError($"Target at index {i} is null.");
} else if (targetsActive[i]) {
activeTargets.Add(i);
}
}
if (activeTargets.Count > 0) {
int randomIndex = Random.Range(0, activeTargets.Count);
int targetIndex = activeTargets[randomIndex];
if (targets[targetIndex] == null) {
// Debug.LogError($"Target at index {targetIndex} is null.");
return;
}
// // Debug.Log("Moving NPC to target: " + targets[targetIndex].position);
agent.SetDestination(targets[targetIndex].position);
// // Debug.Log("목적 설정");
StartCoroutine(CheckIfArrived(targetIndex, targets[targetIndex].position));
// // Debug.Log("체크 설정");
} else {
// Debug.Log("No active targets available.");
}
}
private int FindNextActiveTargetIndex() {
for (int i = 0; i < targetsActive.Count; i++) {
if (targetsActive[i]) return i;
}
return -1; // 모든 타겟이 비활성화된 경우
}
// 타겟에 도착했는지 확인하는 코루틴
IEnumerator CheckIfArrived(int targetIndex, Vector3 targetPosition) {
while (true) {
yield return new WaitForSeconds(0.5f); // 주기적으로 체크
<<<<<<< HEAD
// 타겟에 충분히 가까워졌는지 확인
// 타겟에 도착했다고 간주, OnTargetReached 호출
=======
while (true) {
// 타겟과의 현재 거리 계산
float distance = Vector3.Distance(agent.transform.position, targetPosition);
// 거리가 임계값 이하인지 확인
if (distance <= thresholdDistance) {
// // Debug.Log("Target reached: " + targetIndex);
>>>>>>> BEDev
OnTargetReached(targetIndex);
Debug.Log("OnTargetReached호출");
break;
}
}
void OnTargetReached(int targetIndex) {
targetsActive[targetIndex] = false; // 해당 타겟을 비활성화 상태로 변경
targets[targetIndex].gameObject.SetActive(false); // 타겟 게임 오브젝트를 비활성화
<<<<<<< HEAD
if (!IsAnyTargetActive()) {
Debug.Log("모든 타겟을 방문했습니다.");
// 여기서 필요하다면 NPC 생성을 멈출 수 있습니다.
=======
ShowFoodImage(targetIndex);
if (!IsAnyTargetActive()) {
// Debug.Log("모든 타겟을 방문했습니다.");
>>>>>>> BEDev
} else {
}
StartCoroutine(WaitAndChangeImageOrLeave(targetIndex, this.gameObject));
}
private IEnumerator WaitAndChangeImageOrLeave(int targetIndex, GameObject customer) {
yield return new WaitForSeconds(20); // 15초 기다립니다.
SpriteRenderer customerSpriteRenderer = customer.transform.Find("Square/status").GetComponent<SpriteRenderer>();
TextMesh customerTextMesh = customer.transform.Find("textstatus")?.GetComponent<TextMesh>();
string[] texts = new string[] {
"뭐야..배고파 죽겠는데",
"여기 별로네"
};
// 15초 후 실행되는 로직
if (targetsActive[targetIndex] == false) { // 플레이어가 서빙하지 않았다면
SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer != null) {
customerSpriteRenderer.enabled = false;
int randomIndex = Random.Range(0, texts.Length);
customerTextMesh.text = texts[randomIndex];
customerTextMesh.gameObject.SetActive(true); // TextMesh를 활성화
}
MoveToSpawnPoint(); // NPC를 스폰 포인트로 이동
}
}
void ShowFoodImage(int targetIndex) {
MenuManager menuManager = FindObjectOfType<MenuManager>(); // 메뉴 매니저 인스턴스를 찾습니다.
<<<<<<< HEAD
}
=======
if (menuManager != null) {
MenuItem randomFood = menuManager.GetRandomFoodItem(); // 랜덤 음식 아이템을 가져옵니다.
if (randomFood != null && randomFood.image != null && foodImageUI != null) {
SpriteRenderer spriteRenderer = foodImageUI.GetComponent<SpriteRenderer>();
if (spriteRenderer != null) {
spriteRenderer.sprite = randomFood.image;
// Debug.Log("FoodImage displayed on the GameObject");
} else {
// Debug.LogError("SpriteRenderer component is not found on the foodImageUI GameObject.");
}
}
else {
MoveToSpawnPoint();
}
}
}
>>>>>>> BEDev
void Update()
{
// NavMeshAgent의 이동 상태에 따라 애니메이션을 업데이트
if (agent != null && animator != null)
{
Vector2 velocity = agent.velocity;
animator.SetBool("Walking", velocity.magnitude > 0.1f);
animator.SetFloat("DirX", velocity.x);
animator.SetFloat("DirY", velocity.y);
}
}
} |
# Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for
# the specific language governing permissions and limitations under the License.
import sys
import unittest
try:
from unittest.mock import MagicMock
except ImportError:
from mock import MagicMock
import botocore
##############
# Parameters #
##############
# Define the default resouce to report to Config Rules
DEFAULT_RESOURCE_TYPE = 'AWS::EC2::VPCEndpointService'
#############
# Main Code #
#############
CONFIG_CLIENT_MOCK = MagicMock()
STS_CLIENT_MOCK = MagicMock()
EC2_CLIENT_MOCK = MagicMock()
class Boto3Mock():
@staticmethod
def client(client_name, *args, **kwargs):
if client_name == 'config':
return CONFIG_CLIENT_MOCK
if client_name == 'sts':
return STS_CLIENT_MOCK
if client_name == 'ec2':
return EC2_CLIENT_MOCK
raise Exception("Attempting to create an unknown client")
sys.modules['boto3'] = Boto3Mock()
RULE = __import__('VPC_ENDPOINT_MANUAL_ACCEPTANCE')
class ComplianceTest(unittest.TestCase):
no_customer_endpointservices = {"ServiceDetails": [{"ServiceName": "com.amazonaws.us-east-1.transfer.server", "Owner": "amazon", "AcceptanceRequired": False}]}
customer_es_true = {"ServiceDetails": [{"AcceptanceRequired": True, "ServiceName": "com.amazonaws.vpce.us-west-2.vpce-svc-0000000000", "Owner": "123456789012"}, {"ServiceName": "com.amazonaws.us-east-1.transfer.server", "Owner": "amazon", "AcceptanceRequired": False}]}
customer_es_false = {"ServiceDetails": [{"AcceptanceRequired": False, "ServiceName": "com.amazonaws.vpce.us-west-2.vpce-svc-0000000000", "Owner": "123456789012"}, {"ServiceName": "com.amazonaws.us-east-1.transfer.server", "Owner": "amazon", "AcceptanceRequired": False}]}
def setUp(self):
pass
def test_sample_no_cx_es(self):
EC2_CLIENT_MOCK.describe_vpc_endpoint_services = MagicMock(return_value=self.no_customer_endpointservices)
RULE.ASSUME_ROLE_MODE = False
response = RULE.lambda_handler(build_lambda_scheduled_event(), {})
resp_expected = []
resp_expected.append(build_expected_response('NOT_APPLICABLE', '123456789012', 'AWS::::Account'))
assert_successful_evaluation(self, response, resp_expected)
def test_sample_cx_es_true(self):
EC2_CLIENT_MOCK.describe_vpc_endpoint_services = MagicMock(return_value=self.customer_es_true)
RULE.ASSUME_ROLE_MODE = False
response = RULE.lambda_handler(build_lambda_scheduled_event(), {})
resp_expected = []
resp_expected.append(build_expected_response('COMPLIANT', 'com.amazonaws.vpce.us-west-2.vpce-svc-0000000000', 'AWS::EC2::VPCEndpointService'))
assert_successful_evaluation(self, response, resp_expected)
def test_sample_cx_es_false(self):
EC2_CLIENT_MOCK.describe_vpc_endpoint_services = MagicMock(return_value=self.customer_es_false)
RULE.ASSUME_ROLE_MODE = False
response = RULE.lambda_handler(build_lambda_scheduled_event(), {})
resp_expected = []
resp_expected.append(build_expected_response('NON_COMPLIANT', 'com.amazonaws.vpce.us-west-2.vpce-svc-0000000000', 'AWS::EC2::VPCEndpointService', 'The Endpoint Service has "AcceptanceRequired" set to False.'))
assert_successful_evaluation(self, response, resp_expected)
####################
# Helper Functions #
####################
def build_lambda_configurationchange_event(invoking_event, rule_parameters=None):
event_to_return = {
'configRuleName':'myrule',
'executionRoleArn':'roleArn',
'eventLeftScope': False,
'invokingEvent': invoking_event,
'accountId': '123456789012',
'configRuleArn': 'arn:aws:config:us-east-1:123456789012:config-rule/config-rule-8fngan',
'resultToken':'token'
}
if rule_parameters:
event_to_return['ruleParameters'] = rule_parameters
return event_to_return
def build_lambda_scheduled_event(rule_parameters=None):
invoking_event = '{"messageType":"ScheduledNotification","notificationCreationTime":"2017-12-23T22:11:18.158Z"}'
event_to_return = {
'configRuleName':'myrule',
'executionRoleArn':'roleArn',
'eventLeftScope': False,
'invokingEvent': invoking_event,
'accountId': '123456789012',
'configRuleArn': 'arn:aws:config:us-east-1:123456789012:config-rule/config-rule-8fngan',
'resultToken':'token'
}
if rule_parameters:
event_to_return['ruleParameters'] = rule_parameters
return event_to_return
def build_expected_response(compliance_type, compliance_resource_id, compliance_resource_type=DEFAULT_RESOURCE_TYPE, annotation=None):
if not annotation:
return {
'ComplianceType': compliance_type,
'ComplianceResourceId': compliance_resource_id,
'ComplianceResourceType': compliance_resource_type
}
return {
'ComplianceType': compliance_type,
'ComplianceResourceId': compliance_resource_id,
'ComplianceResourceType': compliance_resource_type,
'Annotation': annotation
}
def assert_successful_evaluation(test_class, response, resp_expected, evaluations_count=1):
if isinstance(response, dict):
test_class.assertEquals(resp_expected['ComplianceResourceType'], response['ComplianceResourceType'])
test_class.assertEquals(resp_expected['ComplianceResourceId'], response['ComplianceResourceId'])
test_class.assertEquals(resp_expected['ComplianceType'], response['ComplianceType'])
test_class.assertTrue(response['OrderingTimestamp'])
if 'Annotation' in resp_expected or 'Annotation' in response:
test_class.assertEquals(resp_expected['Annotation'], response['Annotation'])
elif isinstance(response, list):
test_class.assertEquals(evaluations_count, len(response))
for i, response_expected in enumerate(resp_expected):
test_class.assertEquals(response_expected['ComplianceResourceType'], response[i]['ComplianceResourceType'])
test_class.assertEquals(response_expected['ComplianceResourceId'], response[i]['ComplianceResourceId'])
test_class.assertEquals(response_expected['ComplianceType'], response[i]['ComplianceType'])
test_class.assertTrue(response[i]['OrderingTimestamp'])
if 'Annotation' in response_expected or 'Annotation' in response[i]:
test_class.assertEquals(response_expected['Annotation'], response[i]['Annotation'])
def assert_customer_error_response(test_class, response, customer_error_code=None, customer_error_message=None):
if customer_error_code:
test_class.assertEqual(customer_error_code, response['customerErrorCode'])
if customer_error_message:
test_class.assertEqual(customer_error_message, response['customerErrorMessage'])
test_class.assertTrue(response['customerErrorCode'])
test_class.assertTrue(response['customerErrorMessage'])
if "internalErrorMessage" in response:
test_class.assertTrue(response['internalErrorMessage'])
if "internalErrorDetails" in response:
test_class.assertTrue(response['internalErrorDetails'])
def sts_mock():
assume_role_response = {
"Credentials": {
"AccessKeyId": "string",
"SecretAccessKey": "string",
"SessionToken": "string"}}
STS_CLIENT_MOCK.reset_mock(return_value=True)
STS_CLIENT_MOCK.assume_role = MagicMock(return_value=assume_role_response)
##################
# Common Testing #
##################
class TestStsErrors(unittest.TestCase):
def test_sts_unknown_error(self):
RULE.ASSUME_ROLE_MODE = True
STS_CLIENT_MOCK.assume_role = MagicMock(side_effect=botocore.exceptions.ClientError(
{'Error': {'Code': 'unknown-code', 'Message': 'unknown-message'}}, 'operation'))
response = RULE.lambda_handler(build_lambda_configurationchange_event('{}'), {})
assert_customer_error_response(
self, response, 'InternalError', 'InternalError')
def test_sts_access_denied(self):
RULE.ASSUME_ROLE_MODE = True
STS_CLIENT_MOCK.assume_role = MagicMock(side_effect=botocore.exceptions.ClientError(
{'Error': {'Code': 'AccessDenied', 'Message': 'access-denied'}}, 'operation'))
response = RULE.lambda_handler(build_lambda_configurationchange_event('{}'), {})
assert_customer_error_response(
self, response, 'AccessDenied', 'AWS Config does not have permission to assume the IAM role.') |
# Java BitSet |交集()
> 原文:[https://www.geeksforgeeks.org/java-bitset-intersects/](https://www.geeksforgeeks.org/java-bitset-intersects/)
[位集](https://www.geeksforgeeks.org/bitset-class-java-set-1)是在 [java.util](https://www.geeksforgeeks.org/java-util-package-java/) 包中定义的一个类。它创建了一个由 0 和 1 表示的位数组。
**语法**
```java
public boolean intersects(BitSet set)
```
**参数:**该方法接受一个强制参数**集**,这是要检查交集的位集。
**返回:**该方法返回一个布尔值,指示该位集是否与指定的位集相交。
**说明:**如果指定的位集中有任何设置为真的位在该位集中也设置为真,则该方法返回真,否则返回假。
**示例:**
```java
Input :
set1 : {1, 2, 4}
set2 : {}
Output :
false
```
## Java
```java
// Java program illustrating Bitset Class functions.
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Constructors of BitSet class
BitSet bs1 = new BitSet();
BitSet bs2 = new BitSet();
BitSet bs3 = new BitSet();
/* set is BitSet class method
explained in next articles */
bs1.set(0);
bs1.set(1);
bs1.set(2);
bs1.set(4);
// assign values to bs2
bs2.set(4);
bs2.set(6);
bs2.set(5);
bs2.set(1);
bs2.set(2);
bs2.set(3);
// Printing the 2 Bitsets
System.out.println("bs1 : " + bs1);
System.out.println("bs2 : " + bs2);
System.out.println("bs3 : " + bs3);
// Performing intersects on two bitset
System.out.println("bs1 intersection bs3 = "
+ bs1.intersects(bs2));
System.out.println("bs3 intersection bs1 = "
+ bs3.intersects(bs1));
}
}
```
**输出:**
```java
bs1 : {0, 1, 2, 4}
bs2 : {1, 2, 3, 4, 5, 6}
bs3 : {}
bs1 intersection bs3 = true
bs3 intersection bs1 = false
```
**相关文章:**
1. [Sample set of bit set class 1](https://www.geeksforgeeks.org/bitset-class-java-set-1/)
2. [Sample set of bit set class 2](https://www.geeksforgeeks.org/bitset-class-methods-java-examples-set-2/)
3. [Sample set of bit set class 3](https://www.geeksforgeeks.org/bitset-class-methods-java-examples-set-3/) |
---
import { type CollectionEntry, getCollection } from "astro:content";
import Layout from "@layouts/Layout.astro";
import PageTitle from "@components/ui/PageTitle.astro";
import { toSlug } from "@utils/page";
export const prerender = true;
export const getStaticPaths = async () => {
const projects = await getCollection("projects");
return projects.map((project) => {
return {
params: {
slug: toSlug(project.data.title),
},
props: {
project,
},
};
});
};
export interface Props {
project: CollectionEntry<"projects">;
}
const { project } = Astro.props;
const { Content } = await project.render();
---
<Layout title={project.data.title}>
<main class="p-8 flex flex-col">
<header class="pb-6">
<a href="/projects" class="under after:bg-green-500 font-bold"
>← Back to Projects</a
>
<PageTitle
text={project.data.title}
textClass={"text-[3.5rem] xs:text-6xl font-serif font-bold w-full flex justify-center"}
periodClass={"text-green-500"}
/>
<h3 class="text-gray-300 pb-4 w-full flex justify-center">
{project.data.description}
</h3>
</header>
<section class="flex flex-col m-auto">
<article class="w-full md:w-2/3 mx-auto py-4">
<h2 class="text-4xl font-serif font-bold py-2">
Tech<span class="text-green-500">.</span>
</h2>
{
project.data.video && (
<div class="flex justify-center md:block py-4 relative pb-[56.4%]">
<iframe
class="absolute w-full h-full top-0 left-0 pr-8 md:pr-4"
src={project.data.video}
title="YouTube video player"
frame-border="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allow-fullScreen
/>
</div>
)
}
{
project.data.url && (
<div class="py-4">
<a
class="underline decoration-green-500"
href={project.data.url}
target="_blank"
rel="noreferrer"
>
Try {project.data.title}
</a>
</div>
)
}
<section class="text-gray-300">
<section class="flex gap-4">
<h4>Repository:</h4>
{
project.data.repositories.map((repo) => (
<a
class="underline decoration-green-500"
href={repo.url}
target="_blank"
rel="noreferrer"
>
{repo.name}
</a>
))
}
</section>
<section class="py-2">
<h4>Tech Stack:</h4>
<ul class="max-w-4/5 flex flex-wrap">
{project.data.stack.map((tech) => <li class="pr-2">{tech}</li>)}
</ul>
</section>
</section>
</article>
<article class="project-content w-full md:w-2/3 mx-auto py-4">
<h2 class="text-4xl font-serif font-bold py-2">
About<span class="text-green-500">.</span>
</h2>
<Content />
</article>
</section>
</main>
</Layout>
<style lang="scss" is:global>
.project-content {
p {
color: #a1a1aa;
padding: 0.5rem 0;
}
}
</style> |
<?xml version="1.0" ?>
<!DOCTYPE book PUBLIC "-//KDE//DTD DocBook XML V4.2-Based Variant V1.1//EN" "dtd/kdex.dtd" [
<!ENTITY kappname "&okular;">
<!ENTITY latex "L<superscript>A</superscript>T<subscript>E</subscript>X">
<!ENTITY package "kdegraphics">
<!ENTITY kpdf "<application>KPDF</application>">
<!ENTITY PDF "<acronym>PDF</acronym>">
<!ENTITY % English "INCLUDE">
<!ENTITY % addindex "IGNORE">
]>
<!-- TODO
add chapter about navigation panel
Show/Hide Contens/Thumbnails/Reviews/Bookmarks bar to save screen space
Use Small Icons and deselect Show Text to minimize the navigation panel
Describe all actions only possible in the navigation bars:
Switching between documents using bookmarks
Context menu actions like Rename Bookmarks etc.)
-->
<book id="okular" lang="&language;">
<bookinfo>
<title>The &okular; Handbook</title>
<authorgroup>
<author>
<firstname>Albert</firstname>
<surname>Astals Cid</surname>
<affiliation>
<address>&Albert.Astals.Cid.mail;</address>
</affiliation>
</author>
<author>
<firstname>Pino</firstname>
<surname>Toscano</surname>
<affiliation>
<address><email>pino@kde.org</email></address>
</affiliation>
</author>
<!-- TRANS:ROLES_OF_TRANSLATORS -->
</authorgroup>
<legalnotice>&FDLNotice;</legalnotice>
<date>2014-02-25</date>
<releaseinfo>0.19 (&kde; 4.13)</releaseinfo>
<!-- Abstract about this handbook -->
<abstract>
<para>&okular; is a &kde; universal document viewer based on &kpdf; code.</para>
</abstract>
<keywordset>
<keyword>KDE</keyword>
<keyword>okular</keyword>
<keyword>pdf</keyword>
<keyword>ps</keyword>
<keyword>postscript</keyword>
<keyword>tiff</keyword>
<keyword>djvu</keyword>
<keyword>dvi</keyword>
<keyword>chm</keyword>
<keyword>xps</keyword>
<keyword>comicbook</keyword>
<keyword>fictionbook</keyword>
<keyword>mobipocket</keyword>
<keyword>plucker</keyword>
<keyword>annotation</keyword>
</keywordset>
</bookinfo>
<chapter id="introduction">
<title>Introduction</title>
<para>&okular; is a &kde; universal document viewer based on the code of the &kpdf; application.
Although being based on &kpdf; code, &okular; has some unique features such as overview mode,
improved presentation support and annotation support.
</para>
<para>
&okular; supports a lot of different formats like &PDF;, &PostScript;, Tiff, CHM, DjVU, Images (png, jpg, &etc;)
XPS, Open Document (ODT), Fiction Books, Comic Book, Plucker, EPub and Fax.
For all supported formats and their features see <ulink url="http://okular.kde.org/formats.php">
&okular; Document Format Handlers</ulink>.
</para>
<screenshot>
<screeninfo>&okular;s Main Window</screeninfo>
<mediaobject>
<imageobject>
<imagedata fileref="mainwindow.png" format="PNG" />
</imageobject>
<textobject>
<phrase>&okular;s Main Window</phrase>
</textobject>
</mediaobject>
</screenshot>
</chapter>
<chapter id="use">
<title>Basic Usage</title>
<sect1 id="opening">
<title>Opening Files</title>
<para>
To view any supported file in &okular;, select <menuchoice><guimenu>File</guimenu><guimenuitem>Open...</guimenuitem>
</menuchoice>, choose a supported file in the dialog and click <guibutton>Open</guibutton>.
Your file should now be displayed in the main window.
</para>
<important>
<para>
The new document will be opened in a new tab should the <guilabel>Open new files in tabs</guilabel> option on the <link linkend="configgeneral">General configuration page</link> is checked.
</para>
</important>
<para>
If you have already opened files in &okular; before, you can quickly access them by selecting them in
the <menuchoice><guimenu>File</guimenu><guisubmenu>Open Recent</guisubmenu></menuchoice> menu.
</para>
<para>&okular; is the default &kde; application for &PDF; and &PostScript; files, launched when you click with the
&LMB; on such a file type in the filemanager. If you want to open any file whose format is supported by &okular;
use <menuchoice><guimenu>Open with...</guimenu><guimenuitem>&okular;</guimenuitem> </menuchoice> from context
menu in the filemanager.
</para>
<para>
After having a file opened you probably want to read it and therefore navigate through it. Go to the
<link linkend="navigating">next section</link> to learn more about this.
</para>
</sect1>
<sect1 id="navigating">
<title>Navigating</title>
<para>This section describes how you can navigate through a document in &okular;.</para>
<para>
There are multiple ways of scrolling the viewing area. One is to use the
<keysym>Up Arrow</keysym> and <keysym>Down Arrow</keysym> keys. You may also use
the scrollbar, your mousewheel or the <keycap>Page Up</keycap> and <keycap>Page Down</keycap>
keys.
</para>
<para>
You can also use <application>vim</application>-like navigation keys, namely <keycap>H</keycap> to move to the top of the previous page, <keycap>L</keycap> to move to the top of the next page, <keycap>J</keycap> to move one line down, and <keycap>K</keycap> to move one line up.
</para>
<para>
Another way is to hold the &LMB; down at any place on the document while dragging the mouse in the
opposite direction of where you want to move. This procedure only works if the Browse Tool is
enabled, which you can select by choosing <menuchoice><guimenu>Tools</guimenu>
<guimenuitem>Browse Tool</guimenuitem></menuchoice>.
</para>
<note>
<para>
When viewing a document in the <link linkend="presentationMode">Presentation mode</link> use <keysym>Up Arrow</keysym> and <keysym>Down Arrow</keysym> keys to switch between pages or slides. The number and the position of the current slide will be shown in the overlay at the right upper corner of screen.
</para>
</note>
<para>If you want to read a document with several pages use the automatic scrolling feature of &okular;.
Start automatic scrolling with <keycombo action="simul">&Shift;<keysym>Down Arrow</keysym></keycombo> or
<keycombo action="simul">&Shift;<keysym>Up Arrow</keysym></keycombo>. Then use these keys to increase and
decrease the scrolling speed. You can start or stop automatic scrolling temporarily by pressing the &Shift; key;
pressing any other key deactivates this feature.
</para>
<para>Another way to navigate through a document with several pages is to use the mouse pointer. Drag the page up or down, continue to drag even while reaching the bottom or top of the screen and behold.
Once you cross the border of a page, the mouse cursor appears on top or bottom of the screen again and you can just continue to drag.
</para>
<para>
The navigation panel on the left side of the screen enables two more ways of navigating
through a document:
</para>
<itemizedlist>
<listitem>
<para>
If you click on a page thumbnail the viewing area will be brought to
that page.
</para>
</listitem>
<listitem>
<para>
If the document has a table of contents, clicking on a table
of contents item will bring the document to the page linked to that
item.
</para>
</listitem>
<listitem>
<para>
If the document has bookmarks, enable the <guilabel>Bookmarks</guilabel> view
and click them to go to the associated page.
If bookmarks are not only shown for the current document, you can quickly
switch to bookmarks in all recently opened files.
</para>
</listitem>
<listitem>
<para>
If the document has annotations, enable the <guilabel>Reviews</guilabel> view
and click the annotations or select them with the <keysym>Up Arrow</keysym> and <keysym>Down Arrow</keysym> keys and press <keycap>Return</keycap> to go to the associated page.
</para>
</listitem>
</itemizedlist>
<para>
Some documents have links. In this case you can click on them and the view will
change to the page it links to. If the link is to a web page or some
other document the default &kde; handler for that format will be invoked.
For example, clicking on a link pointing to <quote>http://www.kde.org</quote>
will open the web page in the default &kde;'s web browser.
</para>
<important>
<para>
The document internal links work only when <link linkend="menutools">Browse Tool</link> is used.
</para>
</important>
<para>
Additionally, you may use the following functionality to quickly move to specific places
in the document:
</para>
<itemizedlist>
<listitem>
<para>
You can go to the beginning of the document using
<keycombo action="simul">&Ctrl;<keycap>Home</keycap></keycombo> or
using
<menuchoice>
<guimenu>Go</guimenu>
<guimenuitem>Beginning of the document</guimenuitem>
</menuchoice>.
</para>
</listitem>
<listitem>
<para>
You can go to the end of the document using
<keycombo action="simul">&Ctrl;<keycap>End</keycap></keycombo> or
using
<menuchoice>
<guimenu>Go</guimenu>
<guimenuitem>End of the document</guimenuitem>
</menuchoice>.
</para>
</listitem>
<listitem>
<para>
You can go forward in the document using <keycap>Space</keycap> or <keycap>Page Down</keycap>.
To go to the next page of the document use the <guibutton>Next Page</guibutton> Toolbar
button or
<menuchoice>
<guimenu>Go</guimenu>
<guimenuitem>Next Page</guimenuitem>
</menuchoice> in the menubar.
</para>
</listitem>
<listitem>
<para>
You can go back in the document using &Backspace; or <keycap>Page Up</keycap>.
To go to the previous page of the document use <guibutton>Previous Page</guibutton> Toolbar
button or
<menuchoice>
<guimenu>Go</guimenu>
<guimenuitem>Previous Page</guimenuitem>
</menuchoice> in the menubar.
</para>
</listitem>
<listitem>
<para>
You can go back to the positions in the document where you came from in a chronological order.
Consider ⪚ reading the phrase <quote>As shown in [15], …</quote>, and you want
to know quickly lookup reference [15]. So you click on it, and &okular; will jump to the list
of references. Using <keycombo>&Alt;&Shift;<keysym>Left</keysym></keycombo> or
<menuchoice>
<guimenu>Go</guimenu>
<guimenuitem>Back</guimenuitem>
</menuchoice> in the menubar will bring you back to exactly the position where you came from.
</para>
</listitem>
<listitem>
<para>
You can go forward in the document after the jumping back as described above using
<keycombo>&Alt;&Shift;<keysym>Right</keysym></keycombo> or
<menuchoice>
<guimenu>Go</guimenu>
<guimenuitem>Forward</guimenuitem>
</menuchoice> in the menubar.
</para>
</listitem>
<listitem>
<para>
You can go to the next match when searching using
<keycap>F3</keycap> or &Enter; (when the focus is on <guilabel>Find</guilabel> text field) keys or
<menuchoice>
<guimenu>Edit</guimenu>
<guimenuitem>Find Next</guimenuitem>
</menuchoice>
menu item or move back to the previous match using
<keycombo>&Shift;<keysym>F3</keysym></keycombo> or <keycombo>&Shift;&Enter;</keycombo> (when the focus is on <guilabel>Find</guilabel> text field) keys or
<menuchoice>
<guimenu>Edit</guimenu>
<guimenuitem>Find Previous</guimenuitem>
</menuchoice>
menu item.
</para>
</listitem>
</itemizedlist>
</sect1>
<sect1 id="presentationMode">
<title>Presentation Mode</title>
<para>
The Presentation mode represents another way to view documents in &okular;. It can be
enabled in
<menuchoice><guimenu>View</guimenu><guimenuitem>Presentation</guimenuitem></menuchoice>.
It shows the document on a page per page basis. The pages are shown with
zoom to page, that means all the page is visible.
</para>
<note>
<para>
&PDF; documents can even specify that they are always opened in presentation mode.
</para>
</note>
<para>
When in presentation mode, you have an helper bar located on the top of the screen. Just move
the mouse cursor to the top of the screen to make it appear.
</para>
<screenshot>
<screeninfo>&okular; in Presentation Mode</screeninfo>
<mediaobject>
<imageobject>
<imagedata fileref="presentation.png" format="PNG" />
</imageobject>
<textobject>
<phrase>&okular; in Presentation Mode</phrase>
</textobject>
</mediaobject>
</screenshot>
<para>
To navigate between
pages you may use the &LMB; (next page) and the &RMB; (previous page), the mouse
wheel, the arrow icons or the line edit in the top bar,
or the keys specified in the <link linkend="navigating">Navigating</link>
section.
</para>
<para>
Use <guilabel>Play/Pause</guilabel> button in the top bar to start playing presentation or pause it, correspondingly.
</para>
<para>
You can exit presentation mode at any time by pressing the &Esc; key or clicking
the <guiicon>Quit</guiicon> icon in the top bar.
</para>
<para>
You can also draw on the current page with a pencil. Click on the
<guilabel>Toggle Drawing Mode</guilabel> icon in the top bar to enable or disable the possibility
to draw in the presentation mode. The drawings are cleared automatically when leaving the presentation
mode. You can also click on the <guilabel>Erase Drawings</guilabel> icon to remove the
drawings in the current page.
</para>
<para>
The presentation mode has support for more than one screen in a multi-monitor configuration.
With more than one screen a new button will appear in the top bar, with the icon of a screen:
this is a drop down box that allows you to move the presentation to any of the other available screens.
</para>
<para>
Presentation mode has some configuration options, you can find their
description in the chapter <link linkend="configpresentation">Configuring &okular;</link>.
</para>
</sect1>
<sect1 id="inverse_search">
<title>Inverse Search between &latex; Editors and &okular;</title>
<para>Inverse search is a very useful feature when you are writing a &latex; document yourself. If everything is set up properly, you can
click into &okular;'s window with the <mousebutton>left</mousebutton> mouse button while pressing &Shift;. After that editor loads the &latex; source file and jumps to
the proper paragraph.</para>
<para>Inverse search cannot work unless:</para>
<itemizedlist>
<listitem><para>The source file has been compiled successfully.</para></listitem>
<listitem><para>&okular; knows which editor you would like to use.</para></listitem>
<listitem><para>The Browse Tool has to be enabled, which you can select by choosing
<menuchoice><guimenu>Tools</guimenu><guimenuitem>Browse Tool
</guimenuitem></menuchoice>.</para></listitem>
</itemizedlist>
<para>With this feature of &okular;, a left mouse click while pressing &Shift; in the &DVI; or &PDF; document will
result in editor opening the corresponding &latex; document and attempt to go to the
corresponding line. Remember to tell &okular; to use proper editor, in &okular;'s
menu item <menuchoice><guimenu>Settings</guimenu><guimenuitem>Configure Okular...</guimenuitem></menuchoice>
(on the page <guimenuitem>Editor</guimenuitem>).</para>
<para>For more details on editor configuration please refer to the <link linkend="configeditor">corresponding section of this manual</link>.</para>
<screenshot>
<screeninfo>Configuring &okular;</screeninfo>
<mediaobject>
<imageobject>
<imagedata fileref="configure-editor.png" format="PNG" />
</imageobject>
<textobject>
<phrase>Configuring editor in &okular;</phrase>
</textobject>
<caption><para>Configuring editor in &okular;</para></caption>
</mediaobject>
</screenshot>
</sect1>
</chapter>
<chapter id="advanced">
<title>&okular; Advanced Features</title>
<sect1 id="embedded-files">
<title>Embedded Files</title>
<para>
If the current document has some files embedded in it, when you open it a yellow bar
will appear above the page view to notify you about the embedded files.
</para>
<screenshot>
<screeninfo>The embedded files bar</screeninfo>
<mediaobject>
<imageobject>
<imagedata fileref="embedded-files-bar.png" format="PNG" />
</imageobject>
<textobject>
<phrase>The embedded files bar</phrase>
</textobject>
</mediaobject>
</screenshot>
<para>
In this case, you can either click on the link in the text of the bar or choose
<menuchoice><guimenu>File</guimenu><guimenuitem>Embedded Files</guimenuitem></menuchoice>
to open the embedded files dialog. The dialog allows you to view the embedded files and
to extract them.
</para>
</sect1>
<sect1 id="forms">
<title>Forms</title>
<para>
If the current document has forms, when you open it a bar
will appear above the page view where you can enable the forms.
</para>
<screenshot>
<screeninfo>The forms bar</screeninfo>
<mediaobject>
<imageobject>
<imagedata fileref="forms-bar.png" format="PNG" />
</imageobject>
<textobject>
<phrase>The forms bar</phrase>
</textobject>
</mediaobject>
</screenshot>
<para>
In this case, you can either click on <guilabel>Show Forms</guilabel> in the bar or choose
<menuchoice><guimenu>View</guimenu><guimenuitem>Show Forms</guimenuitem></menuchoice>
to enter data into the form fields.
</para>
</sect1>
<sect1 id="annotations">
<title>Annotations</title>
<para>
&okular; allows you to review and annotate your documents.
Annotations created in &okular; are automatically saved in the internal local data folder
for each user.
&okular; does not implicitly change any document it opens.
</para>
<screenshot>
<screeninfo>&okular;'s Annotations</screeninfo>
<mediaobject>
<imageobject>
<imagedata fileref="annotations.png" format="PNG" />
</imageobject>
<textobject>
<phrase>&okular;'s Annotations</phrase>
</textobject>
</mediaobject>
</screenshot>
<para>&okular; has two different kind of annotations:</para>
<para>Text annotations like <guilabel>Yellow Highlighter</guilabel> and <guilabel>Black Underlining</guilabel>
for files with text like ⪚ &PDF;.</para>
<para>Graphic annotations like <guilabel>Pop-up Note</guilabel>, <guilabel>Inline Note</guilabel>, <guilabel>Freehand Line</guilabel>, <guilabel>Highlighter</guilabel>, <guilabel>Straight Line</guilabel>, <guilabel>Polygon</guilabel>, <guilabel>Stamp</guilabel>, <guilabel>Underline</guilabel>, and <guilabel>Ellipse</guilabel> for all formats supported by &okular;.</para>
<para>Using the context menu either in the <guilabel>Reviews</guilabel> view of the navigation panel or in the main window you can open a <guilabel>Pop up Note</guilabel> for any kind of annotation and add or edit comments.</para>
<para>Annotations are not only limited to &PDF; files, they can be used for any format &okular; supports.</para>
<para>
Since &kde; 4.2, &okular; has the "document archiving" feature. This is an &okular;-specific format for carrying the document plus various metadata related to it (currently only annotations). You can save a "document archive" from the open document by choosing <menuchoice><guimenu>File</guimenu><guisubmenu>Export As</guisubmenu><guimenuitem>Document Archive</guimenuitem></menuchoice>. To open an &okular; document archive, just open it with &okular; as it would be ⪚ a &PDF; document.
</para>
<para>
Since &okular; 0.15 you can <emphasis>also</emphasis> save annotations directly into &PDF; files. This feature is only available if &okular; has been built with version 0.20 or later of <ulink url="http://poppler.freedesktop.org/">Poppler rendering library</ulink>. You can use <menuchoice><guimenu>File</guimenu> <guimenuitem>Save As...</guimenuitem></menuchoice> to save the copy of &PDF; file with annotations.
</para>
<note>
<para>
It is not possible to save annotations into &PDF; file if original file was encrypted and &okular; uses Poppler libraries of version which is lower than 0.22.
</para>
</note>
<note>
<para>
If you open a &PDF; with existing annotations, your annotation changes are not automatically saved in the internal local data folder, and you need to save the modified document (using <menuchoice><guimenu>File</guimenu><guimenuitem>Save As...</guimenuitem></menuchoice>) before closing it. Should you forget to do this &okular; will show confirmation window that allows you to save the document.
</para>
</note>
<note>
<para>
Due to DRM limitations (typically with &PDF; documents), adding, editing some properties
or removing annotations could not be possible.
</para>
</note>
<note>
<para>
Any action on annotations (creation and removal of annotations, editing arbitrary annotation properties, relocating annotations with &Ctrl;+drag, and editing the text contents of an annotation) can be <link linkend="edit-undo">undone</link> or <link linkend="edit-redo">redone</link> using the corresponding item from the <guimenu>Edit</guimenu> menu. It is also possible to undo the action by pressing <keycombo>&Ctrl;<keycap>Z</keycap></keycombo> and redo the undone action by pressing <keycombo>&Ctrl;&Shift;<keycap>Z</keycap></keycombo>.
</para>
</note>
<para>
Since &okular; 0.17 you can configure the default properties and appearance of each annotating tool. Please refer to the <link linkend="configannotations">corresponding section in this documentation</link>.
</para>
<sect2 id="annotations-add">
<title>Adding annotations</title>
<para>
To add some annotations to the document, you have to activate the annotating toolbar.
This is done by either selecting
<menuchoice><guimenu>Tools</guimenu><guimenuitem>Review</guimenuitem></menuchoice> or
pressing <keycap>F6</keycap>. Once the annotating toolbar is shown, just press one of
its buttons or use keyboard shortcuts (keys from <keycap>1</keycap> to <keycap>9</keycap>) to start constructing that annotation.
</para>
<para>
The annotating toolbar helps you to make annotations with drawings, shapes, and text messages. You can use the annotating toolbar to mark up a document (⪚ add lines, ellipses, polygons, stamps, highlights, underlines &etc;). The table below describes exactly what the default set of annotating toolbar buttons does.
</para>
<informaltable>
<tgroup cols="3">
<thead>
<row>
<entry>
Button
</entry>
<entry>
Tool Name
</entry>
<entry>
Description
</entry>
</row>
</thead>
<tbody>
<row>
<entry>
<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="tool-note-okular.png" format="PNG"/>
</imageobject>
</inlinemediaobject>
</para>
</entry>
<entry>
<para>
Pop-up Note
</para>
</entry>
<entry>
<para>
To draw multiline note. The note will can be viewed by double clicking on an icon in the document.
</para>
<para>
Click on the tool button, then click on the place in the document where the pop-up note should be added. Enter the text of pop-up note then click on the <guilabel>Close this note</guilabel> button in the top right corner of the pop-up window.
</para>
</entry>
</row>
<row>
<entry>
<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="tool-note-inline-okular.png" format="PNG"/>
</imageobject>
</inlinemediaobject>
</para>
</entry>
<entry>
<para>
Inline Note
</para>
</entry>
<entry>
<para>
To draw inline note. The note will be shown inline as is.
</para>
<para>
Click on the tool button, then click with the &LMB; and hold to place the top-left corner of the note, then drag to place the bottom-right one. Enter the text of the note then click on the <guibutton>OK</guibutton> to save the note, <guibutton>Cancel</guibutton> to cancel note entering or <guibutton>Clear</guibutton> to clear the note.
</para>
</entry>
</row>
<row>
<entry>
<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="tool-ink-okular.png" format="PNG"/>
</imageobject>
</inlinemediaobject>
</para>
</entry>
<entry>
<para>
Freehand Line
</para>
</entry>
<entry>
<para>
To draw free-form lines.
</para>
<para>
Click on the tool button, then click with the &LMB; and hold to place the start of the line, then drag to draw the line.
</para>
</entry>
</row>
<row>
<entry>
<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="tool-highlighter-okular.png" format="PNG"/>
</imageobject>
</inlinemediaobject>
</para>
</entry>
<entry>
<para>
Highlighter
</para>
</entry>
<entry>
<para>
To highlight text in the document with some given background color.
</para>
<para>
Click on the tool button, then click with the &LMB; and hold to place the beginning of the highlighted text snippet, then drag to highlight it.
</para>
</entry>
</row>
<row>
<entry>
<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="tool-line-okular.png" format="PNG"/>
</imageobject>
</inlinemediaobject>
</para>
</entry>
<entry>
<para>
Straight Line
</para>
</entry>
<entry>
<para>
To mark with a line.
</para>
<para>
Click on the tool button, then click with the &LMB; to place the starting point of the line, then drag to place of the ending point of the line should be and click once more.
</para>
</entry>
</row>
<row>
<entry>
<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="tool-polygon-okular.png" format="PNG"/>
</imageobject>
</inlinemediaobject>
</para>
</entry>
<entry>
<para>
Polygon
</para>
</entry>
<entry>
<para>
To draw a closed plane figure from three or more segments. The corresponding note can be viewed by double clicking inside the polygon.
</para>
<para>
Click on the tool button, then click with the &LMB; to place the first vertex of the polygon, then drag to place of the second vertex. Proceed until you draw the whole polygon up to the first vertex. Click twice if you want to add some note to the polygon. Enter the text of the note then click on the <guibutton>OK</guibutton> to save the note, <guibutton>Cancel</guibutton> to cancel note entering or <guibutton>Clear</guibutton> to clear the note.
</para>
</entry>
</row>
<row>
<entry>
<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="tool-stamp-okular.png" format="PNG"/>
</imageobject>
</inlinemediaobject>
</para>
</entry>
<entry>
<para>
Stamp
</para>
</entry>
<entry>
<para>
To mark the text or image with some predefined shape.
</para>
<para>
Click on the tool button then click with the &LMB; to place the stamp.
</para>
<para>
A single click just places a square stamp (useful for icons).
To add a rectangular stamp you can click with the &LMB; and hold to place the top-left point, then drag to place the bottom-right one.
</para>
</entry>
</row>
<row>
<entry>
<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="tool-underline-okular.png" format="PNG"/>
</imageobject>
</inlinemediaobject>
</para>
</entry>
<entry>
<para>
Underline
</para>
</entry>
<entry>
<para>
To underline some text.
</para>
<para>
Click on the tool button, then click with the &LMB; and hold to place the beginning of the underlined text snippet, then drag to underline it.
</para>
</entry>
</row>
<row>
<entry>
<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="tool-ellipse-okular.png" format="PNG"/>
</imageobject>
</inlinemediaobject>
</para>
</entry>
<entry>
<para>
Ellipse
</para>
</entry>
<entry>
<para>
To draw an ellipse around some chosen area.
</para>
<para>
Click on the tool button, then click with the &LMB; and hold to place the top-left corner of the circumscribed rectangular for the ellipse, then drag to place the bottom-right one.
</para>
</entry>
</row>
</tbody>
</tgroup>
</informaltable>
<para>
The contents of the annotating toolbar can be configured using the <link linkend="configannotations">Annotations page of &okular; configuration dialog</link>. This page can be opened with &RMB; clicking on the annotating toolbar then choosing <guimenuitem>Configure Annotations...</guimenuitem> from the context menu.
</para>
<para>
With a single &LMB; click on an annotation tool button you can use a tool once.
If you ⪚ want to highlight all important parts of a text, activate that tool
permanently by double clicking on the tool button.
Press the <keycap>Esc</keycap> key or click the tool button again to leave the permanent mode.
</para>
<note>
<para>
The annotating toolbar can be docked in any side of the viewing area: just drag it to
move it to another place.
</para>
</note>
<note>
<para>
Activating the annotating toolbar will make you switch to the Browse Tool Mode.
</para>
</note>
<para>
You can stop the construction any time by pressing again on the button of the
annotation you are constructing, or by pressing the &Esc; key.
</para>
<para>
The newly constructed annotation will have as author the author you set in the
<link linkend="configannotations"><guilabel>Annotations</guilabel> page</link> in &okular;s
configuration dialog. The <guilabel>Annotations</guilabel> page can also be used to configure the content of the annotating toolbar.
</para>
</sect2>
<sect2 id="annotations-remove">
<title>Removing annotations</title>
<para>
To remove an annotation, just click on it with the &RMB;, and select
<guimenuitem>Delete</guimenuitem>.
</para>
<para>
When removing the annotation, its window will be closed if open.
</para>
<note>
<para>
This option could not be enabled because the document does not allow removing
annotations.
</para>
</note>
</sect2>
<sect2 id="annotations-edit">
<title>Editing annotations</title>
<para>
To edit an annotation, click on it with the &RMB; and select
<guimenuitem>Properties</guimenuitem>. A dialog will appear with the general
annotation settings (like color and opacity, author, &etc;) and the settings specific
to that annotation type.
</para>
<screenshot>
<screeninfo>Annotation Property Dialog</screeninfo>
<mediaobject>
<imageobject>
<imagedata fileref="annotation-properties.png" format="PNG" />
</imageobject>
<textobject>
<phrase>Annotation Property Dialog</phrase>
</textobject>
</mediaobject>
</screenshot>
<para>
To move an annotation, hold down the &Ctrl; key, move the mouse pointer on it and
then start dragging with the &LMB;.
</para>
<note>
<para>
Depending on the document permissions (typically with &PDF; documents), some options
can be disabled.
</para>
</note>
</sect2>
</sect1>
<sect1 id="bookmark-management">
<title>Bookmark Management</title>
<para>
&okular; has a very flexible bookmark system. &okular; saves the position on the page in bookmark and allows you to define more than one bookmark per page.
</para>
<para>
To manage bookmarks in &okular; you can use <guilabel>Bookmarks</guilabel> view from <guilabel>Navigation Panel</guilabel>, <link linkend="menubookmarks">Bookmarks menu</link> or context menu of document view (click with &RMB; to open it).
</para>
<sect2 id="bookmarks-view">
<title>Bookmarks view</title>
<para>
To open <guilabel>Bookmarks</guilabel> view click on <guilabel>Bookmarks</guilabel> item on the <guilabel>Navigation Panel</guilabel>. If the <guilabel>Navigation Panel</guilabel> is not shown, use <menuchoice><shortcut><keycap>F7</keycap></shortcut> <guimenu>Settings</guimenu><guimenuitem>Show Navigation Panel</guimenuitem>
</menuchoice> main menu item to make it visible.
</para>
<screenshot>
<screeninfo>Bookmark view context menu</screeninfo>
<mediaobject>
<imageobject>
<imagedata fileref="bookmark-management.png" format="PNG" />
</imageobject>
<textobject>
<phrase>Bookmark view context menu</phrase>
</textobject>
</mediaobject>
</screenshot>
<para>
The filter bar at the top of <guilabel>Bookmarks</guilabel> view can be used to filter the content of bookmark list pane according to the text in the box.
</para>
<para>
The list pane permits to view the bookmark list in a tree-like fashion: each document in the list can be <quote>expanded</quote> or <quote>collapsed</quote> by clicking on the <guiicon><</guiicon> or <guiicon>v</guiicon> icon next to it.
</para>
<para>
Click on <inlinemediaobject><imageobject><imagedata fileref="rating.png" format="PNG"/></imageobject></inlinemediaobject> icon below the list to show only the bookmarks from the current document.
</para>
<para>
Right-click menu of document item can be used to open document, rename its item or remove it from the list. Remember that the removal of a document item leads to the removal of all bookmarks in the corresponding document.
</para>
<para>
Right-click menus of individual bookmark items allow you to go to the bookmark, rename or remove it.
</para>
</sect2>
</sect1>
<!-- Please keep this section content in sync with man page (man-okular.1.docbook) -->
<sect1 id="command-line-options">
<title>Command Line Options</title>
<para>
Though &okular; may most often be started from the &kde; program menu, or a desktop icon, it can also be opened at the command line prompt of a terminal window. There are a few useful options that are available when doing this.
</para>
<sect2 id="specify-a-file">
<title>Specify a File</title>
<para>
By specifying the path and name of a particular file the user can have &okular; open that file immediately upon startup. This option might look something like the following:
</para>
<informalexample><screen><prompt>%</prompt> <userinput><command>okular</command> <option><replaceable>/home/myhome/docs/mydoc.pdf</replaceable></option> </userinput> </screen>
</informalexample>
<note>
<para>
For &PDF; documents, the name can be given as <replaceable>document_name</replaceable>#<replaceable>named_destination</replaceable> where <replaceable>named_destination</replaceable> is a particular named destination embedded in the document.
</para>
</note>
</sect2>
<sect2 id="other-command-line-options">
<title>Other Command Line Options</title>
<para>
The following command line help options are available
</para>
<variablelist>
<varlistentry>
<term><userinput><command>okular</command>
<option>--help</option></userinput></term>
<listitem><para>This lists the most basic options available at the command line.</para></listitem>
</varlistentry>
<varlistentry>
<term><userinput><command>okular</command>
<option>--help-qt</option></userinput></term>
<listitem><para>This lists the options available for changing the way &okular; interacts with &Qt;.</para></listitem>
</varlistentry>
<varlistentry>
<term><userinput><command>okular</command>
<option>--help-kde</option></userinput></term>
<listitem><para>This lists the options available for changing the way &okular; interacts with &kde;.</para></listitem>
</varlistentry>
<varlistentry>
<term><userinput><command>okular</command>
<option>--help-all</option></userinput></term>
<listitem><para>This lists all of the command line options.</para></listitem>
</varlistentry>
<varlistentry>
<term><userinput><command>okular</command>
<option>--author</option></userinput></term>
<listitem><para>Lists &okular;'s authors in the terminal window</para></listitem>
</varlistentry>
<varlistentry>
<term><userinput><command>okular</command>
<option>-v, --version</option></userinput></term>
<listitem><para>Lists version information for &Qt;, &kde;, and &okular;. Also available through <userinput><command>okular</command> <option>-v</option></userinput> </para></listitem>
</varlistentry>
<varlistentry>
<term><userinput><command>okular</command>
<option>--license</option></userinput></term>
<listitem><para>Shows license information.</para></listitem>
</varlistentry>
<varlistentry>
<term><userinput><command>okular</command>
<option>--page <replaceable>number</replaceable></option></userinput></term>
<listitem><para>Open a page with a given number in the document. Also available through <userinput><command>okular</command> <option>-p <replaceable>number</replaceable></option></userinput></para></listitem>
</varlistentry>
<varlistentry>
<term><userinput><command>okular</command>
<option>--presentation</option></userinput></term>
<listitem><para>Start the document in presentation mode.</para></listitem>
</varlistentry>
<varlistentry>
<term><userinput><command>okular</command>
<option>--print</option></userinput></term>
<listitem><para>Start with print dialog.</para></listitem>
</varlistentry>
<varlistentry>
<term><userinput><command>okular</command>
<option>--unique</option></userinput></term>
<listitem><para>Unique instance control.</para></listitem>
</varlistentry>
<varlistentry>
<term><userinput><command>okular</command>
<option>--noraise</option></userinput></term>
<listitem><para>Allows to prevent &okular; window raising after the start.</para></listitem>
</varlistentry>
<varlistentry>
<term><userinput><command>okular</command>
<option>--</option></userinput></term>
<listitem><para>End of options.</para></listitem>
</varlistentry>
</variablelist>
</sect2>
</sect1>
<sect1 id="fit-window-to-page">
<title>Fit window to page</title>
<para>
The Fit window to page feature resizes the window so that it is exactly the same size as the page at the current zoom factor.
If the page doesn't completely fit on the screen, the window is enlarged so that the largest possible part of the page is shown.
</para>
<para>
This feature can be accessed by using the keyboard shortcut <keycombo action="simul">&Ctrl;<keycap>J</keycap></keycombo>
</para>
</sect1>
</chapter>
<chapter id="primary-menu-items">
<title>The Menubar</title>
<sect1 id="menufile">
<title>The File Menu</title>
<variablelist>
<varlistentry>
<term>
<menuchoice>
<shortcut>
<keycombo action="simul">&Ctrl;<keycap>O</keycap></keycombo>
</shortcut>
<guimenu>File</guimenu>
<guimenuitem>Open...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>
<action>Open</action> a supported file or &okular; archive. If there is already an opened file it will be closed. For more information, see the section about <link linkend="opening">Opening Files</link>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>File</guimenu>
<guisubmenu>Open Recent</guisubmenu>
</menuchoice>
</term>
<listitem>
<para>
<action>Open</action> a file which was used previously from a
submenu. If a file is currently being displayed it
will be closed. For more information, see the section about
<link linkend="opening">Opening Files</link>.
</para>
</listitem>
</varlistentry>
<!--
<varlistentry>
<term>
<menuchoice>
<shortcut><keycap>G</keycap></shortcut>
<guimenu>File</guimenu>
<guimenuitem>Get Books From Internet...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>to be written</para>
</listitem>
</varlistentry>
<-->
<varlistentry>
<term>
<menuchoice>
<guimenu>File</guimenu>
<guimenuitem>Import PostScript as &PDF;...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>
<action>Open</action> a &PostScript; file and convert it to &PDF;.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>File</guimenu>
<guimenuitem>Save As...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Save</action> the currently open file under a different name using the document backend. With the &PDF; backend (Poppler >= 0.8 required) it is possible to save the document with the changed values of the form fields.<!--Only useful for pdf? what happens with other formats/backends?--> It can be possible (provided that the data were not secured using DRM) to save annotations with &PDF; files (Poppler >= 0.22 required).</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>File</guimenu>
<guimenuitem>Save Copy As...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Save</action> a copy of the currently open file under a different name
without using the current document backend.</para>
<!-- does not save the annotations, they are still coupled to the original file-->
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycap>F5</keycap></shortcut>
<guimenu>File</guimenu>
<guimenuitem>Reload</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Reload</action> the currently open file.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>P</keycap></keycombo></shortcut>
<guimenu>File</guimenu>
<guimenuitem>Print...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>
<action>Print</action> the currently displayed document.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>File</guimenu>
<guimenuitem>Print Preview...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>
<action>Show a preview</action> of how the currently displayed
document would be printed with the default options.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>File</guimenu>
<guimenuitem>Properties</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Display some basic information</action> about the document, such as
title, author, creation date, and details about the fonts used. The available information
depends on the type of document.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>File</guimenu>
<guimenuitem>Embedded Files...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Show the files embedded</action> in the document, if the document has any.
For more information, see the section about the
<link linkend="embedded-files">Embedded Files</link>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>File</guimenu>
<guisubmenu>Export As</guisubmenu>
</menuchoice>
</term>
<listitem>
<para>This item contains the export formats the current document can be exported to.
The first entry for all kind of documents is always <guimenuitem>Plain Text...</guimenuitem></para>
<para>The second entry is <guimenuitem>Document Archive</guimenuitem>, which allows you to save the document with your annotations into an &okular;-specific archive format. Thus it is easily possible to share the original document and your annotations with other &okular; users or work with them collaboratively.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>Q</keycap></keycombo></shortcut>
<guimenu>File</guimenu>
<guimenuitem>Quit</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Close</action> &okular;.</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1 id="menuedit">
<title>The Edit Menu</title>
<variablelist>
<varlistentry>
<term>
<anchor id="edit-undo"/>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>Z</keycap></keycombo></shortcut>
<guimenu>Edit</guimenu>
<guimenuitem>Undo</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Undo</action> the last annotation editing command (creation and removal of annotations, editing arbitrary annotation properties, relocating annotations with &Ctrl;+drag, and editing the text contents of an annotation).</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<anchor id="edit-redo"/>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;&Shift;<keycap>Z</keycap></keycombo></shortcut>
<guimenu>Edit</guimenu>
<guimenuitem>Redo</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Redo</action> the last undo step when editing annotations.</para>
</listitem>
</varlistentry>
</variablelist>
<variablelist>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>C</keycap></keycombo></shortcut>
<guimenu>Edit</guimenu>
<guimenuitem>Copy</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Copy</action> the currently selected text in
<guibutton>Text Selection</guibutton> mode to the clipboard.</para>
</listitem>
</varlistentry>
</variablelist>
<variablelist>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>A</keycap></keycombo></shortcut>
<guimenu>Edit</guimenu>
<guimenuitem>Select All</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Selects</action> all the text (if the document provides it). This works only in
<guibutton>Text Selection</guibutton> mode.</para>
</listitem>
</varlistentry>
</variablelist>
<variablelist>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>F</keycap></keycombo></shortcut>
<guimenu>Edit</guimenu>
<guimenuitem>Find...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>
Show the find bar on the bottom of the viewing area that allows you to
<action>search for a string in the document</action>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycap>F3</keycap></shortcut>
<guimenu>Edit</guimenu>
<guimenuitem>Find Next</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>Try to <action>find the previous searched string again</action> in the document.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Shift;<keycap>F3</keycap></keycombo></shortcut>
<guimenu>Edit</guimenu>
<guimenuitem>Find Previous</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Goes to the previous occurrence of the search string</action> in the document.</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1 id="menuview">
<title>The View Menu</title>
<variablelist>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;&Shift;<keycap>P</keycap></keycombo></shortcut>
<guimenu>View</guimenu>
<guimenuitem>Presentation</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Activates</action> the Presentation Mode. For more information, see the
section about <link linkend="presentationMode">Presentation Mode</link>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>+</keycap></keycombo></shortcut>
<guimenu>View</guimenu>
<guimenuitem>Zoom In</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Increase the magnification</action> of the document view.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>-</keycap></keycombo></shortcut>
<guimenu>View</guimenu>
<guimenuitem>Zoom Out</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Decrease the magnification</action> of the document view.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>View</guimenu>
<guimenuitem>Fit Width</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Change the magnification</action> of the document
view to a value that makes the pages' width equal to the document
view's width.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>View</guimenu>
<guimenuitem>Fit Page</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Change the magnification</action> of the document view
to a value that makes at least one whole page visible.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>View</guimenu>
<guimenuitem>Auto Fit</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Change the magnification</action> of the document view
to a value that, depending on the size relation between the page and the view area, automatically either makes the pages' width equal to the document view's width (like fit-width), the pages' height equal to the document view's height (like fit-height), or the whole page visible (like fit-page).</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>View</guimenu>
<guimenuitem>Continuous</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Enable the continuous page mode</action>. In continuous mode,
all pages of the document are shown, and you can scroll through
them without having to use the <menuchoice><guimenu>Go</guimenu>
<guimenuitem>Previous Page</guimenuitem></menuchoice> and
<menuchoice><guimenu>Go</guimenu><guimenuitem>Next Page</guimenuitem>
</menuchoice> options.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>View</guimenu>
<guisubmenu>View Mode</guisubmenu>
</menuchoice>
</term>
<listitem>
<para>This submenu makes you choose the view mode for the pages. The possible
options are: <guimenuitem>Single Page</guimenuitem> (only one page per row),
<guimenuitem>Facing Pages</guimenuitem> (two pages per row, in a book style),
<guimenuitem>Facing Pages (Center First Page)</guimenuitem> and
<guimenuitem>Overview</guimenuitem> (the number of columns is the one
specified in the <link linkend="configure">&okular; settings</link>).</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>View</guimenu>
<guisubmenu>Orientation</guisubmenu>
</menuchoice>
</term>
<listitem>
<para>
This submenu allows you to <action>changes the orientation</action>
of the pages of the document.
</para>
<note>
<para>
The rotation is applied to the orientation of every page.
</para>
</note>
<para>
You can select <guimenuitem>Original Orientation</guimenuitem> to restore
the orientation of the document, discarding all the rotations applied
manually.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>View</guimenu>
<guisubmenu>Page Size</guisubmenu>
</menuchoice>
</term>
<listitem>
<para>
<action>Changes the size of the pages</action> of the document.
</para>
<note>
<para>
This submenu is active only if the current type of document
supports different page sizes.
</para>
</note>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>View</guimenu>
<guimenuitem>Trim Margins</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>
Remove the white border of pages when viewing pages.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>View</guimenu>
<guimenuitem>Show/Hide Forms</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>
<action>Show or hides the display</action> of the form fields of the
document.
</para>
<note>
<para>
This menu item is active only if the current document has form
fields.
</para>
</note>
</listitem>
</varlistentry>
</variablelist>
<!-- Crtl + mouse wheel zoom in + out-->
</sect1>
<sect1 id="menugo">
<title>The Go Menu</title>
<variablelist>
<varlistentry>
<term>
<menuchoice>
<guimenu>Go</guimenu>
<guimenuitem>Previous Page</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>View the previous page</action> of the document.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>Go</guimenu>
<guimenuitem>Next Page</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>View the next page</action> of the document.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>Home</keycap></keycombo></shortcut>
<guimenu>Go</guimenu>
<guimenuitem>Beginning of the document</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Go to the beginning</action> of the document.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>End</keycap></keycombo></shortcut>
<guimenu>Go</guimenu>
<guimenuitem>End of the document</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Go to the end</action> of the document.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Alt;&Shift;<keysym>Left</keysym></keycombo></shortcut>
<guimenu>Go</guimenu>
<guimenuitem>Back</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Go back to the previous view</action> of the document.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Alt;&Shift;<keysym >Right</keysym></keycombo></shortcut>
<guimenu>Go</guimenu>
<guimenuitem>Forward</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Move forward to the next view</action> of the document. This only works if you have already moved back before.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>G</keycap></keycombo></shortcut>
<guimenu>Go</guimenu>
<guimenuitem>Go to Page...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>Open a dialog which allows you to <action>go to any page</action> of the document.</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1 id="menubookmarks">
<title>The Bookmarks Menu</title>
<variablelist>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>B</keycap></keycombo></shortcut>
<guimenu>Bookmarks</guimenu>
<guimenuitem>Add/Remove Bookmark</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>
<action>Add or remove a bookmark for the current position</action>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>Bookmarks</guimenu>
<guimenuitem>Rename Bookmark</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>
<action>Rename a bookmark for the current position</action>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>Bookmarks</guimenu>
<guimenuitem>Previous Bookmark</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Go to the previous bookmark</action>, or do nothing if there
are no bookmarks prior to the current one.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>Bookmarks</guimenu>
<guimenuitem>Next Bookmark</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Go to the next bookmark</action>, or do nothing if there
are no bookmarks after the current one.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>Bookmarks</guimenu>
<guimenuitem>No Bookmarks</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>This is an always disabled action that appears in this menu only if the current document has
no bookmarks. Otherwise a list of all bookmarks is displayed here. Clicking on these bookmarks
allows you to go directly to the associated position.</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1 id="menutools">
<title>The Tools Menu</title>
<variablelist>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>1</keycap></keycombo></shortcut>
<guimenu>Tools</guimenu>
<guimenuitem>Browse Tool</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>The mouse will have its normal behavior, &LMB; for dragging the document and following links and &RMB; for adding bookmarks and fit to width.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>2</keycap></keycombo></shortcut>
<guimenu>Tools</guimenu>
<guimenuitem>Zoom Tool</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>The mouse will work as a zoom tool. Clicking &LMB; and dragging will zoom the view to the selected area, clicking &RMB; will bring the document back to the previous zoom.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>3</keycap></keycombo></shortcut>
<guimenu>Tools</guimenu>
<guimenuitem>Selection Tool</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>The mouse will work as a select tool. In that mode clicking &LMB; and dragging will give the option of copying the text/image of current selected area to the clipboard, speak a text or to save an image to a file.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>4</keycap></keycombo></shortcut>
<guimenu>Tools</guimenu>
<guimenuitem>Text Selection Tool</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>The mouse will work as a text selection tool. In that mode clicking &LMB; and
dragging will give the option of selecting the text of the document. Then, just
click with the &RMB; to copy to the clipboard or speak the current selection.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>5</keycap></keycombo></shortcut>
<guimenu>Tools</guimenu>
<guimenuitem>Table Selection Tool</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>Draw a rectangle around the text for the table, then use the click with the &LMB;
to divide the text block into rows and columns. A &LMB; click on a existing line removes it and merges the adjacent rows or columns.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>6</keycap></keycombo></shortcut>
<guimenu>Tools</guimenu>
<guimenuitem>Magnifier</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>Activates the magnifier mode for the mouse pointer. Press and hold the &LMB; to activate magnifier widget, move the pointer for panning through the document. The magnifier scales each pixel in the document into 10 pixels in the magnifier widget.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycap>F6</keycap></shortcut>
<guimenu>Tools</guimenu>
<guimenuitem>Review</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Open the review toolbar</action>. The review toolbar allows you to add
annotations on the document you are reading. For more information, please see the
section about <link linkend="annotations">Annotations</link>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>Tools</guimenu>
<guimenuitem>Speak Whole Document</guimenuitem>
</menuchoice>
</term>
<term>
<menuchoice>
<guimenu>Tools</guimenu>
<guimenuitem>Speak Current Page</guimenuitem>
</menuchoice>
</term>
<term>
<menuchoice>
<guimenu>Tools</guimenu>
<guimenuitem>Stop Speaking</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>These items allow you to speak the whole document or just the current page and stop speaking using the &kde; Text-to-Speech system &jovie;.</para>
<para>The <guilabel>Speak ...</guilabel> actions are enabled only if &jovie; is available in the system.</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1 id="settings-menu">
<title>The Settings Menu</title>
<variablelist>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;<keycap>M</keycap></keycombo></shortcut>
<guimenu>Settings</guimenu>
<guimenuitem>Show Menubar</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Toggle the Menubar display</action> on and off. Once
hidden it can be made visible using the shortcut
<keycombo action="simul">&Ctrl;<keycap>M</keycap></keycombo> again.
If the menubar is hidden, the context menu opened with a right mouse button
click anywhere in the view area has an extra entry <guimenuitem>Show Menubar</guimenuitem>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>Settings</guimenu>
<guimenuitem>Show Toolbar</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Toggle the Toolbar display</action> on and off.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycap>F7</keycap></shortcut>
<guimenu>Settings</guimenu>
<guimenuitem>Show Navigation Panel</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Toggle the navigation panel</action> on and off.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>Settings</guimenu>
<guimenuitem>Show Page Bar</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Toggle the page bar</action> at the bottom of document area on and off to save vertical place in &okular; window.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<shortcut><keycombo action="simul">&Ctrl;&Shift;<keycap>F</keycap></keycombo></shortcut>
<guimenu>Settings</guimenu>
<guimenuitem>Full Screen Mode</guimenuitem>
</menuchoice>
</term>
<listitem>
<para><action>Enables the full screen mode</action>. Note that
full screen mode is different from <link
linkend="presentationMode">presentation mode</link> insofar as the
only peculiarity of full screen mode is that it hides the window
decorations, the menubar and the toolbar.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>Settings</guimenu>
<guimenuitem>Configure Shortcuts...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>Opens a window that lets you <action>configure the keyboard
shortcuts</action> for many menu commands.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>Settings</guimenu>
<guimenuitem>Configure Toolbars...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>Opens a window that lets you choose which icons are visible
in the toolbar.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>Settings</guimenu>
<guimenuitem>Configure Backends...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>Opens the <link linkend="configure-backends">Backend Configuration</link>
window.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<menuchoice>
<guimenu>Settings</guimenu>
<guimenuitem>Configure &okular;...</guimenuitem>
</menuchoice>
</term>
<listitem>
<para>Opens the <link linkend="configure">Configure</link>
window.</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1 id="menuhelp">
<title>The Help Menu</title>
&help.menu.documentation;
</sect1>
</chapter>
<chapter id="configure-backends">
<title>Configuring &okular; Backends</title>
<para>
You can configure &okular; backends by choosing <menuchoice>
<guimenu>Settings</guimenu>
<guimenuitem>Configure Backends...</guimenuitem>
</menuchoice>.
Currently, configuration options are provided for EPub, &PostScript;, FictionBook, Txt, OpenDocument Text, and &PDF; backends only.
</para>
<screenshot>
<screeninfo>The backends configuration dialog</screeninfo>
<mediaobject>
<imageobject>
<imagedata fileref="configure-backends.png" format="PNG" />
</imageobject>
<textobject>
<phrase>The backends configuration dialog</phrase>
</textobject>
</mediaobject>
</screenshot>
<para>
Using backend configuration pages for EPub, FictionBook, Txt and OpenDocument Text you can define the font to render documents in the corresponding formats. The <guibutton>Choose...</guibutton> button in these pages opens standard &kde; font configuration window. Please refer to the <ulink url="help:/fundamentals/fonts.html">&kde; Fundamentals documentation</ulink> for the details.
</para>
<para>
The description of &PostScript; and &PDF; backends configuration pages can be found below.
</para>
<sect1 id="config-ghostscript">
<title>&PostScript; backend configuration</title>
<para>
You can configure &okular; &PostScript; rendering backend based on <ulink url="http://www.ghostscript.com/">Ghostscript</ulink> by choosing <guilabel>Ghostscript</guilabel> from the list on the left part of the configuration dialog. The only configurable option is as follows.
</para>
<para>
<variablelist>
<varlistentry>
<term>
<guilabel>Use platform fonts</guilabel>
</term>
<listitem>
<para>This option determines whether Ghostscript should be allowed to use platform fonts, if unchecked only usage of fonts embedded in the document will be allowed. This option is checked by default.
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</sect1>
<sect1 id="config-pdf">
<title>&PDF; backend configuration</title>
<para>
You can configure &okular; &PDF; rendering backend based on <ulink url="http://poppler.freedesktop.org/">Poppler</ulink> by choosing <guilabel>&PDF;</guilabel> from the list on the left part of the configuration dialog. The only configurable option is as follows.
</para>
<para>
<variablelist>
<varlistentry>
<term>
<guilabel>Enhance thin lines</guilabel>
</term>
<listitem>
<para>
Drawing lines in &okular; is implemented in two steps: generation of the clipping path and filling this clipping path. When the line in the original document is less than one pixel this two step implementation could cause problems. For those lines, the clipping path is filled with the filling color that depends on the thickness of the line part inside the clipping area. If the part of the line inside the clipping area gets very small the contrast between the shape and the background color can become too low for the line to be recognizable. The grids of such lines then looks very unpretty.
</para>
<informaltable>
<tgroup cols="2">
<tbody>
<row>
<entry>
<para>
<screenshot>
<mediaobject>
<imageobject>
<imagedata fileref="enhance-thinline.png" format="PNG"/>
</imageobject>
</mediaobject>
</screenshot>
</para>
</entry>
<entry>
<para>
<screenshot>
<mediaobject>
<imageobject>
<imagedata fileref="enhance-lowcontrast.png" format="PNG"/>
</imageobject>
</mediaobject>
</screenshot>
</para>
</entry>
</row>
<row>
<entry>Thin line (red), its clipping path (dashed line) and pixel boundaries (black solid lines)</entry>
<entry>Thin line shown at a low contrast</entry>
</row>
</tbody>
</tgroup>
</informaltable>
<para>
To enhance the look of the thin lines &okular; implements two options.
</para>
<para>
The first option is <guimenuitem>Solid</guimenuitem>. With this option &okular; adjusts clipping path and line position so that clipping path and line are on the same pixel boundary, &ie; &okular; enlarges the thin lines to one pixel on the output device. This mode is similar to the <guilabel>Enhance thin lines</guilabel> in <trademark class="registered">Adobe</trademark>
<trademark class="registered">Reader</trademark>. If this option is chosen, the thin lines are always enlarged.
</para>
<para>
<screenshot>
<mediaobject>
<imageobject>
<imagedata fileref="enhance-solid.png" format="PNG"/>
</imageobject>
<textobject>
<phrase>Thin line with <guimenuitem>Solid</guimenuitem> enhancement</phrase>
</textobject>
<caption>
<para>Thin line with <guimenuitem>Solid</guimenuitem> enhancement</para>
</caption>
</mediaobject>
</screenshot>
</para>
<para>
The second option is <guimenuitem>Shape</guimenuitem>. With this option the clipping path and line are adjusted to pixel boundary as well, but the line intensity is corrected according to its width.
</para>
<para>
<screenshot>
<mediaobject>
<imageobject>
<imagedata fileref="enhance-shape.png" format="PNG"/>
</imageobject>
<textobject>
<phrase>Thin line with <guimenuitem>Shape</guimenuitem> enhancement</phrase>
</textobject>
<caption>
<para>Thin line with <guimenuitem>Shape</guimenuitem> enhancement</para>
</caption>
</mediaobject>
</screenshot>
</para>
<para>
The thin lines are not enhanced by default (option <guimenuitem>No</guimenuitem>).
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</sect1>
</chapter>
<chapter id="configure">
<title>Configuring &okular;</title>
<sect1 id="configindex">
<title>General configuration</title>
<para>
You can configure &okular; by choosing <menuchoice><guimenu>Settings</guimenu>
<guimenuitem>Configure &okular;...</guimenuitem></menuchoice>.
The configuration dialog is split into six sections. This chapter describes the available
options in detail.
</para>
<itemizedlist>
<listitem>
<para><link linkend="configgeneral">General</link></para>
</listitem>
<listitem>
<para><link linkend="configaccessibility">Accessibility</link></para>
</listitem>
<listitem>
<para><link linkend="configperformance">Performance</link></para>
</listitem>
<listitem>
<para><link linkend="configpresentation">Presentation</link></para>
</listitem>
<listitem>
<para><link linkend="configannotations">Annotations</link></para>
</listitem>
<listitem>
<para><link linkend="configeditor">Editor</link></para>
</listitem>
</itemizedlist>
<screenshot>
<screeninfo>The configuration dialog</screeninfo>
<mediaobject>
<imageobject>
<imagedata fileref="configure.png" format="PNG" />
</imageobject>
<textobject>
<phrase>The configuration dialog</phrase>
</textobject>
</mediaobject>
</screenshot>
<para>
Depending on the currently installed backends, the <menuchoice><guimenu>Settings</guimenu>
<guimenuitem>Configure Backends...</guimenuitem></menuchoice> menu item could be enabled.
This particular configuration dialog holds the configurations of the backends that can
actually be configured.
</para>
</sect1>
<sect1 id="configgeneral">
<title>General</title>
<variablelist>
<varlistentry>
<term><guilabel>Show scrollbars</guilabel></term>
<listitem>
<para>Whether to show scrollbars for the document view.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Link the thumbnails with the page</guilabel></term>
<listitem>
<para>Whether the thumbnails view should always display the current
page or not.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Show hints and info messages</guilabel></term>
<listitem>
<para>Whether to show some informative messages on startup, file
load, &etc;</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Display document title in titlebar if available</guilabel></term>
<listitem>
<para>Whether to show the current document title in the titlebar of &okular; window. If no metadata for title
found in the document or this item is unchecked &okular; shows filename of the document.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>When not displaying document title</guilabel></term>
<listitem>
<para>You can choose any of two options, <guilabel>Display file name only</guilabel> or <guilabel>Display full file path</guilabel>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Obey DRM limitations</guilabel></term>
<listitem>
<para>Whether &okular; should obey <firstterm>DRM</firstterm>
(Digital Rights Management) restrictions. DRM limitations are used
to make it impossible to perform certain actions with &PDF; documents,
such as copying content to the clipboard. Note that in some configurations
of &okular;, this option is not available.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Open new files in tabs</guilabel></term>
<listitem>
<para>Whether to open new documents in tabs. The tabs are disabled by default.</para>
<para>
The default shortcuts to switch between tabs are <keycombo>&Ctrl;<keycap>.</keycap></keycombo> (<guilabel>Next tab</guilabel>) and <keycombo>&Ctrl;<keycap>,</keycap></keycombo> (<guilabel>Previous tab</guilabel>).
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Reload document on file change</guilabel></term>
<listitem>
<para>Whether opened files should be automatically checked for
changes and updated, if necessary.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Show backend selection dialog</guilabel></term>
<listitem>
<para>Whether &okular; should ask the user which backend to use in case of more
than one backend able to open the current file. If unchecked, &okular; will
use the backend with the highest priority.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Overview columns</guilabel></term>
<listitem>
<para>
This option represents the number of columns to use in the overview mode.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Page Up/Down overlap</guilabel></term>
<listitem>
<para>
Here you can define the percentage of the current viewing area that should be visible after pressing <keycap>Page Up</keycap>/<keycap>Page Down</keycap> keys.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Default Zoom</guilabel></term>
<listitem>
<para>
This options specifies the default zoom mode for file which were never
opened before. For those files which were opened before the previous zoom mode
is applied.
</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1 id="configaccessibility">
<title>Accessibility</title>
<variablelist>
<varlistentry>
<term><guilabel>Draw border around links</guilabel></term>
<listitem>
<para>Whether to draw a border around links.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Change colors</guilabel></term>
<listitem>
<para><action>Enables</action> the color changing options.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Invert Colors</guilabel></term>
<listitem>
<para><action>Inverts</action> colors on the view, &ie; black objects will be shown white.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Change Paper Color</guilabel></term>
<listitem>
<para><action>Changes</action> the paper's color, &ie; the document's background.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Change Dark & Light Colors</guilabel></term>
<listitem>
<para><action>Changes</action> the dark and light color to your preference, that means
black will not be rendered as black but as the selected dark color and white
will not be rendered as white but as the selected light color.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Convert to Black & White</guilabel></term>
<listitem>
<para><action>Converts</action> the document to black and white. You can set the
threshold and the contrast. Setting the threshold to a higher value
by moving it to the right will result in lighter grays used.</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1 id="configperformance">
<title>Performance</title>
<variablelist>
<varlistentry>
<term><guilabel>Enable transparency effects</guilabel></term>
<listitem>
<para>Draw selections and other special graphics using
transparency effects. Disable the option to draw them using
outline or opaque fill styles and increase speed on selections.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Memory Usage</guilabel></term>
<listitem>
<para>&okular; can achieve best performance by tuning the memory usage, based on your system and your tastes.
The more memory you let it to use, the faster the program will behave. The Default profile is good
for every system, but you can prevent &okular; from using more memory than necessary by selecting the Low
profile, or let it get the most out of your system using Aggressive. Use Greedy profile to preload all
pages without risk of system memory overfull (only 50% of total memory or free memory will be used).</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Rendering</guilabel></term>
<listitem>
<para>Using this group of options you can improve text and image rendering in &okular;. The result depends on the device to display the document.
<guilabel>Enable Text Antialias</guilabel> and <guilabel>Enable Graphics Antialias</guilabel> items can be used to switch on and off <ulink url="http://en.wikipedia.org/wiki/Spatial_anti-aliasing">spatial anti-aliasing</ulink> of text and images in document, correspondingly.
<guilabel>Enable Text Hinting</guilabel> item is meant to be a switcher for <ulink url="http://en.wikipedia.org/wiki/Font_hinting">font hinting</ulink>.
Antialiasing and hinting change how the documents are displayed, you may want to tweak them to your preference.</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1 id="configpresentation">
<title>Presentation</title>
<variablelist>
<varlistentry>
<term><guilabel>Advance every</guilabel></term>
<listitem>
<para>Enables automatic advancing of pages given a time period.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Loop after last page</guilabel></term>
<listitem>
<para>When navigating on presentation mode and going past the last page the first page will appear.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Background color</guilabel></term>
<listitem>
<para>The color that will fill the part of the screen not covered by the page when on presentation mode.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Pencil color</guilabel></term>
<listitem>
<para>The color of the pencil used when drawing on the pages during the presentation mode.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Mouse cursor</guilabel></term>
<listitem>
<para>Whether the mouse should be always hidden, always shown or hidden after a small time of inactivity.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Show progress indicator</guilabel></term>
<listitem>
<para>Whether to show a progress circle that shows the current page and the total number of pages on the upper
right corner of the presentation screen every time you change the page.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Show summary page</guilabel></term>
<listitem>
<para>Whether to show a summary page at the beginning of the presentation with the title, author and number of pages of the document.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Enable transitions</guilabel></term>
<listitem>
<para>Use this check box to enable or disable transition effects between pages.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Default transition</guilabel></term>
<listitem>
<para>The transition effect between page and page if the document does not specify one. Set this to <guilabel>Random
Transition</guilabel> to make &okular; randomly choose one of the available effects.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Placement</guilabel></term>
<listitem>
<para>In this section you can select the <guilabel>Screen</guilabel> used to display the presentation.</para>
<para><guilabel>Current Screen</guilabel> is same screen of the &okular; window that starts the presentation mode.</para>
<para><guilabel>Default Screen</guilabel> is the screen marked as default in the xinerama configuration.</para>
<para><guilabel>Screen 0</guilabel>, <guilabel>Screen 1</guilabel> &etc; are the available screens.</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1 id="configannotations">
<title>Annotations</title>
<screenshot>
<screeninfo>The Annotations page of the configuration dialog</screeninfo>
<mediaobject>
<imageobject>
<imagedata fileref="configure-annotations.png" format="PNG" />
</imageobject>
<textobject>
<phrase>The Annotations page of the configuration dialog</phrase>
</textobject>
</mediaobject>
</screenshot>
<variablelist>
<varlistentry>
<term><guilabel>Author</guilabel></term>
<listitem>
<para>The author of the contents added on a document.
Default is the name from the <guilabel>Password & User Account</guilabel> page of the &systemsettings; module <guilabel>Account Details</guilabel>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Annotation tools</guilabel></term>
<listitem>
<para>
This pane is used to configure your <link linkend="annotations-add">annotating toolbar</link>.
</para>
<para>
There are five buttons (<guibutton>Add</guibutton>, <guibutton>Edit</guibutton>, <guibutton>Remove</guibutton>, <guibutton>Move Up</guibutton>, <guibutton>Move Down</guibutton>) and a list box (which lists the contents of the current annotating toolbar) which are used to configure the toolbar.
</para>
<para>
If you need to add some tool button on the toolbar click on the <guibutton>Add</guibutton> button. You can choose the <guilabel>Name</guilabel>, the <guilabel>Type</guilabel> and the <guilabel>Appearance</guilabel> of the created tool.
</para>
<note>
<para>
Please remember that annotation tools in &okular; are highly configurable. For example, you can have two buttons of the same tool but with different color. Do not hesitate to experiment in choosing the button set that is exactly tailored to your workflow.
</para>
</note>
<para>
Click on some item in the list box then click on the corresponding button at the right part of the page to edit, remove, move up or move down the item. The keyboard shortcut of the tool (keys from <keycap>1</keycap> to <keycap>9</keycap>) depends on its position in the list of annotating toolbar.
</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1 id="configeditor">
<title>Editor</title>
<variablelist>
<varlistentry>
<term><guilabel>Editor</guilabel></term>
<listitem>
<para>Choose the editor you want to launch when &okular; wants to open a source file.
This is the case when the document has references to the various points (usually row and column number) of sources it was generated from. The &DVI; format supports natively the addition of the information about the sources the LaTeX document was generated from. A similar system exists for &PDF; documents, called <acronym>pdfsync</acronym>, which stores these extra information in an external file named after the &PDF; file itself (for example <filename>mydocument.pdfsync</filename> for <filename>mydocument.pdf</filename>).
</para>
<para>
&okular; ships with preconfigured settings for the following editors: <ulink url="http://kate-editor.org/">&kate;</ulink>, <ulink url="http://kile.sourceforge.net/">Kile</ulink>, <ulink url="http://www.scintilla.org/SciTE.html">SciTE</ulink>, <ulink url="http://www.gnu.org/software/emacs/">&Emacs; client</ulink>, and <ulink url="http://www.lyx.org/">LyX client</ulink>.
</para>
<note>
<para>
To use inverse search in <application>Kile</application>, you have to compile your &latex; file with the <guilabel>Modern</guilabel> configuration.
</para>
</note>
</listitem>
</varlistentry>
<varlistentry>
<term><guilabel>Command</guilabel></term>
<listitem>
<para>This is the command and its parameters to invoke the selected editor with the source file of the actual document.</para>
<para>This field will be filled automatically if you use one of the preconfigured editors. Otherwise, please choose <guimenuitem>Custom Text Editor</guimenuitem> in <guilabel>Editor</guilabel> drop down box and refer to the documentation on your favorite editor to find the proper command.
</para>
<para>You can use the following placeholders:</para>
<itemizedlist>
<listitem>
<para>%f - the file name</para>
</listitem>
<listitem>
<para>%l - the line of the file to be reached</para>
</listitem>
<listitem>
<para>%c - the column of the file to be reached</para>
</listitem>
</itemizedlist>
<para>If %f is not specified, then the document name is appended to the specified command.</para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
</chapter>
<chapter id="credits">
<title>Credits and License</title>
<itemizedlist>
<title>Program Copyright:</title>
<listitem><para>&Albert.Astals.Cid; &Albert.Astals.Cid.mail; Current maintainer</para></listitem>
<listitem><para>Pino Toscano <email>pino@kde.org</email></para></listitem>
<listitem><para>Enrico Ros <email>eros.kde@email.it</email> &kpdf; developer</para></listitem>
</itemizedlist>
<itemizedlist>
<title>Documentation Copyright:</title>
<listitem><para>&Albert.Astals.Cid; &Albert.Astals.Cid.mail; Author</para></listitem>
<listitem><para>Titus Laska <email>titus.laska@gmx.de</email> Some updates and additions</para></listitem>
<listitem><para>Pino Toscano <email>pino@kde.org</email></para></listitem>
</itemizedlist>
<!-- TRANS:CREDIT_FOR_TRANSLATORS -->
&underFDL;
&underGPL;
</chapter>
<appendix id="installation">
<title>Installation</title>
<sect1 id="getting-kapp">
<title>How to obtain &okular;</title>
&install.intro.documentation;
</sect1>
<sect1 id="compilation">
<title>Compilation and Installation</title>
<note>
<para>
If you are reading this help in the &khelpcenter;, &okular; has already been
installed on this system and you do not need install it anymore.
</para>
</note>
&install.compile.documentation;
</sect1>
</appendix>
&documentation.index;
</book>
<!--
Local Variables:
mode: sgml
sgml-minimize-attributes:nil
sgml-general-insert-case:lower
sgml-indent-step:0
sgml-indent-data:nil
End:
// vim:ts=2:sw=2:tw=78:noet
--> |
import { render } from '@testing-library/react';
import { createMemoryHistory } from 'history';
import React from 'react';
import { Router } from 'react-router-dom';
import RecipeProvider from '../../context/RecipeProvider';
function renderWithRouterAndContext(component, path = '/') {
const history = createMemoryHistory({ initialEntries: [path] });
return {
...render(
<RecipeProvider>
<Router history={ history }>
{component}
</Router>
</RecipeProvider>,
),
history,
};
}
export default renderWithRouterAndContext; |
/**
* クラス名:CRMDPUpdAccountIndustryBatchTest
* クラス概要:取引先.業種の更新バッチテストクラス
------------------------------------------------------------------------------------------------------
* Project Name: デジタルセールス高度化Ph4
------------------------------------------------------------------------------------------------------
* Created Date: 2023/11/22
* Updated Date: -
------------------------------------------------------------------------------------------------------
*/
@isTest
public with sharing class CRMDPUpdAccountIndustryBatchTest {
@TestSetup
static void setup() {
// アタックリスト
List<mpOpportunity__c> mpOppList = new List<mpOpportunity__c>();
for (Integer i = 0; i < 22; i++) {
mpOpportunity__c mpOpp = new mpOpportunity__c();
mpOpp = TestDataFactory.createMpOpportunity('アタックリスト' + String.valueOf(i+1), mpUtilString.getRecordTypeByDeveloperName(mpOpportunity__c.sObjectType, 'mpList'), false);
mpOppList.add(mpOpp);
}
mpOppList[0].MerchandiseClassification__c = '食品スーパー';
mpOppList[1].MerchandiseClassification__c = '各種小売';
mpOppList[2].MerchandiseClassification__c = '大規模小売店';
mpOppList[3].MerchandiseClassification__c = '公共サービス';
mpOppList[4].MerchandiseClassification__c = 'コンビニ';
mpOppList[5].MerchandiseClassification__c = '大手向け特別';
mpOppList[6].MerchandiseClassification__c = '学校・教育機関';
mpOppList[7].MerchandiseClassification__c = '行政・公共サービス';
mpOppList[8].MerchandiseClassification__c = '交通';
mpOppList[9].MerchandiseClassification__c = 'ギフトカード';
mpOppList[10].MerchandiseClassification__c = 'サービス';
mpOppList[11].MerchandiseClassification__c = 'スクール';
mpOppList[12].MerchandiseClassification__c = '病院';
mpOppList[13].MerchandiseClassification__c = 'ビューティ・リラクゼーション';
mpOppList[14].MerchandiseClassification__c = '飲食';
mpOppList[15].MerchandiseClassification__c = '小売';
mpOppList[16].MerchandiseClassification__c = 'テスト';
mpOppList[18].MerchandiseClassification__c = '小売';
mpOppList[19].MerchandiseClassification__c = '飲食';
mpOppList[20].MerchandiseClassification__c = '娯楽';
insert mpOppList;
// 取引先
List<Account> accList = new List<Account>();
for (Integer i = 0; i < 21; i++) {
Account acc = new Account();
if (i < 15) {
acc = TestDataFactory.createAccount('【取引先_業種更新テスト】個店・取引先' + String.valueOf(i+1), Constant.ACC_DEVELOPER_NAME_MEMBER, false);
}
else if (i < 19) {
acc = TestDataFactory.createAccount('【取引先_業種更新テスト】個店・見込取引先' + String.valueOf(i+1), Constant.ACC_DEVELOPER_NAME_NON_MEMBER, false);
}
else {
acc = TestDataFactory.createAccount('【取引先_業種更新テスト】エンプラ・取引先' + String.valueOf(i+1), Constant.ACC_DEVELOPER_NAME_MEMBER, false);
}
// 移行元アタックリスト設定
if (0 < i) {
acc.CRMDPAccountId__c = mpOppList[i-1].Id;
}
accList.add(acc);
}
insert accList;
// 企業分割取引先
Account acc1 = TestDataFactory.createAccount('【取引先_業種更新テスト】企業分割1-1', Constant.ACC_DEVELOPER_NAME_MEMBER, false);
Account acc2 = TestDataFactory.createAccount('【取引先_業種更新テスト】企業分割1-2', Constant.ACC_DEVELOPER_NAME_MEMBER, false);
// Id pearentId = [SELECT Id FROM Account WHERE Name = 'エンプラ取引先1'];
acc1.ParentId = accList[0].Id;
acc1.CRMDPAccountId__c = mpOppList[20].Id;
acc2.ParentId = accList[0].Id;
insert new List<Account>{acc1, acc2};
// 案件
List<Opportunity> oppList = new List<Opportunity>();
for (Integer i = 0; i < 22; i++) {
Opportunity opp = new Opportunity();
if (i < 18) {
opp = TestDataFactory.createOpportunity('個店案件' + String.valueOf(i+1), accList[i+1].Id, Date.newInstance(2099, 10, 1), Constant.OPP_DEVELOPER_NAME_INDIVSALES, false);
}
else if (i < 20) {
opp = TestDataFactory.createOpportunity('エンプラ案件' + String.valueOf(i+1), accList[i+1].Id, Date.newInstance(2099, 10, 1), Constant.OPP_DEVELOPER_NAME_ENTERPRISE_OFFLINE, false);
}
else if (i == 20) {
opp = TestDataFactory.createOpportunity('個店企業分割案件' + String.valueOf(i+1), acc1.Id, Date.newInstance(2099, 10, 1), Constant.OPP_DEVELOPER_NAME_INDIVSALES, false);
}
else {
opp = TestDataFactory.createOpportunity('個店企業分割案件' + String.valueOf(i+1), acc2.Id, Date.newInstance(2099, 10, 1), Constant.OPP_DEVELOPER_NAME_INDIVSALES, false);
}
oppList.add(opp);
}
insert oppList;
}
/**
* 取引先.業種の更新バッチ 全件成功
*/
@isTest
private static void update_accountIndustry_success() {
DateTime executionDate = DateTime.newInstance(2024, 01, 01, 00, 00, 00);
Test.startTest();
CRMDPUpdAccountIndustryBatch.run(executionDate);
Test.stopTest();
// 取引先を取得
List<Account> expectAccList = [
SELECT Id, Industry, CRMDPAccountId__r.MerchandiseClassification__c
FROM Account
WHERE CRMDPAccountId__c != null
AND Id IN (SELECT AccountId FROM Opportunity WHERE RecordType.DeveloperName = :Constant.OPP_DEVELOPER_NAME_INDIVSALES)];
// 移行元アタックリストがある取引先レコード = 19
System.assertEquals(19, expectAccList.size(), 'test_CRMDPUpdAccountIndustryBatchTest_size_success');
List<String> ngText = new List<String>{'テスト', 'ギフトカード'};
for (Account expAcc : expectAccList) {
String val = expAcc.CRMDPAccountId__r.MerchandiseClassification__c;
if (ngText.contains(val)) {
System.assertEquals(null, expAcc.Industry, 'test_CRMDPUpdAccountIndustryBatchTest_value_success');
} else {
System.assertEquals(expAcc.CRMDPAccountId__r.MerchandiseClassification__c, expAcc.Industry, 'test_CRMDPUpdAccountIndustryBatchTest_value_success');
}
}
}
/**
* 取引先.業種の更新バッチ 失敗
* 更新時エラーがある場合
*/
@isTest
private static void update_accountIndustry_ngIndustry_error() {
CRMDPUpdAccountIndustryBatch.testFlag = true;
DateTime executionDate = DateTime.newInstance(2024, 01, 01, 00, 00, 00);
Test.startTest();
CRMDPUpdAccountIndustryBatch.run(executionDate);
Test.stopTest();
// 取引先を取得
List<Account> expectAccList = [
SELECT Id, Industry, CRMDPAccountId__r.MerchandiseClassification__c
FROM Account
WHERE CRMDPAccountId__c != null
AND Id IN (SELECT AccountId FROM Opportunity WHERE RecordType.DeveloperName = :Constant.OPP_DEVELOPER_NAME_INDIVSALES)];
// 移行元アタックリストがある取引先レコード = 19
System.assertEquals(19, expectAccList.size(), 'test_CRMDPUpdAccountIndustryBatchTest_size_success');
String errorLogTitle = CRMDPUpdAccountIndustryBatch.BATCH_LOG_TITLE;
List<Log__c> log = [SELECT Title__c, Level__c, Detail__c FROM Log__c WHERE Title__c LIKE :errorLogTitle + '%'];
System.assertEquals(true, log.size() >= 1, 'cannt get ErrorLog');
System.assertEquals('ERROR', log[0].Level__c, 'not correct logLevel');
}
/**
* 取引先.業種の更新バッチ 失敗
* DMLException
*/
@isTest
private static void update_accountIndustry_dmlExeption_error() {
CRMDPUpdAccountIndustryBatch.isUpdateAccIndustryExceptionTest = true;
DateTime executionDate = DateTime.newInstance(2024, 01, 01, 00, 00, 00);
Test.startTest();
CRMDPUpdAccountIndustryBatch.run(executionDate);
Test.stopTest();
String errorLogTitle = CRMDPUpdAccountIndustryBatch.BATCH_LOG_TITLE;
List<Log__c> log = [SELECT Title__c, Level__c, Detail__c FROM Log__c WHERE Title__c LIKE :errorLogTitle + '%'];
System.assertEquals(true, log.size() >= 1, 'cannt get ErrorLog');
System.assertEquals('ERROR', log[0].Level__c, 'not correct logLevel');
}
} |
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class RegisterPage extends StatefulWidget {
@override
_RegisterPageState createState() => _RegisterPageState();
}
class _RegisterPageState extends State<RegisterPage> {
TextEditingController nameController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
Future<void> _register() async {
final response = await http.post(
Uri.parse('http://10.0.2.2:8000/api/auth/register'),
body: {
'nama': nameController.text,
'kelas': 'costumer',
'email': emailController.text,
'password': passwordController.text,
},
);
if (response.statusCode == 201) {
final data = jsonDecode(response.body);
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Registration Successful'),
content: Text(data['message']),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('OK'),
),
],
),
);
} else {
final data = jsonDecode(response.body);
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Registration Failed'),
content: Text(data['message']),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('OK'),
),
],
),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Register'),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
controller: nameController,
decoration: InputDecoration(labelText: 'Name'),
),
TextField(
controller: emailController,
decoration: InputDecoration(labelText: 'Email'),
),
TextField(
controller: passwordController,
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
),
SizedBox(height: 16.0),
ElevatedButton(
onPressed: _register,
child: Text('Register'),
),
],
),
),
);
}
} |
// Copyright (c) 2002-2004 Brian Wellington (bwelling@xbill.org)
package org.xbill.DNS;
import java.util.*;
import java.io.*;
import java.net.*;
/**
* The Lookup object issues queries to caching DNS servers. The input consists
* of a name, an optional type, and an optional class. Caching is enabled
* by default and used when possible to reduce the number of DNS requests.
* A Resolver, which defaults to an ExtendedResolver initialized with the
* resolvers located by the ResolverConfig class, performs the queries. A
* search path of domain suffixes is used to resolve relative names, and is
* also determined by the ResolverConfig class.
*
* A Lookup object may be reused, but should not be used by multiple threads.
*
* @see Cache
* @see Resolver
* @see ResolverConfig
*
* @author Brian Wellington
*/
public final class Lookup {
private static Resolver defaultResolver;
private static Name [] defaultSearchPath;
private static Map defaultCaches;
private Resolver resolver;
private Name [] searchPath;
private Cache cache;
private boolean temporary_cache;
private int credibility;
private Name name;
private int type;
private int dclass;
private boolean verbose;
private int iterations;
private boolean foundAlias;
private boolean done;
private boolean doneCurrent;
private List aliases;
private Record [] answers;
private int result;
private String error;
private boolean nxdomain;
private boolean badresponse;
private String badresponse_error;
private boolean networkerror;
private boolean timedout;
private boolean nametoolong;
private boolean referral;
private static final Name [] noAliases = new Name[0];
/** The lookup was successful. */
public static final int SUCCESSFUL = 0;
/**
* The lookup failed due to a data or server error. Repeating the lookup
* would not be helpful.
*/
public static final int UNRECOVERABLE = 1;
/**
* The lookup failed due to a network error. Repeating the lookup may be
* helpful.
*/
public static final int TRY_AGAIN = 2;
/** The host does not exist. */
public static final int HOST_NOT_FOUND = 3;
/** The host exists, but has no records associated with the queried type. */
public static final int TYPE_NOT_FOUND = 4;
public static synchronized void
refreshDefault() {
try {
defaultResolver = new ExtendedResolver();
}
catch (UnknownHostException e) {
throw new RuntimeException("Failed to initialize resolver");
}
defaultSearchPath = FindServer.searchPath();
defaultCaches = new HashMap();
}
static {
refreshDefault();
}
/**
* Gets the Resolver that will be used as the default by future Lookups.
* @return The default resolver.
*/
public static synchronized Resolver
getDefaultResolver() {
return defaultResolver;
}
/**
* Sets the default Resolver to be used as the default by future Lookups.
* @param resolver The default resolver.
*/
public static synchronized void
setDefaultResolver(Resolver resolver) {
defaultResolver = resolver;
}
/**
* Gets the Cache that will be used as the default for the specified
* class by future Lookups.
* @param dclass The class whose cache is being retrieved.
* @return The default cache for the specified class.
*/
public static synchronized Cache
getDefaultCache(int dclass) {
DClass.check(dclass);
Cache c = (Cache) defaultCaches.get(Mnemonic.toInteger(dclass));
if (c == null) {
c = new Cache(dclass);
defaultCaches.put(Mnemonic.toInteger(dclass), c);
}
return c;
}
/**
* Sets the Cache to be used as the default for the specified class by future
* Lookups.
* @param cache The default cache for the specified class.
* @param dclass The class whose cache is being set.
*/
public static synchronized void
setDefaultCache(Cache cache, int dclass) {
DClass.check(dclass);
defaultCaches.put(Mnemonic.toInteger(dclass), cache);
}
/**
* Gets the search path that will be used as the default by future Lookups.
* @return The default search path.
*/
public static synchronized Name []
getDefaultSearchPath() {
return defaultSearchPath;
}
/**
* Sets the search path to be used as the default by future Lookups.
* @param domains The default search path.
*/
public static synchronized void
setDefaultSearchPath(Name [] domains) {
defaultSearchPath = domains;
}
/**
* Sets the search path that will be used as the default by future Lookups.
* @param domains The default search path.
* @throws TextParseException A name in the array is not a valid DNS name.
*/
public static synchronized void
setDefaultSearchPath(String [] domains) throws TextParseException {
if (domains == null) {
defaultSearchPath = null;
return;
}
Name [] newdomains = new Name[domains.length];
for (int i = 0; i < domains.length; i++)
newdomains[i] = Name.fromString(domains[i], Name.root);
defaultSearchPath = newdomains;
}
private final void
reset() {
iterations = 0;
foundAlias = false;
done = false;
doneCurrent = false;
aliases = null;
answers = null;
result = -1;
error = null;
nxdomain = false;
badresponse = false;
badresponse_error = null;
networkerror = false;
timedout = false;
nametoolong = false;
referral = false;
if (temporary_cache)
cache.clearCache();
}
/**
* Create a Lookup object that will find records of the given name, type,
* and class. The lookup will use the default cache, resolver, and search
* path, and look for records that are reasonably credible.
* @param name The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @throws IllegalArgumentException The type is a meta type other than ANY.
* @see Cache
* @see Resolver
* @see Credibility
* @see Name
* @see Type
* @see DClass
*/
public
Lookup(Name name, int type, int dclass) {
Type.check(type);
DClass.check(dclass);
if (!Type.isRR(type) && type != Type.ANY)
throw new IllegalArgumentException("Cannot query for " +
"meta-types other than ANY");
this.name = name;
this.type = type;
this.dclass = dclass;
synchronized (Lookup.class) {
this.resolver = getDefaultResolver();
this.searchPath = getDefaultSearchPath();
this.cache = getDefaultCache(dclass);
}
this.credibility = Credibility.NORMAL;
this.verbose = Options.check("verbose");
this.result = -1;
}
/**
* Create a Lookup object that will find records of the given name and type
* in the IN class.
* @param name The name of the desired records
* @param type The type of the desired records
* @throws IllegalArgumentException The type is a meta type other than ANY.
* @see #Lookup(Name,int,int)
*/
public
Lookup(Name name, int type) {
this(name, type, DClass.IN);
}
/**
* Create a Lookup object that will find records of type A at the given name
* in the IN class.
* @param name The name of the desired records
* @see #Lookup(Name,int,int)
*/
public
Lookup(Name name) {
this(name, Type.A, DClass.IN);
}
/**
* Create a Lookup object that will find records of the given name, type,
* and class.
* @param name The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @throws TextParseException The name is not a valid DNS name
* @throws IllegalArgumentException The type is a meta type other than ANY.
* @see #Lookup(Name,int,int)
*/
public
Lookup(String name, int type, int dclass) throws TextParseException {
this(Name.fromString(name), type, dclass);
}
/**
* Create a Lookup object that will find records of the given name and type
* in the IN class.
* @param name The name of the desired records
* @param type The type of the desired records
* @throws TextParseException The name is not a valid DNS name
* @throws IllegalArgumentException The type is a meta type other than ANY.
* @see #Lookup(Name,int,int)
*/
public
Lookup(String name, int type) throws TextParseException {
this(Name.fromString(name), type, DClass.IN);
}
/**
* Create a Lookup object that will find records of type A at the given name
* in the IN class.
* @param name The name of the desired records
* @throws TextParseException The name is not a valid DNS name
* @see #Lookup(Name,int,int)
*/
public
Lookup(String name) throws TextParseException {
this(Name.fromString(name), Type.A, DClass.IN);
}
/**
* Sets the resolver to use when performing this lookup. This overrides the
* default value.
* @param resolver The resolver to use.
*/
public void
setResolver(Resolver resolver) {
this.resolver = resolver;
}
/**
* Sets the search path to use when performing this lookup. This overrides the
* default value.
* @param domains An array of names containing the search path.
*/
public void
setSearchPath(Name [] domains) {
this.searchPath = domains;
}
/**
* Sets the search path to use when performing this lookup. This overrides the
* default value.
* @param domains An array of names containing the search path.
* @throws TextParseException A name in the array is not a valid DNS name.
*/
public void
setSearchPath(String [] domains) throws TextParseException {
if (domains == null) {
this.searchPath = null;
return;
}
Name [] newdomains = new Name[domains.length];
for (int i = 0; i < domains.length; i++)
newdomains[i] = Name.fromString(domains[i], Name.root);
this.searchPath = newdomains;
}
/**
* Sets the cache to use when performing this lookup. This overrides the
* default value. If the results of this lookup should not be permanently
* cached, null can be provided here.
* @param cache The cache to use.
*/
public void
setCache(Cache cache) {
if (cache == null) {
this.cache = new Cache(dclass, 0);
this.temporary_cache = true;
} else {
this.cache = cache;
this.temporary_cache = false;
}
}
/**
* Sets the minimum credibility level that will be accepted when performing
* the lookup. This defaults to Crefibility.NORMAL.
* @param credibility The minimum credibility level.
*/
public void
setCredibility(int credibility) {
this.credibility = credibility;
}
private void
follow(Name name, Name oldname) {
foundAlias = true;
badresponse = false;
networkerror = false;
timedout = false;
nxdomain = false;
referral = false;
iterations++;
if (iterations >= 6 || name.equals(oldname)) {
result = UNRECOVERABLE;
error = "CNAME loop";
done = true;
return;
}
if (aliases == null)
aliases = new ArrayList();
aliases.add(name);
lookup(name);
}
private void
processResponse(Name name, SetResponse response) {
if (response.isSuccessful()) {
RRset [] rrsets = response.answers();
List l = new ArrayList();
Iterator it;
int i;
for (i = 0; i < rrsets.length; i++) {
it = rrsets[i].rrs();
while (it.hasNext())
l.add(it.next());
}
result = SUCCESSFUL;
answers = (Record []) l.toArray(new Record[l.size()]);
done = true;
} else if (response.isNXDOMAIN()) {
nxdomain = true;
doneCurrent = true;
if (iterations > 0) {
result = HOST_NOT_FOUND;
done = true;
}
} else if (response.isNXRRSET()) {
result = TYPE_NOT_FOUND;
answers = null;
done = true;
} else if (response.isCNAME()) {
CNAMERecord cname = response.getCNAME();
follow(cname.getTarget(), name);
} else if (response.isDNAME()) {
DNAMERecord dname = response.getDNAME();
Name newname = null;
try {
follow(name.fromDNAME(dname), name);
} catch (NameTooLongException e) {
result = UNRECOVERABLE;
error = "Invalid DNAME target";
done = true;
}
} else if (response.isDelegation()) {
// We shouldn't get a referral. Ignore it.
referral = true;
}
}
private void
lookup(Name current) {
SetResponse sr = cache.lookupRecords(current, type, credibility);
if (verbose) {
System.err.println("lookup " + current + " " +
Type.string(type));
System.err.println(sr);
}
processResponse(current, sr);
if (done || doneCurrent)
return;
Record question = Record.newRecord(current, type, dclass);
Message query = Message.newQuery(question);
Message response = null;
try {
response = resolver.send(query);
}
catch (IOException e) {
// A network error occurred. Press on.
if (e instanceof InterruptedIOException)
timedout = true;
else
networkerror = true;
return;
}
int rcode = response.getHeader().getRcode();
if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) {
// The server we contacted is broken or otherwise unhelpful.
// Press on.
badresponse = true;
badresponse_error = Rcode.string(rcode);
return;
}
if (!query.getQuestion().equals(response.getQuestion())) {
// The answer doesn't match the question. That's not good.
badresponse = true;
badresponse_error = "response does not match query";
return;
}
sr = cache.addMessage(response);
if (sr == null)
sr = cache.lookupRecords(current, type, credibility);
if (verbose) {
System.err.println("queried " + current + " " +
Type.string(type));
System.err.println(sr);
}
processResponse(current, sr);
}
private void
resolve(Name current, Name suffix) {
doneCurrent = false;
Name tname = null;
if (suffix == null)
tname = current;
else {
try {
tname = Name.concatenate(current, suffix);
}
catch (NameTooLongException e) {
nametoolong = true;
return;
}
}
lookup(tname);
}
/**
* Performs the lookup, using the specified Cache, Resolver, and search path.
* @return The answers, or null if none are found.
*/
public Record []
run() {
if (done)
reset();
if (name.isAbsolute())
resolve(name, null);
else if (searchPath == null)
resolve(name, Name.root);
else {
if (name.labels() > 1)
resolve(name, Name.root);
if (done)
return answers;
for (int i = 0; i < searchPath.length; i++) {
resolve(name, searchPath[i]);
if (done)
return answers;
else if (foundAlias)
break;
}
}
if (!done) {
if (badresponse) {
result = TRY_AGAIN;
error = badresponse_error;
done = true;
} else if (timedout) {
result = TRY_AGAIN;
error = "timed out";
done = true;
} else if (networkerror) {
result = TRY_AGAIN;
error = "network error";
done = true;
} else if (nxdomain) {
result = HOST_NOT_FOUND;
done = true;
} else if (referral) {
result = UNRECOVERABLE;
error = "referral";
done = true;
} else if (nametoolong) {
result = UNRECOVERABLE;
error = "name too long";
done = true;
}
}
return answers;
}
private void
checkDone() {
if (done && result != -1)
return;
StringBuffer sb = new StringBuffer("Lookup of " + name + " ");
if (dclass != DClass.IN)
sb.append(DClass.string(dclass) + " ");
sb.append(Type.string(type) + " isn't done");
throw new IllegalStateException(sb.toString());
}
/**
* Returns the answers from the lookup.
* @return The answers, or null if none are found.
* @throws IllegalStateException The lookup has not completed.
*/
public Record []
getAnswers() {
checkDone();
return answers;
}
/**
* Returns all known aliases for this name. Whenever a CNAME/DNAME is
* followed, an alias is added to this array. The last element in this
* array will be the owner name for records in the answer, if there are any.
* @return The aliases.
* @throws IllegalStateException The lookup has not completed.
*/
public Name []
getAliases() {
checkDone();
if (aliases == null)
return noAliases;
return (Name []) aliases.toArray(new Name[aliases.size()]);
}
/**
* Returns the result code of the lookup.
* @return The result code, which can be SUCCESSFUL, UNRECOVERABLE, TRY_AGAIN,
* HOST_NOT_FOUND, or TYPE_NOT_FOUND.
* @throws IllegalStateException The lookup has not completed.
*/
public int
getResult() {
checkDone();
return result;
}
/**
* Returns an error string describing the result code of this lookup.
* @return A string, which may either directly correspond the result code
* or be more specific.
* @throws IllegalStateException The lookup has not completed.
*/
public String
getErrorString() {
checkDone();
if (error != null)
return error;
switch (result) {
case SUCCESSFUL: return "successful";
case UNRECOVERABLE: return "unrecoverable error";
case TRY_AGAIN: return "try again";
case HOST_NOT_FOUND: return "host not found";
case TYPE_NOT_FOUND: return "type not found";
}
throw new IllegalStateException("unknown result");
}
} |
import {Drawer, Input, Col, Select, Form, Row, Button, Upload, message} from 'antd'
import React, {useEffect, useState} from "react";
import axios, {toFormData} from "axios";
import {LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import {useNavigate} from "react-router-dom";
const {Option} = Select;
function AddCreatorDrawer({showDrawer, setShowDrawer}) {
const [file, setFile] = useState(null);
const [fileName, setFileName] = useState('Choose File');
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const onClose=()=>setShowDrawer(false);
const onFinish = values => {
alert(JSON.stringify(values, null, 2));
};
const onFinishFailed = errorInfo => {
alert(JSON.stringify(errorInfo, null, 2));
};
const handleChange = (info) => {
setFile(info.file.originFileObj);
setFileName(info.file.name);
};
const handleSubmit = () => {
setLoading(true);
const formData = new FormData();
formData.append('file', file);
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then((response) => {
console.log(response.data);
message.success('File uploaded successfully');
setLoading(false);
}).catch((error) => {
console.log(error);
message.error('There was an error uploading the file');
setLoading(false);
});
};
const uploadButton = (
<div>
{loading ? <LoadingOutlined /> : <PlusOutlined />}
<div className="ant-upload-text">{fileName}</div>
</div>
);
const saveSong = async () => {
const formData = new FormData();
formData.append('file', file);
const a = await (await fetch("http://localhost:8080/api/storage/uploadFile", {
method: 'POST',
mode: 'cors',
header: {
'Content-Type': 'multipart/form-data'
},
body: formData
})).text();
const res = await fetch("http://localhost:8080/api/song", {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: fileName,
url: a,
authorId:2,
album: "a"
})
});
};
console.log(showDrawer);
return <Drawer
title="Create new song"
width={720}
onClose={onClose}
visible={showDrawer}
bodyStyle={{paddingBottom: 80}}
footer={
<div
style={{ textAlign:'right'
}}
>
<Button onClick={onClose} style={{marginRight: 8}}> Cansel</Button>
</div>
}
>
<Form layout="vertical"
onFinishFailed={onFinishFailed}
onFinish={onFinish}
hideRequiredMark>
<Row gutter={16}>
<Col span={12}>
<Form.Item
name="name"
label="Name"
rules={[{required: true, message: 'Please enter'}]}>
<Input placeholder="Please enter song name"/>
</Form.Item>
</Col>
</Row>
<Row>
<Col>
<Form.Item>
<Upload
name="file"
listType="text"
type="file"
className="upload-demo-start"
accept=".mp3"
fileList={file ? [{ name: fileName }] : []}
onChange={handleChange}
>
{file ? null : uploadButton}
</Upload>
</Form.Item>
</Col>
</Row>
<Row>
<Col>
<Form.Item>
<Button type="primary" htmlType="submit" onClick={saveSong}>
Submit
</Button>
</Form.Item>
</Col>
</Row>
</Form>
</Drawer>
}
export default AddCreatorDrawer; |
package Games::Bettor::Martingale;
use warnings;
use strict;
use Carp;
use Data::Dumper;
sub new{
my ( $class, %args ) = @_;
$args{'percent'} = 0 unless exists $args{'percent'} && defined $args{'percent'};
bless{
name => 'Martingale',
amount => $args{'amount'},
percent => $args{'percent'} * .01,
prior_bet => undef
}, $class;
}
sub name{
my ( $self ) = @_;
return $self->{'name'};
}
sub get_bet{
my ( $self, %args ) = @_;
my $bet;
# if there's no prior bet, this is the first bet, so return the base bet
# otherwise, check the prior result
# if the prior result was a win, use the base bet
# otherwise, double the size of the last bet and return that
if( ! defined $self->{'prior_bet'} ){
$bet = _get_base_bet( $self, $args{'bankroll'} );
}else{
if( $args{'history'}[-1]{'result'} == 1 ){
$bet = _get_base_bet( $self, $args{'bankroll'} );
}else{
$bet = $self->{'prior_bet'} * 2;
}
}
$self->{'prior_bet'} = $bet;
return $bet;
}
sub _get_base_bet{
my ( $self, $bankroll ) = @_;
my $bet;
if( $self->{'amount'} ){ $bet = $self->{'amount'};
}elsif( $self->{'percent'} ){ $bet = $bankroll * $self->{'percent'};
}else{ $bet = 0;
}
return $bet;
}
=head1 NAME
Games::Bettor::Martingale - A class that holds the methods for a martingale bettor
=head1 VERSION
Version 1.0
=cut
our $VERSION = '1.00';
=head1 SYNOPSIS
use Games::Bettor::Martingale;
$bettor = Games::Bettor::Martingale->new( amount => 1 );
$bettor = Games::Bettor::Martingale->new( percent => 10 );
=head1 DESCRIPTION
This method represents a bettor who always bets using the Martingale system. This bettor will always bet the
same amount on the first bet and on any subsequent bet where he has won the previous trial. If he has lost
the previous trial, he will double his last bet until he wins.
=head1 METHODS
=head2 new
$method = Games::Bettor::Martingale->new( amount => 1 );
$method = Games::Bettor::Martingale->new( percent => 10 );
amount: The amount of bet on each round in absolute betting units.
percent: The amount fo bet on each round in percentage of bankroll.
=head2 name
$method_name = $method->name();
Returns the name of the betting method.
=head2 get_bet
$amount = $method->get_bet( bankroll => $bankroll );
Returns the amount to bet for this trial. The bankroll argument is the amount of the bankroll currently for
the Bettor object using this method.
=head1 AUTHOR
Troy Denkinger, C<< <tdenkinger at gmail.com> >>
=head1 BUGS
Please report any bugs or feature requests to
C<bug-games-bettor at rt.cpan.org>, or through the web interface at
L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Games-Bettor>.
I will be notified, and then you'll automatically be notified of progress on
your bug as I make changes.
=head1 SUPPORT
You can find documentation for this module with the perldoc command.
perldoc Games::Bettor::Martingale
You can also look for information at:
=over 4
=item * AnnoCPAN: Annotated CPAN documentation
L<http://annocpan.org/dist/Games-Bettor>
=item * CPAN Ratings
L<http://cpanratings.perl.org/d/Games-Bettor>
=item * RT: CPAN's request tracker
L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Games-Bettor>
=item * Search CPAN
L<http://search.cpan.org/dist/Games-Bettor>
=back
=head1 ACKNOWLEDGEMENTS
=head1 COPYRIGHT & LICENSE
Copyright 2006 Troy Denkinger, all rights reserved.
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=cut
1; # End of Games::Bettor::Martingale |
---
title: "clean_this_is_me"
output: html_document
date: "2024-05-02"
---
## Purpose
Prepare This is Me transcript data for narrative identity coding and other types of future analyses. Note that this script should _not_ rewrite the files once training is underway!
## Inputs
- .csv files created by copying and pasting the word doc transcriptions of
## Outputs
- .csv file with a master key relating each transcript to its randomized id (random_id)
- .csv file with randomized id and each transcript, with a greater proportion of later waves in the first 150 transcripts for training (40 from wave 4, 50 from wave 5, the rest are random draws from waves 1-3)
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(pacman)
p_load("dplyr", "tidyr", "knitr", "ggplot2", "tidytext", "stringr", "readr")
```
```{r inputs}
tim_dir <- "/Volumes/psych-cog/dsnlab/TAG/behavior/This_Is_Me/"
waves <- paste0("w", rep(1:5))
```
```{r create a df with all transcripts}
all_text <- data.frame(subject_id = as.character(),
wave = as.character(),
text = as.character())
for (i in 1:length(waves)){
wave <- waves[i]
# read in the data frame
df <- read.csv(paste0(tim_dir, "TRANSCRIPTIONS/", waves[i], "_transcriptions.csv"), header = F)
df <- data.frame(V1 = df[, 1]) # keep first column
df <- filter(df, V1 != " ") # remove blank rows
df <- filter(df, V1 != "")
# subject IDs are anything starting with TAG
subject_ids <- filter(df, startsWith(df$V1, "TAG"))
subject_ids <- str_replace_all(subject_ids$V1, fixed(" "), "") # remove the space if one got introduced
subject_ids <- substr(subject_ids, start = 1, stop = 6) # only keep the TAG ID (so ignoring "verified by" or other notes)
# text is anything _not_ starting with TAG
text <- filter(df, !startsWith(df$V1, "TAG")) # | startsWith(df$V1, "0")) # create text var w/ lines that start with S; a few typos without the word S, so I start with "0" sometimes
# if there's the same number of units of subject IDs and text, then put these together into a data frame
if(length(subject_ids) == nrow(text)){
temp <- data.frame(subject_id = subject_ids,
wave = wave,
text = text)
colnames(temp) <- c("subject_id", "wave", "text")
all_text <- rbind(all_text, temp) # append to whatever we have going on from the other waves
} else {print(paste0("differing numbers of subject ids and text for wave ", wave))} # otherwise print that the subject IDs and waves don't match
}
all_text$subj_wave_id <- paste(all_text$subject_id, all_text$wave, sep = "_")
# manual edits
# remove TAG026 version 1 (they restarted)
all_text <- filter(all_text, !(subject_id == "TAG026" & grepl("Can I start over?", text)))
# other misc notes
# TAG181 and TAG194 has no transcript and was removed from the csv
# had to delete comments at the end of w5 transcripts
# spot checked alignment with original transcripts on 5/2/2024
```
```{r create training set}
# first 150 should oversample from waves 4 and 5 -- so 40 from each, then the remaining 70 from waves 1-3
# randomly re-order wave 5 data
w5_text <- all_text %>% filter(wave == "w5")
random_nums_w5 <- sample(1:nrow(w5_text), size = nrow(w5_text), replace = FALSE) # give each participant a random number
w5_text$random_num <- random_nums_w5
random_order_w5_text <- w5_text[order(w5_text$random_num), ] # re order the dataframe
# do the same with wave 4 data
w4_text <- all_text %>% filter(wave == "w4")
random_nums_w4 <- sample(1:nrow(w4_text), size = nrow(w4_text), replace = FALSE)
w4_text$random_num <- random_nums_w4
random_order_w4_text <- w4_text[order(w4_text$random_num), ]
# randomly select from waves 1-3
rest_of_data <- rbind(all_text %>% filter(wave != "w5" & wave != "w4")) %>%
mutate(random_num = sample(1:nrow(.), size = nrow(.), replace = FALSE))
random_order_rest_of_data <- rest_of_data[order(rest_of_data$random_num), ]
# combine these three sets to create a training data set
training_data <- rbind(random_order_w5_text[1:40, 1:4], random_order_w4_text[1:40, 1:4], random_order_rest_of_data[1:70, 1:4])
training_data$random_num <- sample(1:nrow(training_data), size = nrow(training_data), replace = FALSE) # now give each of these a _new_ random number
training_data <- training_data[order(training_data$random_num), ] # shuffle the training data based on this random number
```
```{r get the rest of the data}
non_training_data <- all_text %>% filter(!(subj_wave_id %in% training_data$subj_wave_id))
non_training_data$random_num<- sample(151:(150+nrow(non_training_data)), size = nrow(non_training_data), replace = FALSE) # random number from 151 to 510
```
```{r combine training and non-training dfs}
all_text_reordered <- rbind(training_data, non_training_data )
all_text_reordered <- all_text_reordered[order(all_text_reordered$random_num), ]
# change random_num into random_id
all_text_reordered$random_id <- str_pad(all_text_reordered$random_num, width = 3, pad = "0")
all_text_reordered$random_id <- paste0("random_", all_text_reordered$random_id)
```
```{r save two versions}
## do not overwrite once training is underway
# saveRDS(all_text_reordered, file = paste0(tim_dir, "TRANSCRIPTIONS/coding_master_key.rds"))
anonymized_text <- all_text_reordered %>% select(c("random_id", "text"))
#write.csv(anonymized_text, file = paste0(tim_dir, "TRANSCRIPTIONS/coding_anonymized_transcripts.csv"), fileEncoding = "macroman")
```
```{r summary stats, include = F}
all_text %>% group_by(wave) %>%
count()
```
```{r remove text extras, include = F}
# df_wide$text <- filter(df_raw, startsWith(df_raw$V1, "S") | startsWith(df_raw$V1, "0")) # create text var w/ lines that start with S; a few typos without the word S, so I start with "0" sometimes
# df_wide <- as.data.frame(df_wide) # change the list into a dataframe
# colnames(df_wide) <- c("SID", "text") # rename the variables
``` |
/** @license
*
* Copyright (c) Shawn P. Gilroy, Louisiana State University.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {
AuthorizationContextStateInterface,
FirebaseLoginAction,
} from '../interfaces/AuthorizationInterfaces';
export const InitialAuthorizationState = {
user: null,
authIsReady: false,
studentRecruitFlag: false,
adFlag: false,
sysAdminFlag: false,
systemAdministratorFlag: false,
diversityReviewFlag: false,
submissionReviewFlag: false,
};
export enum AuthorizationStates {
LOGIN = 'LOGIN',
LOGOUT = 'LOGOUT',
READY = 'READY',
CLAIMS = 'CLAIMS',
THROWERR = 'THROWERR',
}
/** AuthorizationReducer
*
* Reducer for firestore login
*
* @param {AuthorizationContextStateInterface} state Current state
* @param {FirebaseLoginAction} action Action type
* @returns {AuthorizationContextStateInterface}
*/
export function authorizationReducer(
state: AuthorizationContextStateInterface,
action: FirebaseLoginAction,
): AuthorizationContextStateInterface {
switch (action.type) {
case AuthorizationStates.LOGIN:
return {
...state,
user: action.payloadUser,
authIsReady: false,
studentRecruitFlag: action.payloadStudentRecruitmentFlag,
systemAdministratorFlag: action.payloadFlagSysAdmin,
diversityReviewFlag: action.payloadDiversityReviewFlag,
};
case AuthorizationStates.LOGOUT:
return {
...state,
user: null,
studentRecruitFlag: false,
systemAdministratorFlag: false,
diversityReviewFlag: false,
};
case AuthorizationStates.READY:
return {
user: action.payloadUser,
authIsReady: true,
studentRecruitFlag: action.payloadStudentRecruitmentFlag,
systemAdministratorFlag: action.payloadFlagSysAdmin,
diversityReviewFlag: action.payloadDiversityReviewFlag,
submissionReviewFlag: action.payloadFlagSubmissionReview,
} as AuthorizationContextStateInterface;
case AuthorizationStates.CLAIMS:
return {
user: action.payloadUser,
authIsReady: true,
studentRecruitFlag: action.payloadStudentRecruitmentFlag,
systemAdministratorFlag: action.payloadFlagSysAdmin,
diversityReviewFlag: action.payloadDiversityReviewFlag,
submissionReviewFlag: action.payloadFlagSubmissionReview,
} as AuthorizationContextStateInterface;
default:
return state;
}
} |
import { MainCartList } from '@components/MainCartList/MainCartList';
import { List, Typography, Button } from 'antd';
const { Paragraph, Link, Text } = Typography;
import { AndroidFilled, AppleFilled } from '@ant-design/icons';
import styles from './main-page.module.css';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '@redux/configure-store';
import { push } from 'redux-first-history';
import { Loader } from '@components/Loader/Loader';
import { feedbacksAsync } from '@redux/actions/feedback';
export const MainPage: React.FC = () => {
const data = [
'— планировать свои тренировки на календаре, выбирая тип и уровень нагрузки;',
'— отслеживать свои достижения в разделе статистики, сравнивая свои результаты с нормами и рекордами;',
' — создавать свой профиль, где ты можешь загружать свои фото, видео и отзывы о тренировках;',
'— выполнять расписанные тренировки для разных частей тела, следуя подробным инструкциям и советам профессиональных тренеров',
];
const dispatch = useDispatch<AppDispatch>();
const isLoadingFeedbacks = useSelector((state: RootState) => state.feedbacks.isLoading);
const isErrorFeedbacks = useSelector((state: RootState) => state.feedbacks.error);
const getReviews = async () => {
if(!isErrorFeedbacks && (localStorage.getItem('token') || sessionStorage.getItem('token'))) {
await dispatch(feedbacksAsync());
}
if(!isLoadingFeedbacks) {
dispatch(push('/feedbacks'))
}
}
return (
<>
{isLoadingFeedbacks && <Loader/>}
<div className={styles.mainWrapper}>
<List
className={styles.mainList}
header={<div>С CleverFit ты сможешь:</div>}
dataSource={data}
renderItem={(item) => <List.Item>{item}</List.Item>}
/>
<Paragraph className={styles.mainText}>CleverFit — это
не просто приложение, а твой личный помощник в мире фитнеса.
Не откладывай на завтра — начни
тренироваться уже сегодня!
</Paragraph>
<MainCartList />
<div className={styles.cardBlockDowload}>
<button className={styles.mainLinkReviews} onClick={getReviews} data-test-id='see-reviews'>
Смотреть отзывы
</button>
<div className={styles.cartDownload}>
<div className={styles.cartDownloadTitleBlock}>
<Link href="#" className={styles.cartDownloadLink}>Скачать на телефон</Link>
<Text type="secondary" className={styles.cartDownloadText}>Доступно в PRO-тарифе</Text>
</div>
<div className={styles.cartDownloadContent}>
<Button className={styles.cartDownloadLinkText} type="link" href='#' icon={<AndroidFilled style={{ color: '#262626' }} />}>
Android OS
</Button>
<Button className={styles.cartDownloadLinkText} type="link" href='#' icon={<AppleFilled style={{ color: '#262626' }} />}>
Apple iOS
</Button>
</div>
</div>
</div>
</div>
</>
)
}; |
package com.francle.hello.feature.profile.data.response
import com.francle.hello.feature.profile.domain.model.User
data class UserProfileResponse(
val userId: String,
val email: String,
val username: String,
val hashTag: String,
val age: Int?,
val profileImageUrl: String?,
val bannerImageUrl: String?,
val hobbies: List<String>?,
val following: Int,
val followedBy: Int,
val likedCount: Int,
val postCount: Int,
val bio: String?
) {
fun toUser() = User(
userId = userId,
email = email,
username = username,
hashTag = hashTag,
age = age,
profileImageUrl = profileImageUrl,
bannerImageUrl = bannerImageUrl,
hobbies = hobbies,
following = following,
followedBy = followedBy,
likedCount = likedCount,
postCount = postCount,
bio = bio
)
} |
import { useEffect, useState } from "react";
import PropTypes from "prop-types";
import { ThreeDots } from "react-loader-spinner";
import UserCard from "../UserCard/UserCard";
import fetchUsers from "../../api/fetchUsers";
import { normalizeData } from "../../helpers/normalizeData";
import styles from "./UserSection.module.scss";
const UserSection = ({ users, setUsers }) => {
const [nextUrl, setNextUrl] = useState("");
const [firstFetch, setFirstFetch] = useState(true);
const [lastPage, setLastPage] = useState(false);
const [load, setLoad] = useState(false);
useEffect(() => {
getUsers();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const getUsers = (link) => {
setLoad(true);
const data = fetchUsers(link);
return data
.then((res) => {
const { nextLink, normalized, page, totalPage } = normalizeData(res);
if (firstFetch) {
setUsers([...normalized]);
setFirstFetch(false);
} else {
setUsers((prev) => {
const isPrevUsers = normalized.some((currItem) =>
prev.some((prevItem) => prevItem.id === currItem.id)
);
if (isPrevUsers) return prev;
return [...prev, ...normalized];
});
}
setNextUrl(nextLink);
if (page === totalPage) setLastPage(true);
})
.catch((e) => console.log(e))
.finally(() => setLoad(false));
};
return (
<section className={styles.users} id='users'>
<div className='container'>
<h2 className='title'>Working with GET request</h2>
<div className={styles.usersWrapper}>
{users.map((user) => {
return <UserCard key={user.id} user={user} />;
})}
</div>
<div className={styles.spinnerWrapper}>
{load ? (
<ThreeDots
height='80'
width='80'
radius='9'
color='#f4e041'
ariaLabel='three-dots-loading'
wrapperStyle={{}}
wrapperClassName=''
visible={true}
/>
) : (
!lastPage && (
<button
className={styles.moreButton}
onClick={() => getUsers(nextUrl)}
>
Show more
</button>
)
)}
</div>
</div>
</section>
);
};
export default UserSection;
UserSection.propTypes = {
users: PropTypes.array.isRequired,
setUsers: PropTypes.func.isRequired,
}; |
import React, { createContext, useContext, useState } from "react";
// useContext는 리액트에서 제공해주는 내장 hook함수이다.
// 전역 상태 관리를 도와주는 함수
// react는 데이터의 흐름이 단방향 자식에게 props로 전달 하기 때문에 불편하다
// props로 데이터를 넘겨주지 않아도 컴포넌트들이 데이터를 공유 할 수 있도록
export const Global = createContext();
// createContext 함수를 호출해서 Global객체 생성 context 객체 생성
const Context01 = () => {
return (
<>
<Context02></Context02>
</>
);
};
const Context02 = () => {
const { name, setName } = useContext(Global);
// Global.Provider value로 전달한 값을 받기위해
// useContext()배개 변수로 context 객체를 전달 해준다.
return (
<>
내 이름은{name}
<button
onClick={() => {
setName("soon2");
}}
>
이름 변경
</button>
</>
);
};
const Context = () => {
// 여기가 부모 컴포넌트
const [name, setName] = useState("soon");
// 부모의 상태변수
const obj = {
name,
setName,
};
// 부모의 상태 변수 name과 상태변수 업데이트 함수 setName을 객체의 키값으로 obj 객체 선언
return (
// 전역 상태를 관리할 때 Global.Provider를 최상단 크리로 감싸주고
// value는 정해진 키 전달할 데이터를 넣어준다.(전역 상태)
<Global.Provider value={obj}>
<Context01>Context</Context01>
</Global.Provider>
);
};
export default Context; |
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { WeatherService } from 'src/app/services/weather.service';
import { HttpClient, HttpHandler } from '@angular/common/http';
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [HomeComponent],
imports: [FormsModule ,ReactiveFormsModule],
providers: [HttpClient, HttpHandler]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show zipcode input', () => {
expect(fixture.nativeElement.querySelector('[data-test="zipcode"]')).toBeTruthy();
});
it('TEST form group element count', () => {
const formElement = fixture.debugElement.nativeElement.querySelector('#zipcodeForm');
const inputElements = formElement.querySelectorAll('input');
expect(inputElements.length).toEqual(1);
})
it('should update the zip code value of the input field', () => {
component.formGroup.controls.zipcode.setValue(99999)
const input = fixture.nativeElement.querySelector('#zipcode');
expect(input.value).toEqual('99999');
});
it('should show forecast date and time, temp in farenheit, weather icon', () => {
expect(fixture.nativeElement.querySelector('[data-test="temp-card"]')).toBeTruthy();
})
}); |
{% extends 'base.html' %}
{% block title %}
Добавление новости {{ block.super }}
{% endblock %}
{% block sidebar %}
{% include 'inc/_sidebar.html' %}
{% endblock %}
{% block content %}
<h1>Добавление новости</h1>
<form action="{% url 'add_news' %}" method="post">
{% csrf_token %}
{{ form.non_field.errors }}
{{ form.as_p }}
{% comment %}
<div class="mb-3">
<label for="{{ form.title.id_for_label }}" class="form-label">Названия: </label>
{{ form.title }}
<div class="valid-feedback">
{{ forms.title.errors }}
</div>
<div class="mb-3">
<label for="{{ form.title.id_for_label }}" class="form-label">Текст: </label>
{{ form.content }}
<div class="valid-feedback">
{{ forms.content.errors }}
</div>
<div class="mb-3">
<label for="{{ form.title.id_for_label }}" class="form-label">Опубликовано?</label>
{{ form.is_published }}
<div class="valid-feedback">
{{ forms.is_published.errors }}
</div>
</div>
<div class="mb-3">
<label for="{{ form.title.id_for_label }}" class="form-label">Категория: </label>
{{ form.category }}
<div class="valid-feedback">
{{ forms.category.errors }}
</div>
</div>
</div>
</div>
{% endcomment %}
{% comment %}
{% for field in form %}
<div>
{{ field.label_tag }}
{{ field }}
<div>
{{ field.errors }}
</div>
</div>
{% endfor %}
{% endcomment %}
<button type="submit" class="btn btn-primary btn-blick">Добавить новость</button>
</form>
{% endblock %} |
@if (status==null) {
<section class=" py-16 bg-gray-900 text-center">
<div class="flex justify-center mt-12 -mb-12">
<p-paginator class="text-center" (onPageChange)="onPageChang($event)" [first]="oPaginatorState.first!"
[rows]="oPaginatorState.rows!" [totalRecords]="oPage?.totalElements || 0">
</p-paginator>
</div>
</section>
}
<section class=" py-16 bg-gray-900 text-center -mt-12">
<div class="flex justify-center">
<div class="w-1/2">
<div class="text-center">
<div class="bg-gray-900 p-4 rounded ">
<h1 class="text-2xl font-bold mb-4">Books</h1>
<div class="relative overflow-x-auto">
<table class="table-auto w-full bg-gray-700 text-white border border-gray-600">
<thead>
<tr>
<th class="py-2">ID</th>
<th class="py-2">Date</th>
<th class="py-2">Hour</th>
<th class="py-2">Actions</th>
</tr>
</thead>
<tbody>
@for (booking of oPage?.content; track bookings) {
<tr>
<td class="py-2">{{booking.id}}</td>
<td class="py-2">{{booking.date}}</td>
<td class="py-2">{{booking.time_zone.hour}}</td>
<td class="py-2">
<a class="button bg-blue-500 hover:bg-blue-700 text-white mr-2 mb-2" (click)="getOrderByBooking(booking.id)">
<span class="icon is-small is-left">
<fa-icon [icon]="faEye"></fa-icon>
</span>
</a>
<a class="button bg-blue-500 hover:bg-blue-700 text-white mr-2 mb-2"
(click)="doEditBooking(booking.id)">
<span class="icon is-small is-left">
<fa-icon [icon]="faPen"></fa-icon>
</span>
</a>
<!--@if (booking.date > dateToday) {-->
<a class="button bg-red-500 hover:bg-red-700 text-white mr-2" (click)="doRemoveBooking(booking.id)">
<span class="icon is-small is-left">
<fa-icon [icon]="faTrash"></fa-icon>
</span>
</a>
<!--} -->
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- Confirmation Modal -->
@if (isConfirmationModalVisible) {
<div class="modal-container fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 ">
<div class="bg-gray-800 p-8 rounded shadow-lg">
<div class="text-center text-gray-300">
<h1 class="text-2xl font-bold mb-4">Confirm delete</h1>
<p>Are you sure you want to delete the booking {{oBooking.id}}?</p>
<div class="flex justify-center mt-4">
<button class="button border-red-500 text-white bg-red-500 hover:bg-red-700 mr-2" (click)="confirmDelete()">Delete</button>
<button class="button text-gray-700 bg-gray-300 hover:bg-gray-400" (click)="cancelDelete()">Cancel</button>
</div>
</div>
</div>
</div>
}
<!--Ticket modal-->
@if (ticketModalVisible) {
<div class="modal-container fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 ">
<div class="bg-gray-800 p-8 rounded shadow-lg">
<div class="text-center text-gray-300">
<h1 class="text-2xl font-bold mb-4">Ticket</h1>
@for (order of orders; track orders) {
<div class="flex justify-center mt-4">
<p class="text-white">{{order.product.name}}.....{{order.product.price}} €</p>
</div>
}
<p class="text-white">{{price}} €</p>
<button class="button text-gray-700 bg-gray-300 hover:bg-gray-400 mr-2" (click)="closeModal()">Close</button>
<button class="button border-green-500 bg-green-500 text-white rounded hover:bg-green-600" (click)="printTicket()">Print</button>
</div>
</div>
</div>
}
@if (isEditActive) {
<div class="modal-container fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 ">
<div class="bg-gray-800 p-8 rounded shadow-lg">
<h2 class="mb-4 text-lg text-center text-gray-300 ">Edit</h2>
<div class="p-4 md:p-5">
<form [formGroup]="bookingForm" (ngSubmit)="onSubmit()" class="space-y-4" action="#">
<div hidden>
<label class="text-center block mb-2 text-sm font-medium text-white dark:text-white">Id</label>
<input type="text" formControlName="id"
class="text-center bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"
[value]="bookingForm.get('id')?.value" readonly>
</div>
<div hidden>
<label class="text-center block mb-2 text-sm font-medium text-white dark:text-white">
Date</label>
<input type="text" formControlName="date"
class="text-center bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"
[value]="bookingForm.get('date')?.value" required>
</div>
<div>
<label class="block mb-2 text-center text-sm font-medium text-gray-300 dark:text-white">Hour</label>
<div formGroupName="time_zone">
<select formControlName="hour"
class="block py-2.5 px-0 w-full text-sm text-white bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:text-white dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer">
@for (option of options; track options) {
<option class="text-black bg-slate-600" [value]="option">{{ option }}</option>
}
</select>
</div>
</div>
</form>
</div>
<div class="flex justify-end">
<button (click)="closeModal()" class="px-4 py-2 text-sm bg-gray-300 rounded hover:bg-gray-400">Cancel</button>
<button type="submit" (click)="confirmEditBooking()"
class="ml-2 px-4 py-2 text-sm bg-green-500 text-white rounded hover:bg-green-600">Confirm</button>
</div>
</div>
</div>
}
</section> |
The DPLA Ingestion System
-------------------
Build Status
-------------------
[](https://travis-ci.org/dpla/ingestion)
Documentation
-------------------
Please see the [release notes](https://github.com/dpla/ingestion/wiki/Release-History) regarding changes and upgrade steps.
Setting up the ingestion server:
Install Python 2.7 if not already installed (http://www.python.org/download/releases/2.7/);
Install PIP (http://pip.readthedocs.org/en/latest/installing.html);
Install the ingestion subsystem;
$ pip install --no-deps --ignore-installed -r requirements.txt
Configure an akara.ini file appropriately for your environment;
[Akara]
Port=<port for Akara to run on>
; Recommended LogLevel is one of DEBUG or INFO
LogLevel=<priority>
[CouchDb]
Url=<URL to CouchDB instance, including trailing forward-slash>
Username=<CouchDB username>
Password=<CouchDB password>
SyncQAViews=<True or False; consider False on production>
; Recommended LogLevel is INFO for production; defaults to INFO if not set
LogLevel=<priority>
[Twofishes]
BaseUrl=<URL to Twofishes server, required for geo-enrichments>
[Rackspace]
Username=<Rackspace username>
ApiKey=<Rackspace API key>
DPLAContainer=<Rackspace container for bulk download data>
SitemapContainer=<Rackspace container for sitemap files>
[APITokens]
NYPL=<Your NYPL API token>
[Sitemap]
SitemapURI=<Sitemap URI>
SitemapPath=<Path to local directory for sitemap files>
[Alert]
To=<Comma-separated email addresses to receive alert email>
From=<Email address to send alert email>
[Enrichment]
QueueSize=4
ThreadCount=4
Merge the akara.conf.template and akara.ini file to create the akara.conf file;
$ python setup.py install
Set up and start the Akara server;
$ akara -f akara.conf setup
$ akara -f akara.conf start
Build the database views;
$ python scripts/sync_couch_views.py dpla
$ python scripts/sync_couch_views.py dashboard
$ python scripts/sync_couch_views.py bulk_download
Testing the ingestion server:
You can test it with this set description from Clemson;
$ curl "http://localhost:8889/oai.listrecords.json?endpoint=http://repository.clemson.edu/cgi-bin/oai.exe&oaiset=jfb&limit=10"
If you have the endpoint URL but not a set id, there's a separate service for listing the sets;
$ curl "http://localhost:8889/oai.listsets.json?endpoint=http://repository.clemson.edu/cgi-bin/oai.exe&limit=10"
To run the ingest process run the setup.py script, if not done so already, initialize the database and database views, then feed it a source profile (found in the profiles directory);
$ python setup.py install
$ python scripts/sync_couch_views.py dpla
$ python scripts/sync_couch_views.py dashboard
$ python scripts/ingest_provider.py profiles/clemson.pjs
License
--------
This application is released under a AGPLv3 license.
* Copyright Digital Public Library of America, 2012 -- 2017 |
using System;
using System.IO;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Events;
namespace chess.webapi
{
public class Program
{
public static IConfigurationRoot Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables()
.Build();
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration, "Serilog")
.CreateLogger();
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseConfiguration(Configuration)
.UseSerilog()
.UseStartup<Startup>();
}
} |
package com.employeemanagement.emsbackend.serviceImpl;
import com.employeemanagement.emsbackend.dto.EmployeeDto;
import com.employeemanagement.emsbackend.entity.Employee;
import com.employeemanagement.emsbackend.exception.ResourceNotFoundException;
import com.employeemanagement.emsbackend.mapper.EmployeeMapper;
import com.employeemanagement.emsbackend.repository.EmployeeRepository;
import com.employeemanagement.emsbackend.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class EmployeeServiceImpl implements EmployeeService {
private final EmployeeRepository employeeRepository;
@Autowired
public EmployeeServiceImpl(EmployeeRepository employeeRepository){
this.employeeRepository = employeeRepository;
}
@Override
public EmployeeDto createEmployee(EmployeeDto employeeDto) {
Employee employee = EmployeeMapper.mapToEmployee(employeeDto);
employeeRepository.save(employee);
return EmployeeMapper.mapToEmployeeDto(employee);
}
@Override
public EmployeeDto getEmployeeById(long empId){
Employee employee = employeeRepository.findById(empId)
.orElseThrow(() -> new ResourceNotFoundException(
"Employee is not existing with employee Id:: +" + empId
));
return EmployeeMapper.mapToEmployeeDto(employee);
}
@Override
public List<EmployeeDto> getAllEmployees() {
List<Employee> employeeList = employeeRepository.findAll();
return employeeList.stream().map((EmployeeMapper::mapToEmployeeDto)).toList();
}
@Override
public EmployeeDto updateEmployee(EmployeeDto employeeDto){
// get the employee by ID;
Employee employee = employeeRepository.findById(employeeDto.getId())
.orElseThrow(() -> new ResourceNotFoundException("Please check again as the employeeId provided is incorrect"));
// perform the update operation
Employee updatedEmp = setUpdated(employeeDto, employee);
return EmployeeMapper.mapToEmployeeDto(updatedEmp);
}
private Employee setUpdated(EmployeeDto employeeDto, Employee employee) {
employee.setEmail(employeeDto.getEmail());
employee.setFirstName(employeeDto.getFirstName());
employee.setLastName(employeeDto.getLastName());
employeeRepository.save(employee);
return employee;
}
} |
library(readxl)
library(dplyr)
library(MMWRweek)
library(tidyr)
library(ggplot2)
library(ggpubr)
library(lubridate)
library(R2jags)
load("R/parameters_linear_scen1.RData")
load("R/parameters_exp_scen1.RData")
# load("R/parameters_linear_scen2.RData")
# load("R/parameters_exp_scen2.RData")
# load("R/parameters_linear_scen3.RData")
# load("R/parameters_exp_scen3.RData")
seguiments <- read_xls("Data/3554569_DIAGNOSTICS.xls")
dades <- seguiments
dades$PR_DDE <- as.Date(dades$PR_DDE, format="%Y-%m-%d")
dades <- dades[dades$SEXE=="D", ]
### DATA PREPROCESSING
dades$Week <- MMWRweek(dades$PR_DDE)[, 2]
dades$Year <- as.numeric(substr(dades$PR_DDE, 1, 4))
dades$Month <- as.numeric(substr(dades$PR_DDE, 6, 7))
dades$cas <- 1
dades$AGE <- year(dades$PR_DDE)-year(dades$DAT_NAIX)
dades <- dades[dades$AGE >= 16, ] ### Only women 16 years old or older
### Only confirmed cases
dades <- dades[grepl("T74.", dades$PR_COD_PS), ]
data_ts_Week <- dades %>% group_by(BASE, Year, Week) %>% summarise(Cases=sum(cas))
data_ts_Week <- data_ts_Week %>% complete(Week=1:53, fill=list(Cases=0))
x_rec <- function(par, y, I, mode) ## par[1]=q0; par[2]=lambda; par[3]=beta; par[4]=alpha; par[5]=cp
{
n <- length(y)
x <- vector()
if (mode=="exp")
{
q <- c(rep(par[1], round(par[5])), 1-(1-par[1])*exp(-par[4]*seq(1, n-round(par[5]), 1))) #exponential
}else{
if (mode=="linear")
{
q <- c(rep(par[1], round(par[5])), par[1]+seq(1, round(par[4])-round(par[5]), 1)/((1/(1-par[1]))*(round(par[4])-round(par[5])))) #linear
}else{
stop("Wrong mode.")
}
}
for (i in 1:n)
{
prob_ant <- 0
prob <- dbinom(y[i], y[i], q[i])*dpois(y[i], par[2]+I[i]*par[3])
x[i] <- y[i]
r <- y[i]+1
while (r < 300 & prob > prob_ant)
{
prob_ant <- prob
prob <- dbinom(y[i], r, q[i])*dpois(r, par[2]+I[i]*par[3])
if (prob > prob_ant) x[i] <- r
r <- r+1
}
}
return(x)
}
### LINEAR q_t GROWTH (FIGURE SCALES SHOULD BE REVISED ACCORDING TO EACH SCENARIO)
### BASE 25
GBV_mcmc_25 <- as.mcmc(fit_GBV_25)
rec_25 <- x_rec(par=c(q0=summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="q0"],
lambda=summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="lambda"],
beta=summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="beta"],
alpha=summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="alpha"],
cp=summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="cp"]),
y=data_ts_Week[data_ts_Week$BASE==25, ]$Cases,
I=c(rep(0, 541), rep(1, 14), rep(0, 81)), mode="linear")
df1 <- data_ts_Week[data_ts_Week$BASE==25, ]
df1$date <- seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_25))
df2 <- data.frame(BASE=rep("25", length(rec_25)), Week=rep(seq(1:53), length(rec_25)/53), Cases=rec_25,
date=seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_25)),
Series=rep("Reconstructed", length(rec_25)))
df2$Year <- year(df2$date)
df2 <- df2[, c(1, 6, 2, 3, 4, 5)]
df1$Series <- "Registered"
df <- rbind(df1, df2)
p1 <- df %>%
ggplot(aes(x=date, y=Cases, col=Series)) + geom_line() + ylab("") +
ylim(0, 30)+scale_x_date(date_labels = "%m-%Y", date_breaks = "6 month")+
theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_text(angle=60, hjust=1), legend.position = "none") + xlab("") + ggtitle("SUBAREA A")
### BASE 26
GBV_mcmc_26 <- as.mcmc(fit_GBV_26)
rec_26 <- x_rec(par=c(q0=summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="q0"],
lambda=summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="lambda"],
beta=summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="beta"],
alpha=summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="alpha"],
cp=summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="cp"]),
y=data_ts_Week[data_ts_Week$BASE==26, ]$Cases,
I=c(rep(0, 541), rep(1, 14), rep(0, 81)), mode="linear")
df1 <- data_ts_Week[data_ts_Week$BASE==26, ]
df1$date <- seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_26))
df2 <- data.frame(BASE=rep("26", length(rec_26)), Week=rep(seq(1:53), length(rec_26)/53), Cases=rec_26,
date=seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_26)),
Series=rep("Reconstructed", length(rec_26)))
df2$Year <- year(df2$date)
df2 <- df2[, c(1, 6, 2, 3, 4, 5)]
df1$Series <- "Registered"
df <- rbind(df1, df2)
p2 <- df %>%
ggplot(aes(x=date, y=Cases, col=Series)) + geom_line() + ylab("") +
ylim(0, 30)+scale_x_date(date_labels = "%m-%Y", date_breaks = "6 month")+
theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_text(angle=60, hjust=1), legend.position = "none") + xlab("") + ggtitle("SUBAREA B")
### BASE 27
GBV_mcmc_27 <- as.mcmc(fit_GBV_27)
rec_27 <- x_rec(par=c(q0=summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="q0"],
lambda=summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="lambda"],
beta=summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="beta"],
alpha=summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="alpha"],
cp=summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="cp"]),
y=data_ts_Week[data_ts_Week$BASE==27, ]$Cases,
I=c(rep(0, 541), rep(1, 14), rep(0, 81)), mode="linear")
df1 <- data_ts_Week[data_ts_Week$BASE==27, ]
df1$date <- seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_27))
df2 <- data.frame(BASE=rep("27", length(rec_27)), Week=rep(seq(1:53), length(rec_27)/53), Cases=rec_27,
date=seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_27)),
Series=rep("Reconstructed", length(rec_27)))
df2$Year <- year(df2$date)
df2 <- df2[, c(1, 6, 2, 3, 4, 5)]
df1$Series <- "Registered"
df <- rbind(df1, df2)
p3 <- df %>%
ggplot(aes(x=date, y=Cases, col=Series)) + geom_line() + ylab("") +
ylim(0, 30)+scale_x_date(date_labels = "%m-%Y", date_breaks = "6 month")+
theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_text(angle=60, hjust=1), legend.position = "none") + xlab("") + ggtitle("SUBAREA C")
### BASE 31
GBV_mcmc_31 <- as.mcmc(fit_GBV_31)
rec_31 <- x_rec(par=c(q0=summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="q0"],
lambda=summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="lambda"],
beta=summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="beta"],
alpha=summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="alpha"],
cp=summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="cp"]),
y=data_ts_Week[data_ts_Week$BASE==31, ]$Cases,
I=c(rep(0, 541), rep(1, 14), rep(0, 81)), mode="linear")
df1 <- data_ts_Week[data_ts_Week$BASE==31, ]
df1$date <- seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_31))
df2 <- data.frame(BASE=rep("31", length(rec_31)), Week=rep(seq(1:53), length(rec_31)/53), Cases=rec_31,
date=seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_31)),
Series=rep("Reconstructed", length(rec_31)))
df2$Year <- year(df2$date)
df2 <- df2[, c(1, 6, 2, 3, 4, 5)]
df1$Series <- "Registered"
df <- rbind(df1, df2)
p4 <- df %>%
ggplot(aes(x=date, y=Cases, col=Series)) + geom_line() + ylab("") +
ylim(0, 55)+scale_x_date(date_labels = "%m-%Y", date_breaks = "6 month")+
theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_text(angle=60, hjust=1), legend.position = "none") + xlab("") + ggtitle("SUBAREA D")
### BASE 34
GBV_mcmc_34 <- as.mcmc(fit_GBV_34)
rec_34 <- x_rec(par=c(q0=summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="q0"],
lambda=summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="lambda"],
beta=summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="beta"],
alpha=summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="alpha"],
cp=summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="cp"]),
y=data_ts_Week[data_ts_Week$BASE==34, ]$Cases,
I=c(rep(0, 541), rep(1, 14), rep(0, 81)), mode="linear")
df1 <- data_ts_Week[data_ts_Week$BASE==34, ]
df1$date <- seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_34))
df2 <- data.frame(BASE=rep("34", length(rec_34)), Week=rep(seq(1:53), length(rec_34)/53), Cases=rec_34,
date=seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_34)),
Series=rep("Reconstructed", length(rec_34)))
df2$Year <- year(df2$date)
df2 <- df2[, c(1, 6, 2, 3, 4, 5)]
df1$Series <- "Registered"
df <- rbind(df1, df2)
p5 <- df %>%
ggplot(aes(x=date, y=Cases, col=Series)) + geom_line() + ylab("") +
ylim(0, 15)+scale_x_date(date_labels = "%m-%Y", date_breaks = "6 month")+
theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_text(angle=60, hjust=1), legend.position = "none") + xlab("") + ggtitle("SUBAREA E")
### BASE 35
GBV_mcmc_35 <- as.mcmc(fit_GBV_35)
rec_35 <- x_rec(par=c(q0=summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="q0"],
lambda=summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="lambda"],
beta=summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="beta"],
alpha=summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="alpha"],
cp=summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="cp"]),
y=data_ts_Week[data_ts_Week$BASE==35, ]$Cases,
I=c(rep(0, 541), rep(1, 14), rep(0, 81)), mode="linear")
df1 <- data_ts_Week[data_ts_Week$BASE==35, ]
df1$date <- seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_35))
df2 <- data.frame(BASE=rep("35", length(rec_35)), Week=rep(seq(1:53), length(rec_35)/53), Cases=rec_35,
date=seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_35)),
Series=rep("Reconstructed", length(rec_35)))
df2$Year <- year(df2$date)
df2 <- df2[, c(1, 6, 2, 3, 4, 5)]
df1$Series <- "Registered"
df <- rbind(df1, df2)
p6 <- df %>%
ggplot(aes(x=date, y=Cases, col=Series)) + geom_line() + ylab("") +
ylim(0, 55)+scale_x_date(date_labels = "%m-%Y", date_breaks = "6 month")+
theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_text(angle=60, hjust=1), legend.position = "none") + xlab("") + ggtitle("SUBAREA F")
ggarrange(p1, p2, p3, p4, p5, p6,
ncol = 3, nrow = 2)
### EXPONENTIAL q_t GROWTH
### BASE 25
GBV_mcmc_25 <- as.mcmc(fit_GBV_25_exp)
rec_25 <- x_rec(par=c(q0=summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="q0"],
lambda=summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="lambda"],
beta=summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="beta"],
alpha=summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="alpha"],
cp=summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="cp"]),
y=data_ts_Week[data_ts_Week$BASE==25, ]$Cases,
I=c(rep(0, 541), rep(1, 14), rep(0, 81)), mode="exp")
p25 <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==25])/sum(rec_25)*100, 2)
p25_before <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==25]
[1:round(summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="cp"])])/
sum(rec_25[1:round(summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="cp"])])*100, 2)
p25_after <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==25]
[(round(summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="cp"])+1):length(rec_25)])/
sum(rec_25[(round(summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="cp"])+1):length(rec_25)])*100, 2)
df1 <- data_ts_Week[data_ts_Week$BASE==25, ]
df1$date <- seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_25))
df2 <- data.frame(BASE=rep("25", length(rec_25)), Week=rep(seq(1:53), length(rec_25)/53), Cases=rec_25,
date=seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_25)),
Series=rep("Reconstructed", length(rec_25)))
df2$Year <- year(df2$date)
df2 <- df2[, c(1, 6, 2, 3, 4, 5)]
df1$Series <- "Registered"
df <- rbind(df1, df2)
p1 <- df %>%
ggplot(aes(x=date, y=Cases, col=Series)) + geom_line() + ylab("") +
ylim(0, 30)+scale_x_date(date_labels = "%m-%Y", date_breaks = "6 month")+
theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_text(angle=60, hjust=1), legend.position = "none") + xlab("") + ggtitle("SUBAREA A")+
geom_vline(xintercept=df$date[round(summary(GBV_mcmc_25)$quantiles[,3][rownames(summary(GBV_mcmc_25)$quantiles)=="cp"])], linetype=1, color="black", linewidth=1) +
geom_vline(xintercept=df$date[df$date=="2020-03-13"], linetype=1, color="red", linewidth=1)+
geom_vline(xintercept=df$date[df$date=="2020-06-26"], linetype=1, color="red", linewidth=1)+
annotate("rect", xmin = df$date[df$date=="2020-03-13"], xmax = df$date[df$date=="2020-06-26"], ymin = -Inf, ymax = Inf,
alpha = .2)
### BASE 26
GBV_mcmc_26 <- as.mcmc(fit_GBV_26_exp)
rec_26 <- x_rec(par=c(q0=summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="q0"],
lambda=summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="lambda"],
beta=summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="beta"],
alpha=summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="alpha"],
cp=summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="cp"]),
y=data_ts_Week[data_ts_Week$BASE==26, ]$Cases,
I=c(rep(0, 541), rep(1, 14), rep(0, 81)), mode="exp")
p26 <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==26])/sum(rec_26)*100, 2)
p26_before <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==26]
[1:round(summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="cp"])])/
sum(rec_26[1:round(summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="cp"])])*100, 2)
p26_after <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==26]
[(round(summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="cp"])+1):length(rec_26)])/
sum(rec_26[(round(summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="cp"])+1):length(rec_26)])*100, 2)
df1 <- data_ts_Week[data_ts_Week$BASE==26, ]
df1$date <- seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_26))
df2 <- data.frame(BASE=rep("26", length(rec_26)), Week=rep(seq(1:53), length(rec_26)/53), Cases=rec_26,
date=seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_26)),
Series=rep("Reconstructed", length(rec_26)))
df2$Year <- year(df2$date)
df2 <- df2[, c(1, 6, 2, 3, 4, 5)]
df1$Series <- "Registered"
df <- rbind(df1, df2)
p2 <- df %>%
ggplot(aes(x=date, y=Cases, col=Series)) + geom_line() + ylab("") +
ylim(0, 30)+scale_x_date(date_labels = "%m-%Y", date_breaks = "6 month")+
theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_text(angle=60, hjust=1), legend.position = "none") + xlab("") + ggtitle("SUBAREA B")+
geom_vline(xintercept=df$date[round(summary(GBV_mcmc_26)$quantiles[,3][rownames(summary(GBV_mcmc_26)$quantiles)=="cp"])], linetype=1, color="black", linewidth=1) +
geom_vline(xintercept=df$date[df$date=="2020-03-13"], linetype=1, color="red", linewidth=1)+
geom_vline(xintercept=df$date[df$date=="2020-06-26"], linetype=1, color="red", linewidth=1)+
annotate("rect", xmin = df$date[df$date=="2020-03-13"], xmax = df$date[df$date=="2020-06-26"], ymin = -Inf, ymax = Inf,
alpha = .2)
### BASE 27
GBV_mcmc_27 <- as.mcmc(fit_GBV_27_exp)
rec_27 <- x_rec(par=c(q0=summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="q0"],
lambda=summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="lambda"],
beta=summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="beta"],
alpha=summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="alpha"],
cp=summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="cp"]),
y=data_ts_Week[data_ts_Week$BASE==27, ]$Cases,
I=c(rep(0, 541), rep(1, 14), rep(0, 81)), mode="exp")
p27 <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==27])/sum(rec_27)*100, 2)
p27_before <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==27]
[1:round(summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="cp"])])/
sum(rec_27[1:round(summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="cp"])])*100, 2)
p27_after <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==27]
[(round(summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="cp"])+1):length(rec_27)])/
sum(rec_27[(round(summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="cp"])+1):length(rec_27)])*100, 2)
df1 <- data_ts_Week[data_ts_Week$BASE==27, ]
df1$date <- seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_27))
df2 <- data.frame(BASE=rep("27", length(rec_27)), Week=rep(seq(1:53), length(rec_27)/53), Cases=rec_27,
date=seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_27)),
Series=rep("Reconstructed", length(rec_27)))
df2$Year <- year(df2$date)
df2 <- df2[, c(1, 6, 2, 3, 4, 5)]
df1$Series <- "Registered"
df <- rbind(df1, df2)
p3 <- df %>%
ggplot(aes(x=date, y=Cases, col=Series)) + geom_line() + ylab("") +
ylim(0, 30)+scale_x_date(date_labels = "%m-%Y", date_breaks = "6 month")+
theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_text(angle=60, hjust=1), legend.position = "none") + xlab("") + ggtitle("SUBAREA C")+
geom_vline(xintercept=df$date[round(summary(GBV_mcmc_27)$quantiles[,3][rownames(summary(GBV_mcmc_27)$quantiles)=="cp"])], linetype=1, color="black", linewidth=1) +
geom_vline(xintercept=df$date[df$date=="2020-03-13"], linetype=1, color="red", linewidth=1)+
geom_vline(xintercept=df$date[df$date=="2020-06-26"], linetype=1, color="red", linewidth=1)+
annotate("rect", xmin = df$date[df$date=="2020-03-13"], xmax = df$date[df$date=="2020-06-26"], ymin = -Inf, ymax = Inf,
alpha = .2)
### BASE 31
GBV_mcmc_31 <- as.mcmc(fit_GBV_31_exp)
rec_31 <- x_rec(par=c(q0=summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="q0"],
lambda=summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="lambda"],
beta=summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="beta"],
alpha=summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="alpha"],
cp=summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="cp"]),
y=data_ts_Week[data_ts_Week$BASE==31, ]$Cases,
I=c(rep(0, 541), rep(1, 14), rep(0, 81)), mode="exp")
p31 <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==31])/sum(rec_31)*100, 2)
p31_before <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==31]
[1:round(summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="cp"])])/
sum(rec_31[1:round(summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="cp"])])*100, 2)
p31_after <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==31]
[(round(summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="cp"])+1):length(rec_31)])/
sum(rec_31[(round(summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="cp"])+1):length(rec_31)])*100, 2)
df1 <- data_ts_Week[data_ts_Week$BASE==31, ]
df1$date <- seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_31))
df2 <- data.frame(BASE=rep("31", length(rec_31)), Week=rep(seq(1:53), length(rec_31)/53), Cases=rec_31,
date=seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_31)),
Series=rep("Reconstructed", length(rec_31)))
df2$Year <- year(df2$date)
df2 <- df2[, c(1, 6, 2, 3, 4, 5)]
df1$Series <- "Registered"
df <- rbind(df1, df2)
p4 <- df %>%
ggplot(aes(x=date, y=Cases, col=Series)) + geom_line() + ylab("") +
ylim(0, 50)+scale_x_date(date_labels = "%m-%Y", date_breaks = "6 month")+
theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_text(angle=60, hjust=1), legend.position = "none") + xlab("") + ggtitle("SUBAREA D")+
geom_vline(xintercept=df$date[round(summary(GBV_mcmc_31)$quantiles[,3][rownames(summary(GBV_mcmc_31)$quantiles)=="cp"])], linetype=1, color="black", linewidth=1) +
geom_vline(xintercept=df$date[df$date=="2020-03-13"], linetype=1, color="red", linewidth=1)+
geom_vline(xintercept=df$date[df$date=="2020-06-26"], linetype=1, color="red", linewidth=1)+
annotate("rect", xmin = df$date[df$date=="2020-03-13"], xmax = df$date[df$date=="2020-06-26"], ymin = -Inf, ymax = Inf,
alpha = .2)
### BASE 34
GBV_mcmc_34 <- as.mcmc(fit_GBV_34_exp)
rec_34 <- x_rec(par=c(q0=summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="q0"],
lambda=summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="lambda"],
beta=summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="beta"],
alpha=summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="alpha"],
cp=summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="cp"]),
y=data_ts_Week[data_ts_Week$BASE==34, ]$Cases,
I=c(rep(0, 541), rep(1, 14), rep(0, 81)), mode="exp")
p34 <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==34])/sum(rec_34)*100, 2)
p34_before <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==34]
[1:round(summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="cp"])])/
sum(rec_34[1:round(summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="cp"])])*100, 2)
p34_after <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==34]
[(round(summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="cp"])+1):length(rec_34)])/
sum(rec_34[(round(summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="cp"])+1):length(rec_34)])*100, 2)
df1 <- data_ts_Week[data_ts_Week$BASE==34, ]
df1$date <- seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_34))
df2 <- data.frame(BASE=rep("34", length(rec_34)), Week=rep(seq(1:53), length(rec_34)/53), Cases=rec_34,
date=seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_34)),
Series=rep("Reconstructed", length(rec_34)))
df2$Year <- year(df2$date)
df2 <- df2[, c(1, 6, 2, 3, 4, 5)]
df1$Series <- "Registered"
df <- rbind(df1, df2)
p5 <- df %>%
ggplot(aes(x=date, y=Cases, col=Series)) + geom_line() + ylab("") +
ylim(0, 15)+scale_x_date(date_labels = "%m-%Y", date_breaks = "6 month")+
theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_text(angle=60, hjust=1), legend.position = "none") + xlab("") + ggtitle("SUBAREA E")+
geom_vline(xintercept=df$date[round(summary(GBV_mcmc_34)$quantiles[,3][rownames(summary(GBV_mcmc_34)$quantiles)=="cp"])], linetype=1, color="black", linewidth=1) +
geom_vline(xintercept=df$date[df$date=="2020-03-13"], linetype=1, color="red", linewidth=1)+
geom_vline(xintercept=df$date[df$date=="2020-06-26"], linetype=1, color="red", linewidth=1)+
annotate("rect", xmin = df$date[df$date=="2020-03-13"], xmax = df$date[df$date=="2020-06-26"], ymin = -Inf, ymax = Inf,
alpha = .2)
### BASE 35
GBV_mcmc_35 <- as.mcmc(fit_GBV_35_exp)
rec_35 <- x_rec(par=c(q0=summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="q0"],
lambda=summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="lambda"],
beta=summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="beta"],
alpha=summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="alpha"],
cp=summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="cp"]),
y=data_ts_Week[data_ts_Week$BASE==35, ]$Cases,
I=c(rep(0, 541), rep(1, 14), rep(0, 81)), mode="exp")
p35 <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==35])/sum(rec_35)*100, 2)
p35_before <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==35]
[1:round(summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="cp"])])/
sum(rec_35[1:round(summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="cp"])])*100, 2)
p35_after <- round(sum(data_ts_Week$Cases[data_ts_Week$BASE==35]
[(round(summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="cp"])+1):length(rec_35)])/
sum(rec_35[(round(summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="cp"])+1):length(rec_35)])*100, 2)
df1 <- data_ts_Week[data_ts_Week$BASE==35, ]
df1$date <- seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_35))
df2 <- data.frame(BASE=rep("35", length(rec_35)), Week=rep(seq(1:53), length(rec_35)/53), Cases=rec_35,
date=seq.Date(from=as.Date("2010-01-01", format="%Y-%m-%d"), by="week", length.out=length(rec_35)),
Series=rep("Reconstructed", length(rec_35)))
df2$Year <- year(df2$date)
df2 <- df2[, c(1, 6, 2, 3, 4, 5)]
df1$Series <- "Registered"
df <- rbind(df1, df2)
p6 <- df %>%
ggplot(aes(x=date, y=Cases, col=Series)) + geom_line() + ylab("") +
ylim(0, 50)+scale_x_date(date_labels = "%m-%Y", date_breaks = "6 month")+
theme(plot.title = element_text(hjust = 0.5), axis.text.x=element_text(angle=60, hjust=1), legend.position = "none") + xlab("") + ggtitle("SUBAREA F")+
geom_vline(xintercept=df$date[round(summary(GBV_mcmc_35)$quantiles[,3][rownames(summary(GBV_mcmc_35)$quantiles)=="cp"])], linetype=1, color="black", linewidth=1) +
geom_vline(xintercept=df$date[df$date=="2020-03-13"], linetype=1, color="red", linewidth=1)+
geom_vline(xintercept=df$date[df$date=="2020-06-26"], linetype=1, color="red", linewidth=1)+
annotate("rect", xmin = df$date[df$date=="2020-03-13"], xmax = df$date[df$date=="2020-06-26"], ymin = -Inf, ymax = Inf,
alpha = .2)
ggarrange(p1, p2, p3, p4, p5, p6,
ncol = 3, nrow = 2)
### Percentage of registered cases by subarea
data_plot <- data.frame(Subarea=c("A", "B", "C", "D", "E", "F"),
Value=c(p25, p26, p27, p31, p34, p35),
Before=c(p25_before, p26_before, p27_before,
p31_before, p34_before, p35_before),
After=c(p25_after, p26_after, p27_after,
p31_after, p34_after, p35_after))
data_plot %>% ggplot(aes(x=Subarea, y=Value)) + ylim(c(0, 100)) +
geom_point()+geom_ribbon(aes(1:nrow(data_plot),ymax=After,ymin=Before),alpha=0.1) +
xlab("Subarea")+ylab("Percentage of reported cases") + scale_x_discrete(labels=data_plot$Subarea) +
theme(axis.text.x = element_text(angle = 25)) |
# Additional data collection
#' getRaceWeather
#'
#' @description given a race url from ergast (to wikipedia) get the weather
#'
#' @param race_url a wikipedia url for a grand prix (in english)
#'
#' @return a weather, as character (one of `warm`, `cold`, `dry`, `wet`, or `cloudy`)
#'
#' @examples
#' f1model:::getWeather("https://en.wikipedia.org/wiki/2021_Austrian_Grand_Prix")
getWeather <- function(race_url) {
stopifnot(grepl("wikipedia", race_url))
race_weather <- NULL
tryCatch(
{
race_tables <- rvest::html_table(rvest::read_html(race_url))
for (table in race_tables) {
if ("Weather" %in% (table[, 1] %>% dplyr::pull(1))) {
rw <- which((table[, 1] %>% dplyr::pull(1)) == "Weather")
race_weather <- table[rw, 2] %>% dplyr::pull(1)
break
}
}
},
error = function(e) {
message(glue::glue("Error in f1model:::getWeather: {url} - {err}",
url = race_url, err = e
))
}
)
if (is.null(race_weather)) {
# Try the italian site - it's apparently more robust
logger::log_info(glue::glue("f1model:::getWeather: Trying to get weather from Italian Wikipedia instead of {url}",
url = race_url
))
it_url <- grep(
pattern = "https:\\/\\/it.wikipedia.org\\/wiki\\/[a-zA-Z0-9_%]*",
x = RCurl::getURLContent(race_url,
.opts = list(ssl.verifypeer = FALSE)
),
value = TRUE
)
tryCatch(
{
it_race_table <- rvest::html_table(rvest::read_html(race_url))
for (table in race_tables) {
if ("Clima" %in% (table[, 1] %>% dplyr::pull(1))) {
rw <- which((table[, 1] %>% dplyr::pull(1)) == "Clima")
race_weather <- table[rw, 2] %>% dplyr::pull(1)
break
}
}
},
error = function(e) {
message(glue::glue("Error in f1model:::getWeather: {url} - {err}",
url = race_url, err = e
))
}
)
}
# Bin weather to few option or show the value and mark unknown
if (is.null(race_weather)) {
logger::log_info("f1model:::getWeather: Race Weather not found")
race_weather <- "unknown"
} else if (grepl("showers|wet|rain|pioggia|damp|thunderstorms|rainy", race_weather, ignore.case = T)) {
race_weather <- "wet"
} else if (grepl("cloudy|grey|coperto|clouds|nuvoloso|overcast", race_weather, ignore.case = T)) {
race_weather <- "cloudy"
} else if (grepl("dry|asciutto", race_weather, ignore.case = T)) {
race_weather <- "dry"
} else if (grepl("cold|fresh|chilly|cool", race_weather, ignore.case = T)) {
race_weather <- "cold"
} else if (grepl("soleggiato|clear|warm|hot|sunny|fine|mild|sereno", race_weather, ignore.case = T)) {
race_weather <- "warm"
} else {
logger::log_info(glue::glue("f1model:::getWeather: Race Weather of {race_weather} is unknown type. From {url}",
race_weather = race_weather, url = race_url
))
race_weather <- "unknown"
}
return(race_weather)
}
getPracticeTimes <- function(f1RaceId, year, practiceNum) {
practice_url <- glue::glue("https://www.formula1.com/en/results.html/{year}/races/{id}/practice-{num}.html",
year = year, id = f1RaceId, num = practiceNum
)
practice_table <- NA
tryCatch(
{
practice_table <- rvest::html_table(rvest::read_html(practice_url))[[1]]
if ("PTS" %in% colnames(practice_table)) {
# There was no practice practiceNum, so f1 defaults back to race results
stop(glue::glue("There seems to be no practice {num}, {url} returns race results.",
num = practiceNum, url = practice_url
))
} else if ("Grand Prix" %in% colnames(practice_table)) {
# There was likely an issue with the f1RaceId value
stop(glue::glue("There seems to be no race Id {raceid}, {url} returns season results for {year}.",
raceid = f1RaceId, url = practice_url, year = year
))
} else if (nrow(practice_table) > 0) {
# hopefully all ok?
practice_table <- practice_table %>%
dplyr::select(c("Pos", "No", "Driver", "Car", "Time", "Gap", "Laps"))
# reformat driver name/code field
practice_table$Driver <- gsub("\\n", "", practice_table$Driver)
practice_table$Driver <- gsub("\\s+", " ", practice_table$Driver)
colnames(practice_table) <- c(
"position", "driverNum", "driverName",
"driverCar", "time", "gap", "laps"
)
# split driver code from name
practice_table$driverCode <- substr(x = practice_table$driverName, nchar(practice_table$driverName) - 2, nchar(practice_table$driverName))
practice_table$driverName <- substr(x = practice_table$driverName, 0, nchar(practice_table$driverName) - 4)
practice_table$practiceNum <- practiceNum
practice_table$time <- as.character(practice_table$time)
} else {
practice_table <- NA
}
},
error = function(e) {
# message(glue::glue("Error in f1model:::getPracticeTimes: {err}", err=e))
practice_table <- NA
}
)
return(practice_table)
}
getQualiTimes <- function(f1RaceId, year) {
quali_url <- glue::glue("https://www.formula1.com/en/results.html/{year}/races/{id}/qualifying-0.html",
year = year, id = f1RaceId
)
quali_table <- NA
tryCatch(
{
quali_table <- rvest::html_table(rvest::read_html(quali_url))[[1]]
if ("PTS" %in% colnames(quali_table)) {
# There was no practice practiceNum, so f1 defaults back to race results
stop(glue::glue("There seems to be no quali, {url} returns race results.",
url = quali_url
))
} else if ("Grand Prix" %in% colnames(quali_table)) {
# There was likely an issue with the f1RaceId value
stop(glue::glue("There seems to be no race Id {raceid}, {url} returns season results for {year}.",
raceid = f1RaceId, url = quali_url, year = year
))
} else if (nrow(quali_table) > 0) {
# hopefully all ok?
if ("Time" %in% colnames(quali_table)) {
# quali 1 round only has 'Time' as column name (< 2006?)
quali_table <- quali_table %>%
dplyr::select(c("Pos", "No", "Driver", "Car", "Time"))
colnames(quali_table) <- c("position", "driverNum", "driverName", "driverCar", "q1")
quali_table$q2 <- quali_table$q3 <- NA_character_
} else {
quali_table <- quali_table %>%
dplyr::select(c("Pos", "No", "Driver", "Car", "Q1", "Q2", "Q3")) %>%
dplyr::mutate(
"Q1" = dplyr::if_else(.data$Q1 == "", NA_character_, .data$Q1),
"Q2" = dplyr::if_else(.data$Q2 == "", NA_character_, .data$Q2),
"Q3" = dplyr::if_else(.data$Q3 == "", NA_character_, .data$Q3)
)
colnames(quali_table) <- c("position", "driverNum", "driverName", "driverCar", "q1", "q2", "q3")
}
# split driver code from name
quali_table$driverCode <- substr(x = quali_table$driverName, nchar(quali_table$driverName) - 2, nchar(quali_table$driverName))
# reformat driver name field
quali_table$driverName <- gsub("\\n", "", quali_table$driverName)
quali_table$driverName <- gsub("\\s+", " ", quali_table$driverName)
quali_table$q1 <- as.character(quali_table$q1)
quali_table$q2 <- as.character(quali_table$q2)
quali_table$q3 <- as.character(quali_table$q3)
quali_table$position <- as.character(quali_table$position)
} else {
quali_table <- NA
}
},
error = function(e) {
# message(glue::glue("Error in f1model:::getPracticeTimes: {err}", err=e))
quali_table <- NA
}
)
return(quali_table)
}
getRacePractices <- function(raceId) {
# inherently, we're not getting data for races with NA as f1RaceId
rs <- f1model::races[!is.na(f1model::races$f1RaceId), ]
stopifnot(!is.na(rs[rs$raceId == raceId, ]$f1RaceId))
# get practices
practice_data <- data.frame(
"position" = integer(),
"driverNum" = integer(),
"driverName" = character(),
"driverCode" = character(),
"driverCar" = character(),
"time" = character(),
"gap" = character(),
"laps" = integer(),
"practiceNum" = integer()
)
for (i in 1:4) {
pd <- NA
pd <- try(getPracticeTimes(
rs[rs$raceId == raceId, ]$f1RaceId,
rs[rs$raceId == raceId, ]$year, i
))
if (length(pd) > 1 & !("PTS" %in% colnames(pd)) & !("Q1" %in% colnames(pd)) & !("Grand Prix" %in% colnames(pd))) {
practice_data <- dplyr::bind_rows(practice_data, pd)
}
Sys.sleep(5)
}
if (nrow(practice_data) == 0) {
practice_data$f1RaceId <- character()
practice_data$raceId <- practice_data$year <- practice_data$round <- integer()
practice_data$driverId <- practice_data$constructorId <- integer()
return(practice_data)
}
practice_data$raceId <- raceId
practice_data$f1RaceId <- rs[rs$raceId == raceId, ]$f1RaceId
practice_data$year <- rs[rs$raceId == raceId, ]$year
practice_data$round <- rs[rs$raceId == raceId, ]$round
return(assignDriverConstructor(practice_data, raceId))
}
getQualifying <- function(raceId) {
# inherently, we're not getting data for races with NA as f1RaceId
rs <- f1model::races[!is.na(f1model::races$f1RaceId), ]
stopifnot(!is.na(rs[rs$raceId == raceId, ]$f1RaceId))
# get qualifying
quali_data <- getQualiTimes(
rs[rs$raceId == raceId, ]$f1RaceId,
rs[rs$raceId == raceId, ]$year
)
if (nrow(quali_data) == 0) {
quali_data <- data.frame(
"qualifyId" = integer(),
"raceId" = integer(),
"driverId" = integer(),
"constructorId" = integer(),
"number" = integer(),
"position" = character(),
"q1" = character(),
"q2" = character(),
"q3" = character()
)
logger::log_info(glue::glue("Race Id: {raceId} returned empty qualifying data.", raceId = raceId))
return(NA)
}
quali_data$raceId <- raceId
quali_data <- assignDriverConstructor(quali_data, raceId) %>%
dplyr::select(c("raceId", "driverId", "constructorId", "driverNum", "position", "q1", "q2", "q3")) %>%
dplyr::rename("number" = "driverNum") %>%
dplyr::mutate("qualifyId" = NA_integer_)
Sys.sleep(5)
return(quali_data)
}
assignDriverConstructor <- function(data, raceId) {
# add driver/constructor lookups
driverConstructor <- f1model::results[
f1model::results$raceId == raceId,
c("driverId", "constructorId")
]
data$driverId <- NA
data$constructorId <- NA
drvrs <- f1model::drivers
drvrs$fullname <- paste(drvrs$forename, drvrs$surname)
for (i in 1:nrow(data)) {
if ("driverCode" %in% colnames(data)) {
code <- data[i, ]$driverCode
if (code == "RSC") {
code <- "SCH"
} else if (code == "MOY") {
code <- "MON"
} else if (code == "CHD") {
code <- "CHA"
} else if (code == "RSI") {
code <- "RSS"
}
if (code == "ALB") {
logger::log_debug("Separating ALB")
driverId <- ifelse(data[i, ]$driverName == "Alexander Albon", 848, 27)
} else if (code == "MSC") {
logger::log_debug("Separating MSC")
driverId <- ifelse(data[i, ]$driverName == "Michael Schumacher", 30, 854)
} else if (code == "HAR") {
logger::log_debug("Separating HAR")
driverId <- ifelse(data[i, ]$driverName == "Brendon Hartley", 843, 837)
} else if (code == "BIA") {
logger::log_debug("Separating BIA")
driverId <- ifelse(data[i, ]$driverName == "Jules Bianchi", 824, 376)
} else if (code == "MAG") {
logger::log_debug("Separating MAG")
driverId <- ifelse(data[i, ]$driverName == "Kevin Magnussen", 825, 76)
} else if (code == "VER") {
logger::log_debug("Separating VER")
driverId <- ifelse(data[i, ]$driverName == "Max Verstappen", 830, 818)
} else if (code == "PAN") {
logger::log_debug("Separating PAN")
driverId <- ifelse(data[i, ]$driverName == "Olivier Panis", 44, 45)
} else {
driverId <- f1model::drivers[f1model::drivers$code == code, ]$driverId
}
} else if ("driverName" %in% colnames(data)) {
name <- data[i, ]$driverName
if (name %in% drvrs$fullname) {
driverId <- drvrs[drvrs$fullname == name, ]$driverId
} else {
logger::log_info("No Driver Match for {name} in race {race}.",
name = name, race = raceId
)
}
}
if (length(driverId) != 0) {
data[i, ]$driverId <- driverId
constructorId <- driverConstructor[driverConstructor$driverId == driverId, ]$constructorId
if (length(constructorId) > 0) {
data[i, ]$constructorId <- constructorId
next
}
} else {
logger::log_info(glue::glue("Driver {driver} not found: {drivername}",
driver = code,
drivername = data[i, ]$driverName
))
next
}
if (length(constructorId) == 0) {
const <- data[i, ]$driverCar
data[i, ]$constructorId <- dplyr::case_when(
grepl("^ferrari", const, ignore.case = T) ~ 6,
grepl("^mclaren", const, ignore.case = T) ~ 1,
grepl("BAR", const, fixed = T, ignore.case = F) ~ 16,
const == "Sauber BMW" ~ 2,
grepl("^sauber*", const, ignore.case = T) ~ 15,
grepl("jordan", const, ignore.case = T) ~ 17,
grepl("benetton", const, ignore.case = T) ~ 22,
grepl("jaguar *", const, ignore.case = T) ~ 19,
grepl("minardi", const, ignore.case = T) ~ 18,
grepl("arrows", const, ignore.case = T) ~ 21,
grepl("^williams*", const, ignore.case = T) ~ 3,
grepl("prost", const, ignore.case = T) ~ 20,
grepl("^renault", const, ignore.case = T) ~ 4,
grepl("^red bull", const, ignore.case = T) ~ 9,
grepl("rbr *", const, ignore.case = T) ~ 9,
grepl("haas", const, ignore.case = T) ~ 210,
grepl("^alfa romeo", const, ignore.case = T) ~ 51,
grepl("alphatauri*", const, ignore.case = T) ~ 213,
grepl("alpine", const, ignore.case = T) ~ 214,
grepl("^mercedes", const, ignore.case = T) ~ 131,
grepl("^aston martin", const, ignore.case = T) ~ 117,
grepl("torro rosso", const, ignore.case = T) ~ 5,
grepl("toro rosso", const, ignore.case = T) ~ 5,
grepl("stryker", const, ignore.case = T) ~ 14,
grepl("^str *", const, ignore.case = T) ~ 5,
grepl("force india", const, ignore.case = T) ~ 10,
grepl("mf1 *", const, ignore.case = T) ~ 13,
grepl("^honda *", const, ignore.case = T) ~ 11,
grepl("^toyota*", const, ignore.case = T) ~ 7,
grepl("aguri", const, ignore.case = T) ~ 8,
grepl("^hrt *", const, ignore.case = T) ~ 164,
grepl("^virgin *", const, ignore.case = T) ~ 166,
grepl("caterham *", const, ignore.case = T) ~ 207,
grepl("marussia *", const, ignore.case = T) ~ 206,
grepl("lotus mercedes", const, ignore.case = T) ~ 208,
grepl("lotus renault", const, ignore.case = T) ~ 208,
TRUE ~ NA_real_
)
if (is.na(data[i, ]$constructorId)) {
logger::log_info(glue::glue("Found Unknown driverCar: {car} for Driver {driver} in raceId: {race}",
car = const, driver = data[i, ]$driverCode,
race = raceId
))
}
}
}
return(data)
}
#' Combine Data
#'
#' @description merge all of the data frames into one big one for use in modelling. EWMA parameters provided
#' help with determining the strength of the exponential weighted moving average for those parameters.
#'
#' @param driverCrashEWMA How much one race impacts driver's moving average of crash rate
#' @param carFailureEWMA How much one race impacts constructor's moving average of failure rate
#' @param tireFailureEWMA How much one race impacts driver's moving average of tire failure rate
#' @param disqualifiedEWMA How much one race impacts driver's moving average of disqualified rate
#' @param gridPositionCorEWMA How much one race impacts driver's moving average of crash rate
#' @param pitPercEWMA How much one race impacts a driver's moving average of pit rate
#'
#' @return a tibble with tons of data
.combineData <- function(driverCrashEWMA = 0.05, carFailureEWMA = 0.05, tireFailureEWMA = 0.05,
disqualifiedEWMA = 0.05, gridPositionCorEWMA = 0.2, pitPercEWMA = 0.1) {
# This function combines the data from the saved data sets to one
# useful data frame for modelling. It also includes reprocessing
# steps.
# -------- Drivers ----------------------------------
logger::log_info("Manipulating Drivers data")
drivers <- f1model::drivers %>%
dplyr::mutate("driverName" = paste(.data$forename, .data$surname)) %>%
dplyr::select(c("driverId", "code", "driverName", "dob", "nationality")) %>%
dplyr::rename("driverCode" = "code", "driverDOB" = "dob", "driverNationality" = "nationality")
# -------- Driver Standings -------------------------
logger::log_info("Manipulating Drivers Standings data")
driver_standings <- f1model::driver_standings %>%
dplyr::select(c("raceId", "driverId", "points", "wins")) %>%
dplyr::rename("driverSeasonWins" = "wins", "driverPoints" = "points")
# -------- Constructors -----------------------------
logger::log_info("Manipulating Constructors data")
constructors <- f1model::constructors %>%
dplyr::mutate("currentConstructorId" = updateConstructor(.data$constructorId)) %>%
dplyr::select(c("constructorId", "name", "nationality", "currentConstructorId")) %>%
dplyr::rename(c("constructorName" = "name", "constructorNationality" = "nationality"))
# -------- Constructor Standings --------------------
logger::log_info("Manipulating Constructors Standings data")
constructor_standings <- f1model::constructor_standings %>%
dplyr::select(c("raceId", "constructorId", "points", "wins")) %>%
dplyr::rename("constructorSeasonWins" = "wins", "constructorPoints" = "points")
# -------- Practices --------------------------------
logger::log_info("Manipulating Practice data")
practices <- f1model::practices %>%
dplyr::mutate(
"practiceTimeSec" = timeToSec(.data$time),
"practiceGapSec" = timeToSec(.data$gap)
) %>%
dplyr::group_by(.data$raceId, .data$practiceNum) %>%
dplyr::mutate("practiceTimePerc" = .data$practiceTimeSec / min(.data$practiceTimeSec)) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$raceId, .data$driverId) %>%
dplyr::mutate(
"driverPracticeAvgSec" = mean(.data$practiceTimeSec, na.rm = T),
"driverPracticeBestPerc" = min(.data$practiceTimePerc, na.rm = T),
"driverPracticeAvgPerc" = mean(.data$practiceTimePerc, na.rm = T),
"driverNumPracticeLaps" = sum(.data$laps, na.rm = T),
"driverAvgPracticePos" = mean(.data$position, na.rm = T)
) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$raceId, .data$practiceNum, .data$constructorId) %>%
dplyr::mutate(
"constructorPracticeAvgSec" = mean(.data$practiceTimeSec, na.rm = T),
"constructorPracticeAvgPerc" = mean(.data$practiceTimePerc, na.rm = T),
"constructorPracticeBestPerc" = min(.data$practiceTimePerc, na.rm = T)
) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$raceId, .data$constructorId) %>%
dplyr::mutate("constructorNumPracticeLaps" = sum(.data$laps, na.rm = T)) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$raceId, .data$practiceNum) %>%
dplyr::mutate(
"driverTeamPracticeGapSec" = .data$practiceTimeSec - .data$constructorPracticeAvgSec,
"driverTeamPracticeGapPerc" = .data$practiceTimeSec / .data$constructorPracticeAvgSec
) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$raceId) %>%
dplyr::mutate(
"maxDriverPracticeLaps" = max(.data$driverNumPracticeLaps, na.rm = T),
"maxConstructorPracticeLaps" = max(.data$constructorNumPracticeLaps, na.rm = T)
) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$raceId, .data$driverId) %>%
dplyr::mutate(
"constructorPracticeBestPerc" = min(.data$constructorPracticeAvgPerc, na.rm = T),
"constructorPracticeAvgPerc" = mean(.data$constructorPracticeAvgPerc, na.rm = T),
"driverTeamPracticeAvgGapSec" = mean(.data$driverTeamPracticeGapSec, na.rm = T),
"driverTeamPracticeAvgGapPerc" = mean(.data$driverTeamPracticeGapPerc, na.rm = T),
"driverPercPracticeLaps" = .data$driverNumPracticeLaps / .data$maxDriverPracticeLaps
) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$raceId, .data$constructorId) %>%
dplyr::mutate("constructorPercPracticeLaps" = .data$constructorNumPracticeLaps / .data$maxConstructorPracticeLaps) %>%
dplyr::ungroup() %>%
dplyr::mutate(
"driverPercPracticeLaps" = tidyr::replace_na(.data$driverPercPracticeLaps, 0),
"constructorPercPracticeLaps" = tidyr::replace_na(.data$constructorPercPracticeLaps, 0),
"driverPracticeBestPerc" = tidyr::replace_na(.data$driverPracticeBestPerc, 1.10),
"driverPracticeAvgPerc" = tidyr::replace_na(.data$driverPracticeAvgPerc, 1.10),
"constructorPracticeBestPerc" = tidyr::replace_na(.data$constructorPracticeBestPerc, 1.10),
"constructorPracticeAvgPerc" = tidyr::replace_na(.data$constructorPracticeAvgPerc, 1.10),
"driverTeamPracticeAvgGapPerc" = tidyr::replace_na(.data$driverTeamPracticeAvgGapPerc, 1)
) %>%
dplyr::select(c(
"driverId", "constructorId", "raceId",
"driverPercPracticeLaps", "constructorPercPracticeLaps",
"driverPracticeBestPerc", "driverPracticeAvgPerc",
"constructorPracticeBestPerc", "constructorPracticeAvgPerc",
"driverTeamPracticeAvgGapPerc"
)) %>%
dplyr::distinct()
# -------- Pitstops ---------------------------------
logger::log_info("Manipulating Pit Stop data")
pits <- f1model::pit_stops %>%
dplyr::mutate("duration" = .data$milliseconds / 1000) %>%
dplyr::select(c("raceId", "driverId", "stop", "lap", "duration")) %>%
dplyr::group_by(.data$raceId) %>%
dplyr::mutate("raceAvgPitDuration" = mean_lt(.data$duration, 180, na.rm = T)) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$raceId, .data$driverId) %>%
dplyr::mutate(
"driverNumPits" = dplyr::n(),
"driverAvgPitDuration" = mean_lt(.data$duration, 240, na.rm = T),
"driverAvgPitDurationPerc" = .data$driverAvgPitDuration / .data$raceAvgPitDuration,
"driverTotalPitNum" = max(.data$stop)
) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$raceId) %>%
dplyr::mutate("raceAvgNumPits" = mean(.data$driverTotalPitNum, na.rm = T)) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$raceId) %>%
dplyr::mutate("driverNumPitPerc" = .data$driverNumPits / .data$raceAvgNumPits) %>%
dplyr::ungroup() %>%
dplyr::select(c(
"raceId", "driverId", "driverNumPits", "driverAvgPitDurationPerc", "raceAvgPitDuration",
"raceAvgNumPits", "driverNumPitPerc"
)) %>%
dplyr::distinct()
# -------- Quali ------------------------------------
logger::log_info("Manipulating Quali data")
quali <- f1model::qualifying %>%
dplyr::mutate(
"q1" = dplyr::if_else(.data$q1 == "\\N" | .data$q1 == "", NA_character_, .data$q1),
"q2" = dplyr::if_else(.data$q2 == "\\N" | .data$q2 == "", NA_character_, .data$q2),
"q3" = dplyr::if_else(.data$q3 == "\\N" | .data$q3 == "", NA_character_, .data$q3)
) %>%
dplyr::mutate(
"q1Sec" = timeToSec(.data$q1),
"q2Sec" = timeToSec(.data$q2),
"q3Sec" = timeToSec(.data$q3)
) %>%
dplyr::group_by(.data$raceId) %>%
dplyr::mutate(
"q1GapSec" = .data$q1Sec - min(.data$q1Sec, na.rm = T),
"q2GapSec" = .data$q2Sec - min(.data$q2Sec, na.rm = T),
"q3GapSec" = .data$q3Sec - min(.data$q3Sec, na.rm = T)
) %>%
dplyr::mutate(
"q1GapPerc" = .data$q1Sec / min(.data$q1Sec, na.rm = T),
"q2GapPerc" = .data$q2Sec / min(.data$q2Sec, na.rm = T),
"q3GapPerc" = .data$q3Sec / min(.data$q3Sec, na.rm = T)
) %>%
dplyr::mutate("qGapSec" = dplyr::case_when(
!is.na(.data$q3GapSec) ~ .data$q3GapSec,
!is.na(.data$q2GapSec) ~ .data$q2GapSec,
!is.na(.data$q1GapSec) ~ .data$q1GapSec,
TRUE ~ max(min(.data$q1Sec) * .10, max(.data$q1Sec) + 1)
)) %>%
dplyr::mutate("qGapPerc" = dplyr::case_when(
!is.na(.data$q3GapPerc) ~ .data$q3GapPerc,
!is.na(.data$q2GapPerc) ~ .data$q2GapPerc,
!is.na(.data$q1GapPerc) ~ .data$q1GapPerc,
TRUE ~ max(1.10, max(.data$q1GapPerc) + 0.02)
)) %>%
dplyr::ungroup() %>%
dplyr::rename("qPosition" = "position") %>%
dplyr::group_by(.data$raceId) %>%
dplyr::mutate(
"qGapPerc" = tidyr::replace_na(.data$qGapPerc, 0),
) %>%
dplyr::ungroup() %>%
dplyr::select(c("raceId", "driverId", "constructorId", "qPosition", "qGapPerc")) %>%
dplyr::distinct()
# -------- Results ----------------------------------
logger::log_info("Manipulating Result data")
results <- f1model::results %>%
dplyr::mutate(
# "currentConstructorId" = updateConstructor(.data$constructorId),
"fastestLapTimeSec" = timeToSec(.data$fastestLapTime)
) %>%
dplyr::mutate(
"driverCrash" = dplyr::if_else(.data$statusId %in% c(3, 4, 20, 33, 41, 73, 82, 104, 107, 130, 137, 138), 1, 0),
"carFailure" = dplyr::if_else(.data$statusId %in% c(5:10, 21:26, 28, 30:32, 34:40, 42:44, 46:49, 51, 54, 56, 59, 61, 63:72, 74:76, 79, 80, 83:87, 90, 91, 93:95, 98, 99, 101:103, 105, 106, 108:110, 121, 126, 129, 131:136, 140, 141), 1, 0),
"tireFailure" = dplyr::if_else(.data$statusId %in% c(27, 29), 1, 0),
"disqualified" = dplyr::if_else(.data$statusId %in% c(2), 1, 0)
) %>%
# fix position == NA for non-finishers - change to 0?
dplyr::mutate("position" = tidyr::replace_na(.data$position, 0)) %>%
dplyr::group_by(.data$driverId) %>%
dplyr::mutate(
"driverCrashRate" = ewma(.data$driverCrash, driverCrashEWMA),
"carFailureRate" = ewma(.data$carFailure, carFailureEWMA),
"tireFailureRate" = ewma(.data$tireFailure, tireFailureEWMA),
"disqualifiedRate" = ewma(.data$disqualified, disqualifiedEWMA)
) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$raceId) %>%
dplyr::mutate("gridPosCor" = stats::cor(.data$grid, .data$positionOrder)) %>%
dplyr::ungroup() %>%
dplyr::rename("finishingTime" = "time") %>%
dplyr::select(c(
"raceId", "driverId", "constructorId", "grid", "position", "positionOrder",
"status", "driverCrash", "carFailure", "tireFailure", "disqualified",
"driverCrashRate", "carFailureRate", "tireFailureRate", "disqualifiedRate", "gridPosCor"
)) %>%
dplyr::distinct()
# -------- Circuits ---------------------------------
logger::log_info("Manipulating Circuit data")
circuits <- f1model::circuits %>%
dplyr::select(c("circuitId", "name", "country", "alt", "length", "type", "direction", "nationality")) %>%
dplyr::rename(
"circuitName" = "name", "circuitAltitude" = "alt", "circuitLength" = "length",
"circuitType" = "type", "circuitDirection" = "direction", "circuitNationality" = "nationality",
)
# -------- Races ------------------------------------
logger::log_info("Manipulating Races data")
races <- f1model::races %>%
dplyr::mutate("date" = as.Date(.data$date)) %>%
dplyr::arrange(date) %>%
dplyr::filter(.data$date > as.Date("1999-12-31")) %>%
dplyr::mutate(
"safetyCars" = tidyr::replace_na(.data$safetyCars, 0),
"safetyCarLaps" = tidyr::replace_na(.data$safetyCarLaps, 0)
) %>%
dplyr::select(c(
"raceId", "year", "round", "circuitId", "name", "date", "weather",
"safetyCars", "safetyCarLaps", "f1RaceId"
)) %>%
# Previous Race Determination
dplyr::mutate(
"lastRaceId" = dplyr::lag(.data$raceId, n = 1),
"lastRaceId" = dplyr::if_else(.data$round == 1, NA_integer_, .data$lastRaceId)
) %>%
# solve circuit avg # safety cars
dplyr::group_by(.data$circuitId) %>%
dplyr::mutate(
"avgSafetyCar" = cumsum(.data$safetyCars > 0) / seq_along(.data$safetyCars),
"avgSafetyCarPerRace" = dplyr::cummean(.data$safetyCars)
) %>%
dplyr::ungroup()
# -------- Lap Times --------------------------------
logger::log_info("Manipulating Lap Times Data")
laptimes <- f1model::lap_times %>%
# calculate estimated fuel adjusted times
dplyr::group_by(.data$raceId) %>%
dplyr::mutate("numLaps" = max(.data$lap)) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$raceId, .data$driverId) %>%
dplyr::mutate("time_adj" = 25 * (100 / .data$numLaps) * (.data$numLaps - .data$lap)) %>%
dplyr::mutate("fuelAdjTime" = .data$milliseconds - .data$time_adj) %>%
# filter out slow laps (likely lap 1/safety car/in&out laps, etc)
dplyr::filter(.data$fuelAdjTime < min(.data$fuelAdjTime, na.rm = T) * 1.20) %>%
dplyr::filter(.data$lap != 1) %>%
# calculate SD & RSD with rolling 5 lap windows.
dplyr::mutate("lap_sd_roll" = zoo::rollapplyr(.data$fuelAdjTime, 5, sd, na.rm = T, fill = NA)) %>%
dplyr::filter(.data$lap_sd_roll < mean(.data$lap_sd_roll, na.rm = T) + 2 * sd(.data$lap_sd_roll, na.rm = T)) %>%
dplyr::mutate("driver_laptime_sd" = mean(.data$lap_sd_roll, na.rm = T)) %>%
dplyr::mutate("driver_laptime_rsd" = .data$driver_laptime_sd / mean(.data$fuelAdjTime, na.rm = T)) %>%
dplyr::ungroup() %>%
dplyr::select(c("raceId", "driverId", "driver_laptime_rsd")) %>%
dplyr::distinct()
# -------- Merges -----------------------------------
logger::log_info("Merging Data and performing complex calculations")
model_data <- races %>%
# ---- merge in results, drivers, constructors, circuits ----
dplyr::left_join(results, by = c("raceId")) %>%
dplyr::left_join(drivers, by = c("driverId")) %>%
dplyr::left_join(constructors, by = c("constructorId")) %>%
dplyr::left_join(circuits, by = c("circuitId")) %>%
dplyr::left_join(practices, by = c("raceId", "driverId", "constructorId")) %>%
# ---- solve driver's age at race ----
dplyr::mutate("driverAge" = lubridate::time_length(difftime(as.Date(.data$date), as.Date(.data$driverDOB)), unit = "years")) %>%
# ---- solve driver/constructor home race ----
dplyr::mutate(
"driverHomeRace" = dplyr::if_else(.data$driverNationality == .data$circuitNationality, 1, 0),
"constructorHomeRace" = dplyr::if_else(.data$constructorNationality == .data$circuitNationality, 1, 0)
) %>%
# ---- solve number of races per driver ----
dplyr::group_by(.data$driverId) %>%
dplyr::mutate("driverGPExperience" = seq.int(0, dplyr::n() - 1)) %>%
dplyr::ungroup() %>%
# ---- Add Qualifying Data ----
dplyr::left_join(quali, by = c("raceId", "driverId", "constructorId")) %>%
dplyr::group_by(.data$raceId) %>%
dplyr::mutate(
"qPosition" = dplyr::if_else(is.na(.data$qPosition), .data$grid, .data$qPosition),
"qGapPerc" = dplyr::if_else(is.na(.data$qGapPerc), max(.data$qGapPerc + 0.02, 1.10), .data$qGapPerc)
) %>%
dplyr::ungroup() %>%
# ---- Add Pit Stop Info ----
dplyr::left_join(pits, by = c("raceId", "driverId")) %>%
dplyr::group_by(.data$circuitId) %>%
dplyr::mutate(
"circuitAvgPitDuration" = mean_lt(.data$raceAvgPitDuration, 180, na.rm = T),
"circuitAvgNumPits" = mean(.data$raceAvgNumPits, na.rm = T)
) %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$driverId) %>%
dplyr::mutate(
"driverAvgPitPerc" = ewma_drop(.data$driverAvgPitDurationPerc, pitPercEWMA),
"driverAvgNumPitPerc" = ewma_drop(.data$driverNumPitPerc, pitPercEWMA)
) %>%
dplyr::mutate(
"driverAvgPitPerc" = tidyr::replace_na(.data$driverAvgPitPerc, 1L),
"driverAvgNumPitPerc" = tidyr::replace_na(.data$driverAvgNumPitPerc, 1L)
) %>%
dplyr::ungroup() %>%
# ---- Add laptime info ----
dplyr::left_join(laptimes, by = c("raceId", "driverId")) %>%
dplyr::group_by(.data$driverId) %>%
dplyr::mutate("driverAvgLaptimeRSD" = ewma_drop(.data$driver_laptime_rsd, pitPercEWMA)) %>%
dplyr::ungroup() %>%
# ---- Add Driver & constructor Points Going In. ----
# lastRaceId = raceId to lag the points to the poitns incoming to a race.
dplyr::left_join(driver_standings, by = c("lastRaceId" = "raceId", "driverId" = "driverId")) %>%
dplyr::left_join(constructor_standings, by = c("lastRaceId" = "raceId", "constructorId" = "constructorId")) %>%
dplyr::mutate(
"driverPoints" = tidyr::replace_na(.data$driverPoints, 0),
"constructorPoints" = tidyr::replace_na(.data$constructorPoints, 0),
"driverSeasonWins" = tidyr::replace_na(.data$driverSeasonWins, 0),
"constructorSeasonWins" = tidyr::replace_na(.data$constructorSeasonWins, 0)
) %>%
dplyr::group_by(.data$raceId) %>%
dplyr::mutate(
"driverPointsPerc" = dplyr::if_else(.data$round == 1, 0, .data$driverPoints / max(.data$driverPoints, na.rm = T)),
"constructorPointsPerc" = dplyr::if_else(.data$round == 1, 0, .data$constructorPoints / max(.data$constructorPoints, na.rm = T)),
"driverSeasonWinsPerc" = dplyr::if_else(.data$round == 1, 0, .data$driverSeasonWins / max(.data$driverSeasonWins, na.rm = T)),
"constructorSeasonWinsPerc" = dplyr::if_else(.data$round == 1, 0, .data$constructorSeasonWins / max(.data$constructorSeasonWins, na.rm = T)),
) %>%
dplyr::mutate(
"driverPointsPerc" = tidyr::replace_na(.data$driverPointsPerc, 0),
"constructorPointsPerc" = tidyr::replace_na(.data$constructorPointsPerc, 0),
"driverSeasonWinsPerc" = tidyr::replace_na(.data$driverSeasonWinsPerc, 0),
"constructorSeasonWinsPerc" = tidyr::replace_na(.data$constructorSeasonWinsPerc, 0),
"circuitAvgPitDuration" = tidyr::replace_na(.data$circuitAvgPitDuration, mean(.data$circuitAvgPitDuration, na.rm = T)),
"circuitAvgNumPits" = tidyr::replace_na(.data$circuitAvgNumPits, mean(.data$circuitAvgNumPits, na.rm = T)),
"driverAvgLaptimeRSD" = tidyr::replace_na(.data$driverAvgLaptimeRSD, mean(.data$driverAvgLaptimeRSD, na.rm = T))
) %>%
dplyr::ungroup()
# ---- Build grid corellation tables ----
gridCor <- model_data %>%
dplyr::group_by(.data$raceId) %>%
dplyr::summarise("gridPosCor" = mean(.data$gridPosCor, na.rm = T), "circuitId" = .data$circuitId) %>%
dplyr::distinct() %>%
dplyr::ungroup() %>%
dplyr::group_by(.data$circuitId) %>%
dplyr::mutate("avgGridPosCor" = ewma_drop(.data$gridPosCor, gridPositionCorEWMA)) %>%
dplyr::ungroup() %>%
dplyr::select(c("raceId", "avgGridPosCor"))
gpcs <- model_data %>%
dplyr::group_by(.data$circuitType) %>%
dplyr::summarise("meanGridPosCor" = mean(.data$gridPosCor))
model_data <- model_data %>%
dplyr::left_join(gridCor, by = "raceId") %>%
dplyr::mutate(
"avgGridPosCor" = dplyr::if_else(!is.na(.data$avgGridPosCor), .data$avgGridPosCor,
dplyr::case_when(
.data$circuitType == "race" ~ gpcs[gpcs$circuitType == "race", ]$meanGridPosCor,
.data$circuitType == "street" ~ gpcs[gpcs$circuitType == "street", ]$meanGridPosCor,
TRUE ~ mean(gpcs$meanGridPosCor)
)
)
) %>%
dplyr::select(c(
# ID columns
"raceId", "circuitId", "driverId", "currentConstructorId",
# race metadata
"year", "round", "name", "date",
# race info
"weather", "safetyCars", "safetyCarLaps", "avgSafetyCar", "avgSafetyCarPerRace",
# race data
"grid", "position", "positionOrder", "driverCrashRate", "carFailureRate", "tireFailureRate",
"disqualifiedRate",
# driver data
"driverName", "driverDOB", "driverNationality", "driverAge", "driverGPExperience",
"driverSeasonWins", "driverSeasonWinsPerc", "driverPoints", "driverPointsPerc", "driverHomeRace",
# constructor data
"constructorName", "constructorNationality", "constructorPoints", "constructorSeasonWins",
"constructorPointsPerc", "constructorSeasonWinsPerc", "constructorHomeRace",
# circuit data
"circuitName", "circuitAltitude", "circuitLength", "circuitType", "circuitDirection",
"circuitNationality", "avgGridPosCor",
# pit data
"driverAvgPitPerc", "driverAvgNumPitPerc", "circuitAvgPitDuration", "circuitAvgNumPits",
# laps data
"driverAvgLaptimeRSD",
# quali data
"qPosition", "qGapPerc",
# practice data
"driverPercPracticeLaps", "constructorPercPracticeLaps", "driverPracticeBestPerc", "driverPracticeAvgPerc",
"constructorPracticeBestPerc", "constructorPracticeAvgPerc", "driverTeamPracticeAvgGapPerc"
)) %>%
dplyr::mutate(
"driverPercPracticeLaps" = tidyr::replace_na(.data$driverPercPracticeLaps, 0),
"constructorPercPracticeLaps" = tidyr::replace_na(.data$constructorPercPracticeLaps, 0),
"driverPracticeBestPerc" = tidyr::replace_na(.data$driverPracticeBestPerc, 1.10),
"driverPracticeAvgPerc" = tidyr::replace_na(.data$driverPracticeAvgPerc, 1.10),
"constructorPracticeBestPerc" = tidyr::replace_na(.data$constructorPracticeBestPerc, 1.10),
"constructorPracticeAvgPerc" = tidyr::replace_na(.data$constructorPracticeAvgPerc, 1.10),
"driverTeamPracticeAvgGapPerc" = tidyr::replace_na(.data$driverTeamPracticeAvgGapPerc, 1),
"qGapPerc" = tidyr::replace_na(.data$qGapPerc, 1.10)
)
return(model_data)
}
#' Combine Data
#'
#' @description merge all of the data frames into one big one for use in modelling. EWMA parameters provided
#' help with determining the strength of the exponential weighted moving average for those parameters.
#' Note: memoised (cached), for fresh calculations use .combineData()
#'
#' @param driverCrashEWMA How much one race impacts driver's moving average of crash rate
#' @param carFailureEWMA How much one race impacts constructor's moving average of failure rate
#' @param tireFailureEWMA How much one race impacts driver's moving average of tire failure rate
#' @param disqualifiedEWMA How much one race impacts driver's moving average of disqualified rate
#' @param gridPositionCorEWMA How much one race impacts driver's moving average of crash rate
#'
#' @return a tibble with tons of data
#' @export
combineData <- memoise::memoise(.combineData) |
import { useState } from "react";
import Logo from "./Logo";
import Form from "./Form";
import PackingList from "./PackingList";
import Stats from "./Stats";
// const initialItems = [
// { id: 1, description: "Passports", quantity: 2, packed: false },
// { id: 2, description: "Socks", quantity: 12, packed: false },
// ];
export default function App(){
const [items, setItems] = useState([]);
function handleAddItems(item){
setItems((items) => [...items, item]);
}
function handleDeleteItem(id) {
setItems((items) => items.filter(item => item.id !== id));
}
function handleToggleItem(id){
setItems((items) =>
items.map(item =>
item.id === id ? {...item, packed: !item.packed}
: item
)
);
}
function handleClearList(){
const confirm = window.confirm('Are you sure you want to delete all items?');
if (confirm) setItems([]);
}
return <div className="app">
<Logo />
<Form onAddItems={handleAddItems}/>
<PackingList
items={items}
onDeleteItem = {handleDeleteItem}
onToggleItem={handleToggleItem}
onClearList={handleClearList}
/>
<Stats items={items} />
</div>
} |
import { Component, OnInit, Input, OnChanges, ViewChild, ElementRef } from '@angular/core';
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import { fromEvent } from 'rxjs';
import { filter, debounceTime, distinctUntilChanged, tap } from 'rxjs/operators';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { JukeboxService } from '../../jukebox.service';
import { Box } from '../../../../shared/models/box.model';
import { User } from 'app/shared/models/user.model';
import { PlaylistSelectorComponent } from 'app/shared/components/playlist-selector/playlist-selector.component';
import { BoxService } from 'app/shared/services/box.service';
import { QueueItemActionRequest, QueueItem, Permission } from '@teamberry/muscadine';
@Component({
selector: 'app-queue',
templateUrl: './queue.component.html',
styleUrls: ['./queue.component.scss'],
})
export class QueueComponent implements OnInit, OnChanges {
@Input() box: Box = null;
@Input() user: User = null;
@Input() permissions: Array<Permission> = [];
@Input() withHeader = true;
@ViewChild('filterInput') input: ElementRef;
queue: Array<QueueItem> = [];
filteredQueue: Array<QueueItem> = [];
isLoading = true;
isFiltering = false;
filterValue = '';
priorityVideos: Array<QueueItem>;
tabSetOptions = [
{ title: `Upcoming`, value: 'upcoming' },
{ title: 'Played', value: 'played' }
]
displayTab: 'upcoming' | 'played' = 'upcoming';
inAddingProcess = false;
@ViewChild(CdkVirtualScrollViewport) virtualScroller: CdkVirtualScrollViewport;
constructor(
private jukeboxService: JukeboxService,
private modalService: NgbModal,
private boxService: BoxService,
private toastr: ToastrService
) { }
ngOnInit() {
this.listen();
}
ngOnChanges() {
this.listen();
}
showFilter() {
if (this.isFiltering) {
this.resetFilter();
this.isFiltering = false;
} else {
this.isFiltering = true;
setTimeout(() => {
this.bindSearch();
}, 2000);
}
}
bindSearch() {
fromEvent(this.input.nativeElement, 'keyup')
.pipe(
filter(Boolean),
debounceTime(500),
distinctUntilChanged(),
tap(() => {
this.filterValue = this.input.nativeElement.value
this.applyFilter()
})
)
.subscribe()
}
applyFilter() {
this.filteredQueue = this.filterValue
? this.queue.filter(item => item.video.name.toLowerCase().includes(this.filterValue.toLowerCase()))
: this.queue
}
resetFilter() {
this.filterValue = ''
this.input.nativeElement.value = ''
this.applyFilter()
}
scrollToTop() {
this.virtualScroller.scrollToIndex(0, 'smooth');
}
/**
* Subscribe to the box from the jukebox space, to get the playlist when needed
*
* @memberof PlaylistComponent
*/
listen() {
this.jukeboxService.getQueueStream().subscribe(
(queue: Array<QueueItem>) => {
this.queue = [];
this.filteredQueue = [];
const currentlyPlaying = queue.find((queueItem) => queueItem.startTime !== null && queueItem.endTime === null);
const playedVideos = this.buildPartialPlaylist(queue, 'played');
const upcomingVideos = this.buildPartialPlaylist(queue, 'upcoming');
const priorityVideos = this.buildPartialPlaylist(queue, 'priority');
this.queue = this.box.options.loop
? [currentlyPlaying, ...priorityVideos, ...upcomingVideos, ...playedVideos]
: [...playedVideos, currentlyPlaying, ...priorityVideos, ...upcomingVideos]
this.applyFilter()
this.isLoading = false;
}
)
}
/**
* Builds a partial list of the playlist of the box based on the wanted state of the videos
*
* @param playlist The playlist of the box
* @param state The state of the videos. Upcoming or Played
* @returns
* @memberof PlaylistComponent
*/
buildPartialPlaylist(playlist: Array<QueueItem>, state: string): Array<QueueItem> {
if (state === 'upcoming') {
const upcoming = playlist.filter((item: QueueItem) => item.startTime === null && !item.setToNext);
return upcoming
}
if (state === 'played') {
const played = playlist.filter((item: QueueItem) => item.startTime !== null && item.endTime !== null && !item.setToNext);
return played
}
if (state === 'priority') {
const priorityVideos = playlist
.filter(queueItem => queueItem.setToNext)
.sort((a, b) => +new Date(a.setToNext) - +new Date(b.setToNext))
this.priorityVideos = priorityVideos
return priorityVideos;
}
}
/**
* Triggered by the order$ event of the playlist item component.
*
* @param event
* @memberof PlaylistComponent
*/
handlePlaylistOrder(event) {
const actionRequest: QueueItemActionRequest = {
item: event.item,
userToken: this.user._id,
boxToken: this.box._id
}
switch (event.order) {
case 'replay':
this.jukeboxService.replayVideo(actionRequest)
break
case 'cancel':
this.jukeboxService.cancelVideo(actionRequest)
break
case 'skip':
this.jukeboxService.skipVideo()
break
case 'preselect':
this.jukeboxService.preselectVideo(actionRequest)
break
case 'forcePlay':
this.jukeboxService.forcePlayVideo(actionRequest)
break
}
}
startConversion() {
const modalRef = this.modalService.open(PlaylistSelectorComponent);
modalRef.componentInstance.selectedPlaylist$.subscribe(
async (playlistId: string) => {
this.boxService.convert(this.box._id, playlistId).subscribe()
this.toastr.success('Playlist updated', 'Success')
}
)
}
} |
import { Component, Input, OnInit, Output, EventEmitter, OnChanges, SimpleChanges, ViewChild, ElementRef } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { map, startWith, debounceTime } from 'rxjs/operators';
import { isEqual } from 'lodash';
@Component({
selector: 'pros-form-input-autoselect',
templateUrl: './form-input-autoselect.component.html',
styleUrls: ['./form-input-autoselect.component.scss']
})
export class FormInputAutoselectComponent implements OnInit, OnChanges {
/**
* array of options to show in the dropdown
*/
@Input()
updatedOptionsList: any[] = [];
/**
* local variable for holding the filtered options
*/
optionList: any[] = [];
/**
* this key is used to get the value from the selected item
* if the item is an object
*/
@Input()
valueKey: string;
/**
* this key is used to get the tooltip from the selected item
* if the item is an object
*/
@Input()
tooltipKey: string;
/**
* this key is used to get the label from the selected item
* if the item is an object
*/
@Input()
labelKey: string;
/**
* hold or pass the preselected values
*/
@Input()
preSelectedValue: any;
/**
* Define the action that will happen when
* selecting the extra option in the list
*/
@Input()
viewMoreAction: string;
/**
* Define the action that will happen when
* the extra button at the end of the input
* gets clicked
*/
@Input()
extraOption: string;
/**
* Define the label show for the extra option at
* the end of the list
*/
@Input()
extraOptionLabel: string;
/**
* whether values are loading
*/
@Input()
loader = false;
/**
* Preferred deounce value for getting the searchTerm
*/
@Input()
debounceValue = 400;
/**
* Define the field label
*/
@Input()
fieldLabel: string;
/**
* To show/hide extra action level at bottom
*/
@Input()
isExtraLabel = true;
/**
* To show/hide Suffix button at the right side of input
*/
@Input()
isSuffixButton = true;
/**
* Disable internal filter
*/
@Input()
disableInternalFilter = false;
/**
* highlight error
*/
@Input()
hasError = false;
/**
* Event emitter for the selected option
*/
@Output()
optionSelectedEmit: EventEmitter<any> = new EventEmitter(null);
/**
* Event emitter for extra button at the end of the input
*/
@Output()
openCustomDialog: EventEmitter<any> = new EventEmitter(null);
/**
* Event emitter to emit event while searching..
*/
@Output()
emitSearchValue: EventEmitter<any> = new EventEmitter(null);
/**
* Event emitter to emit event on click extra label
*/
@Output()
emitExtraLabelClick: EventEmitter<any> = new EventEmitter(null);
/**
* reference to the input
*/
@ViewChild('textInput') textInput: ElementRef;
/**
* Observable for filtered option
* used to filter results as a search term is typed
*/
filteredOptions: Observable<any[]>;
/**
* Form control for the input field
*/
selectedMdoFldCtrl: FormControl;
/**
* option that holds a value to identify if the results array is empty
*/
hasResult: boolean;
/**
* emit options container scroll end
*/
@Output()
emitScrollEnd: EventEmitter<boolean> = new EventEmitter();
/**
* Constructor of class
*/
constructor() {
this.selectedMdoFldCtrl = new FormControl();
}
/**
* get the value using the key passed as an input to this component
* @param option pass dropdown options object
*/
getValue(option){
if(this.valueKey && option[this.valueKey]) {
return option[this.valueKey];
} else {
return option;
}
}
/**
* get the label using the key passed as an input to this component
* @param option pass dropdown options object
*/
getLabel(option) {
if(option[this.labelKey]) {
return option[this.labelKey];
}
}
/**
* get the tooltip using the key passed as an input to this component
* @param option pass dropdown options object
*/
getTooltipText(option) {
if(option[this.tooltipKey]) {
return option[this.tooltipKey];
}
}
/**
* ANGULAR HOOK
*/
ngOnInit(): void {
this.selectedMdoFldCtrl.valueChanges
.pipe(debounceTime(this.debounceValue))
.subscribe((value) => {
this.emitSearchValue.emit(value);
});
this.optionList = this.updatedOptionsList;
if(!this.disableInternalFilter) {
this.initFilter();
} else {
this.filteredOptions = of(this.optionList);
this.hasResult = !!this.optionList.length;
}
}
initFilter() {
this.filteredOptions = this.selectedMdoFldCtrl.valueChanges.pipe(
debounceTime(400),
startWith(''),
map(value => this._filter(value))
);
}
/**
* method to filter dropdown values based on the typed string
* @param value pass the value to be looked up in the list of values
*/
_filter(value: any): any[] {
let availableOptions = this.optionList;
if(value){
const filterValue = (isNaN(value) && typeof value === 'string')? value.toLowerCase(): value;
availableOptions = this.optionList.filter(option => this.getLowerCaseLabel(option[this.labelKey]).indexOf(filterValue) === 0);
}
this.hasResult = availableOptions.length>0;
return availableOptions;
}
/**
* convert string to lowercase
* @param value pass the string to be converted to lowercase
*/
getLowerCaseLabel(value) {
return value? value.toLowerCase(): '';
}
/**
* method to prevent re rendering in a list
* @param fld track by for performance improvement
*/
suggestedMdoFldTrkBy(fld): string {
if (fld) {
return fld[this.valueKey];
}
return null;
}
/**
* method to show consistent selected values
* @param object pass object from which the value should be displayed
*/
mdoFieldDisplayWith(object): string {
return object ? object[this.labelKey] : '';
}
/**
* emit the selected values
* @param sel selected option or action
*/
emitOptionSelected(event: any) {
let action: string;
this.initFilter();
this.textInput.nativeElement.blur();
if(event && event.option){
action = event.option.value
} else {
action = event;
}
if(action === this.viewMoreAction || action === this.extraOption){
this.openCustomDialog.emit(action);
} else {
this.optionSelectedEmit.emit(action);
}
}
/**
* Function to emit event on click extra label
*/
emitClickEvent() {
this.emitExtraLabelClick.emit();
}
/**
* ANGULAR HOOK
* It will be called when value of @Input changes from parent component.
* @param changes: Object of type SimpleChanges
*/
ngOnChanges(changes: SimpleChanges) {
const preVal = 'previousValue';
if(changes.updatedOptionsList) {
if(changes.updatedOptionsList[preVal] && !isEqual(changes.updatedOptionsList[preVal], changes.updatedOptionsList.currentValue)){
if(changes.updatedOptionsList.currentValue) {
this.optionList = changes.updatedOptionsList.currentValue;
if(!this.disableInternalFilter) {
this.initFilter();
} else {
this.filteredOptions = of(this.optionList);
this.hasResult = !!this.optionList.length;
}
}
}
}
if (changes?.preSelectedValue) {
this.preSelectedValue = changes?.preSelectedValue?.currentValue;
this.selectedMdoFldCtrl.setValue(this.preSelectedValue);
}
if(changes.loader && changes.loader[preVal] !== changes.loader.currentValue) {
this.loader = changes.loader.currentValue;
}
}
/**
* on options container scroll end
*/
onScrollEnd(event) {
console.log(event);
this.emitScrollEnd.emit(true);
}
} |
---
title: "Metrics Library for iOS Performance Debugging Using OSLog and Xray"
description: "A step-by-step guide for using Xray programmatically."
---
## Setup
In your `ClientConfig` (`PROClientConfig`) object, set the `xrayEnabled` and `osLogEnabled` flags to true (YES). This must be done before service startup. For example, this would occur in `AppDelegate.m` in the `promotedMetricsModule` method:
```
- (PromotedMetricsModule *)promotedMetricsModule {
PROClientConfig *config = [[PROClientConfig alloc] init];
// ...
config.osLogEnabled = YES;
config.xrayEnabled = YES;
PROMetricsLoggerService *service =
[[PROMetricsLoggerService alloc] initWithInitialConfig:config];
[service startLoggingServices];
return [[PromotedMetricsModule alloc] initWithMetricsLoggerService:service];
}
```
## OSLog
Logs will be sent to the subsystem ai.promoted with categories `MetricsLogger` and `Xray`.
To view these logs in development, when attached to the Snackpass process via Xcode, look in Xcode’s console output and look for the categories above. You can filter the logs to these categories.

To view these logs when not running under Xcode, either on debug or production:
1. If your iPhone is connected to your Mac, open the Console app and select your iPhone from the sidebar. Then hit Start in the toolbar to begin collecting logs. You can filter the logs to narrow them down.
2. If your iPhone is not connected to a Mac, capture a [sysdiagnose](https://www.jessesquires.com/blog/2018/02/08/how-to-sysdiagnose-ios/) and inspect the logs inside the resulting file.
## Xray
You can access the Xray object programmatically at `MetricsLoggerService.xray`. The relevant properties on Xray are:
| Properties | Description |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| totalBytesSent | Total serialized bytes sent across network.This count is an approximation of actual network traffic. Network traffic also include HTTP headers, which are not counted in this size. |
| totalRequestsMade | Total number of requests sent across network. |
| totalTimeSpent | Total time spent in Promoted logging code. |
| networkBatches | Most recent network batches. |
| calls | Flattened logging calls across networkBatches. |
| errors | Flattened errors across networkBatches. |
Xray also prints a summary of metrics for the latest batch and cumulative resources used at the end of every network flush.
Set a breakpoint in `MetricsLogger.handleFlushResponse()` to view the result of metrics logging calls. You can inspect the properties of Xray via the debugger via the xray property of `MetricsLogger`.
```
private func handleFlushResponse(data: Data?, error: Error?) {
osLog?.info("Logging finished")
if let e = error {
osLog?.error("flush/sendMessage: %{public}@",
e.localizedDescription)
xray?.metricsLoggerBatchResponseDidError(e)
}
xray?.metricsLoggerBatchResponseDidComplete()
}
```
We’ll eventually add more detailed reporting of individual logging calls in Xray, via a separate flag. For now, the debugger is the best way to view this information. |
package com.project.taskmanager.ui.feature.home.composables
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.project.taskmanager.R
import com.project.taskmanager.common.AnimatedPreloader
import com.project.taskmanager.common.NewTaskButton
import com.project.taskmanager.common.VerticalSpacer
import com.project.taskmanager.ui.theme.TaskManagerTheme
@Composable
fun EmptyTaskView(
onNewTaskClick: () -> Unit = {}
) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
AnimatedPreloader(
modifier = Modifier
.fillMaxWidth()
.requiredHeight(300.dp),
rawResId = R.raw.empty,
isPlaying = true
)
VerticalSpacer(size = 50.dp)
Text(
text = "Look's like you have not added any task yet.\nAdd your first task",
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center
)
VerticalSpacer(size = 20.dp)
NewTaskButton(onClick = onNewTaskClick)
}
}
@Preview(showBackground = true)
@Composable
private fun EmptyTaskPreview() {
TaskManagerTheme {
EmptyTaskView()
}
} |
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"strings"
"time"
)
var timeout = flag.Int("timeout", 3, "Ex: 3")
var webhook = flag.String("webhook", "", "Ex: example.com/webhook")
var host = flag.String("host", "", "Ex: example.com")
type Notifier func(host string)
type WebhookPayload struct {
Host string `json:"host"`
Time string `json:"time"`
}
var start = time.Now()
func main() {
flag.Parse()
var notifier Notifier = desktopNotification
if *host == "" {
fmt.Println("Usage: dns-notify --host example.com")
os.Exit(1)
}
if *webhook != "" {
notifier = webhookNotification
}
fmt.Println("Target:", *host)
fmt.Println("Timeout:", *timeout)
for {
if ping(*host) {
fmt.Printf("Host %s found in %s\n", *host, time.Since(start))
notifier(*host)
os.Exit(0)
}
fmt.Println("Pinging host failed...")
time.Sleep(time.Second * time.Duration(*timeout))
}
}
func ping(url string) bool {
if !strings.HasPrefix(url, "https://") && !strings.HasPrefix(url, "http://") {
url = fmt.Sprintf("https://%s", url)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
client := &http.Client{}
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return false
}
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
return true
}
func desktopNotification(url string) {
cmd := exec.Command("notify-send", "DNS Notify", fmt.Sprintf("Host %s is found!", url))
err := cmd.Run()
if err != nil {
fmt.Println("Error executing command:", err)
return
}
}
func webhookNotification(url string) {
webhookUrl := getWebhookUrl(*webhook)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
data, err := json.Marshal(WebhookPayload{
Host: url,
Time: time.Since(start).String(),
})
client := &http.Client{}
req, err := http.NewRequestWithContext(ctx, "POST", webhookUrl, bytes.NewBuffer(data))
if err != nil {
log.Fatal(err)
}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
fmt.Printf("Webhook %s has been notified\n", webhookUrl)
}
func getWebhookUrl(url string) string {
if strings.HasPrefix(*webhook, "http://") || strings.HasPrefix(*webhook, "https://") {
return *webhook
}
return fmt.Sprintf("https://%s", *webhook)
} |
<template>
<b-card>
<b-row class="justify-content-between">
<b-col class="pr-md-32 pr-md-120">
<h4>Basic</h4>
<p class="hp-p1-body">Tooltip will show on mouse enter.</p>
</b-col>
<b-col class="hp-flex-none w-auto">
<b-button
@click="codeClick()"
variant="text"
class="btn-icon-only show-code-btn"
>
<i
class="ri-code-s-slash-line hp-text-color-black-80 hp-text-color-dark-30 lh-1"
style="font-size: 16px"
></i>
</b-button>
</b-col>
</b-row>
<b-row>
<div class="col-12 mt-16">
<b-tabs>
<b-tab title="First" active
><p class="hp-p1-body mt-8">I'm the first tab</p>
</b-tab>
<b-tab title="Second"
><p class="hp-p1-body mt-8">I'm the second tab</p>
</b-tab>
<b-tab title="Disabled" disabled
><p class="hp-p1-body mt-8">I'm a disabled tab!</p>
</b-tab>
</b-tabs>
</div>
<div
v-if="codeActive"
class="col-12 mt-24 hljs-container"
:class="{ active: codeActiveClass }"
>
<pre v-highlightjs>
<code class="hljs html">
{{ codeText }}
</code>
</pre>
</div>
</b-row>
</b-card>
</template>
<script>
import { BRow, BCol, BCard, BButton, BTabs, BTab } from "bootstrap-vue";
import code from "./code";
export default {
data() {
return {
codeText: code.basic,
codeActive: false,
codeActiveClass: false,
};
},
components: {
BRow,
BCol,
BCard,
BButton,
BTabs,
BTab,
},
methods: {
codeClick() {
this.codeActive = !this.codeActive;
setTimeout(() => {
this.codeActiveClass = !this.codeActiveClass;
}, 100);
},
},
};
</script> |
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:google_generative_ai/google_generative_ai.dart';
void main() async {
await dotenv.load(fileName: ".env");
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple, brightness: Brightness.dark),
useMaterial3: true,
),
home: const Home(),
);
}
}
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Build with Gemini"),
centerTitle: true,
),
body: const ChatScreen(),
);
}
}
class ChatScreen extends StatefulWidget {
const ChatScreen({super.key});
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
late final GenerativeModel _model;
late final ChatSession _chat;
final TextEditingController _textController = TextEditingController();
final ScrollController _scrollController = ScrollController();
bool _loading = false;
@override
void initState() {
_model = GenerativeModel(model: "gemini-pro", apiKey: dotenv.env['API_KEY']!);
_chat = _model.startChat();
super.initState();
}
@override
Widget build(BuildContext context) {
bool hasApiKey = dotenv.env['API_KEY'] != null && dotenv.env['API_KEY']!.isNotEmpty;
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: hasApiKey
? ListView.builder(
controller: _scrollController,
itemBuilder: (context, idx) {
final content = _chat.history.toList()[idx];
final text = content.parts.whereType<TextPart>().map<String>((e) => e.text).join('');
return MessageWidget(
text: text,
isFromUser: content.role == 'user',
);
},
itemCount: _chat.history.length,
)
: ListView(
children: const [
Text('No API key found. Please provide an API Key.'),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 25,
horizontal: 15,
),
child: Row(
children: [
Expanded(
child: TextFormField(
controller: _textController,
autofocus: true,
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(15),
hintText: 'Enter a prompt...',
border: OutlineInputBorder(
borderRadius: const BorderRadius.all(
Radius.circular(14),
),
borderSide: BorderSide(
color: Theme.of(context).colorScheme.secondary,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: const BorderRadius.all(
Radius.circular(14),
),
borderSide: BorderSide(
color: Theme.of(context).colorScheme.secondary,
),
),
),
onFieldSubmitted: (String value) {
_sendChatMessage(value);
},
),
),
const SizedBox.square(
dimension: 15,
),
if (!_loading)
IconButton(
onPressed: () async {
_sendChatMessage(_textController.text);
},
icon: Icon(
Icons.send,
color: Theme.of(context).colorScheme.primary,
),
)
else
const CircularProgressIndicator(),
],
),
),
],
),
);
}
Future<void> _sendChatMessage(String message) async {
setState(() => _loading = true);
try {
final response = await _chat.sendMessage(Content.text(message));
final text = response.text;
if (text == null) {
debugPrint('No response from API.');
return;
}
setState(() => _loading = false);
} catch (e) {
debugPrint(e.toString());
} finally {
_textController.clear();
setState(() => _loading = false);
}
}
}
class MessageWidget extends StatelessWidget {
final String text;
final bool isFromUser;
const MessageWidget({
super.key,
required this.text,
required this.isFromUser,
});
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: isFromUser ? MainAxisAlignment.end : MainAxisAlignment.start,
children: [
Flexible(
child: Container(
constraints: const BoxConstraints(maxWidth: 600),
decoration: BoxDecoration(
color: isFromUser
? Theme.of(context).colorScheme.primaryContainer
: Theme.of(context).colorScheme.surfaceVariant,
borderRadius: BorderRadius.circular(18),
),
padding: const EdgeInsets.symmetric(
vertical: 15,
horizontal: 20,
),
margin: const EdgeInsets.only(bottom: 8),
child: MarkdownBody(
selectable: true,
data: text,
),
),
),
],
);
}
} |
import ddf.minim.*;
float facing=0, delta=0;
float x=300, y=200, dx=1, dy=0;
AudioPlayer player;
Minim minim;
void setup ()
{
size(400, 400);
minim = new Minim(this);
player = minim.loadFile ("sound.mp3");
player.loop();
}
void draw ()
{
background(200);
ellipse (200, 200, 10, 10); ellipse (x, y, 10, 10);
line (x, y, 200, 200); line (x, y, x+10*dx, y+10*dy);
text ("Angle is "+theta (x, y, 200, 200)+" Facing "+
facing+" Delta is "+delta+" Pan is "+(-sin(radians(delta))), 10, 30);
}
float theta (float x0, float y0, float x1, float y1)
{
float x;
x = (float)atan2(y1-y0, x1-x0);
if (x<0) x = x + 2*PI;
return degrees(x);
}
void keyPressed ()
{
if (key == 'w') // Move 'forward'
{ x += 5*dx; y += 5*dy; }
else if (key == 's') // Move 'backward'
{ x -= 5*dx; y -= 5*dy; }
else if (key == 'a') facing = facing - 1.0; // Turn left
else if (key == 'd') facing = facing + 1.0; // Turn right
if (facing < 0) facing = facing + 360;
else if (facing>360) facing = facing - 360;
dx = cos(radians(facing)); dy = sin(radians(facing));
delta = facing - theta(x, y, 200, 200);
player.setPan (-sin(radians(delta)));
} |
import time
import board
import digitalio
import busio
from rainbowio import colorwheel
import neopixel
from adafruit_lsm6ds.lsm6ds33 import LSM6DS33
from adafruit_mcp230xx.mcp23017 import MCP23017
# UART Init
uart = busio.UART(board.GP0, board.GP1, baudrate=115200)
# Neopixel Init
num_pixels = 3
pixels = neopixel.NeoPixel(board.GP2, num_pixels, brightness=0.3, auto_write=False)
# I2C Bus Init
i2c = busio.I2C(board.GP13, board.GP12)
# LSM6 CONFIGURATION
sensor = LSM6DS33(i2c)
# MCP23017 CONFIGURATION
# Address within range 0x20 - 0x28 depending on A2 A1 A0
mcp = MCP23017(i2c, address=0x20)
mcp_in_0 = mcp.get_pin(0)
mcp_in_0.direction = digitalio.Direction.INPUT
mcp_in_0.pull = digitalio.Pull.UP
mcp_in_1 = mcp.get_pin(1)
mcp_in_1.direction = digitalio.Direction.INPUT
mcp_in_1.pull = digitalio.Pull.UP
mcp_in_2 = mcp.get_pin(2)
mcp_in_2.direction = digitalio.Direction.INPUT
mcp_in_2.pull = digitalio.Pull.UP
mcp_in_3 = mcp.get_pin(3)
mcp_in_3.direction = digitalio.Direction.INPUT
mcp_in_3.pull = digitalio.Pull.UP
mcp_out_0 = mcp.get_pin(8)
mcp_out_0.direction = digitalio.Direction.OUTPUT
mcp_out_0.value = False
mcp_out_1 = mcp.get_pin(9)
mcp_out_1.direction = digitalio.Direction.OUTPUT
mcp_out_0.value = False
mcp_out_2 = mcp.get_pin(10)
mcp_out_2.direction = digitalio.Direction.OUTPUT
mcp_out_0.value = False
mcp_out_3 = mcp.get_pin(11)
mcp_out_3.direction = digitalio.Direction.OUTPUT
mcp_out_0.value = False
# SHIFT REG CONFIGURATION
# 74HC165 shift in pins
si_data = digitalio.DigitalInOut(board.GP11)
si_data.direction = digitalio.Direction.INPUT
si_data.pull = digitalio.Pull.UP
si_clk = digitalio.DigitalInOut(board.GP7)
si_clk.direction = digitalio.Direction.OUTPUT
si_clk.value = False
si_nlatch = digitalio.DigitalInOut(board.GP6)
si_nlatch.direction = digitalio.Direction.OUTPUT
si_nlatch.value = True
# 74HC595 shift out pins
so_data = digitalio.DigitalInOut(board.GP8)
so_data.direction = digitalio.Direction.OUTPUT
so_data.value = False
so_clk = digitalio.DigitalInOut(board.GP10)
so_clk.direction = digitalio.Direction.OUTPUT
so_clk.value = False
so_nlatch = digitalio.DigitalInOut(board.GP9)
so_nlatch.direction = digitalio.Direction.OUTPUT
so_nlatch.value = True
# FUNCTION DEFINITIONS
# Shift out 8 bit field to 595 shift register
def shift_out(bitfield):
# Chip enable low to begin transaction
so_nlatch.value = False
# For each bit in the bitfield
for i in range(0, 8):
# Set clock low
so_clk.value = False
# Check if bit is set and set data high / low accordingly
if bitfield & (1 << i):
so_data.value = True
else:
so_data.value = False
# Clock going high shift the above set data in
so_clk.value = True
# Return data to zero value (not required, but easier for timing)
so_data.value = False
# Ensure clock is low when transaction finished
so_clk.value = False
# Chif enable high now transaction is done
so_nlatch.value = True
# Shift in 8 bits from 165 shift register
def shift_in():
# Var to store read value in
readback = 0
# Set chip select high to begin read
# Normally chip select is active low, but it's not this time
# I know the name is wrong, but I'm keeping it identical to the schematic / PCB
si_nlatch.value = True
# For the 8 inputs on the shift register, read them into the temp var
for i in range(0, 8):
# Clock going high triggers shift out of next value
si_clk.value = True
# Bitwise or with 0 will set value if set on shift reg
readback |= (si_data.value) << (7-i)
# Clock low so we can bring it high next time
si_clk.value = False
# Transaction over, return chip select to default state
si_nlatch.value = False
# Bitshifting to align values to MSB and invert as DIP switch is active low
return (readback << 3) ^ 0xFF
# Cycling rainbow on all LEDs
def rainbow_cycle():
for j in range(255):
for i in range(num_pixels):
rc_index = (i * 256 // num_pixels) + j
pixels[i] = colorwheel(rc_index & 255)
pixels.show()
time.sleep(0.005)
# DEMO TIME!
# For more info, please reads the docs: https://joshajohnson.com/digital-explorer-board/
while True:
# SHIFT REGISTER DIP SWITCH
# Read in the DIP switch values
sr_dip_val = shift_in()
# Write values out to LEDs
shift_out(sr_dip_val)
# Print info to user for debug
# print("Shift Reg Value: {:04b}".format(sr_dip_val >> 4))
# I2C SCANNER
# while not i2c.try_lock():
# pass
# try:
# print(
# "I2C addresses found:",
# [hex(device_address) for device_address in i2c.scan()],
# )
# finally: # unlock the i2c bus when ctrl-c'ing out of the loop
# i2c.unlock()
# MCP I2C IO EXPANDER
# Read input DIP switch, and write out inverted value to LED (switch is active low)
mcp_out_0.value = not mcp_in_0.value
mcp_out_1.value = not mcp_in_1.value
mcp_out_2.value = not mcp_in_2.value
mcp_out_3.value = not mcp_in_3.value
# UART TRANSMIT
uart.write(bytes("Hello World!\r\n", "ascii"))
# I2C ACCEL
print("Acceleration: X:%.2f, Y: %.2f, Z: %.2f m/s^2" % (sensor.acceleration))
# print("Gyro X:%.2f, Y: %.2f, Z: %.2f radians/s" % (sensor.gyro))
# print("")
# WS2812 "NEOPIXEL" DEMO
# Cycle though rainbow colours on LEDs
# This is a blocking function that takes approx 1.4s to finish
# Comment out if you want everything else to run fast!
rainbow_cycle()
# If you comment out rainbow_cycle(), you may want to add in a delay such as below
# time.sleep(0.1) # Sleep time in seconds (i.e. 100ms delay for each loop) |
<!--
Objectives
1. Using the mobile first approach
- Explore what makes for responsiveness and how they work across different platforms and devices
- Build our own responsive web page using CSS media queries and viewport tag
2. Have basic knowledge of CSS flexbox and animations
How -
1. Set view port
2. Size content to view port
3. Use media queries for specific view port changes
-->
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="./style.css" />
<title></title>
<script type="text/javascript">
function handle_click(el) {
el.classList.toggle("animate");
let dropdown_el_list = document.getElementsByClassName("drop-down");
console.log(dropdown_el_list, "dropdown_el_list");
let dropdown_el = dropdown_el_list[0];
dropdown_el.classList.toggle("hidden");
}
</script>
</head>
<body>
<header>
<h3>Breadface</h3>
<div class="mobile-menu" onclick="handle_click(this)">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
<ul class="main-menu">
<li>Home</li>
<li>About</li>
<li>Contact us</li>
</ul>
</header>
<div class="drop-down hidden">
<ul class="dropdown-menu">
<li>Home</li>
<li>About</li>
<li>Contact us</li>
</ul>
</div>
<div id="main">
<h3 class="title">
Welcome to my food blog. Find interesting recipes you would love to eat.
</h3>
<div class="heading">
Latest recipes
</div>
<div class="recipe">
<div class="recipe_image">
<img src="https://via.placeholder.com/250/190" />
</div>
<div class="recipe_image">
<img src="https://via.placeholder.com/250/190" />
</div>
<div class="recipe_image">
<img src="https://via.placeholder.com/250/190" />
</div>
</div>
<div class="heading">
Favourite Cuisines
</div>
<div class="cuisines">
<div class="cuisine_image">
<img src="https://via.placeholder.com/115/95" />
</div>
<div class="cuisine_image">
<img src="https://via.placeholder.com/115/95" />
</div>
<div class="cuisine_image">
<img src="https://via.placeholder.com/115/95" />
</div>
<div class="cuisine_image">
<img src="https://via.placeholder.com/115/95" />
</div>
</div>
</div>
<footer></footer>
</body>
</html> |
@extends('layouts.main', ['activePage' => 'users', 'titlePage' => 'Nuevo Usuario'])
@section('content')
<div class="content">
<div class="container-dluid">
<div class="row">
<div class="col md-12">
<form action="{{ route('users.store')}}" method="post" class="form-horizontal">
@csrf
<div class="card">
<div class="card-header card-header-primary">
<h4 class="card-title">Usuario</h4>
<p class="card-category">Ingresar datos</p>
</div>
<div class="card-body">
<div class="row">
<label for="name" class="col-sm-2 col-form-label">Nombre</label>
<div class="col-sm-7">
<input type="text" class="form-control" name="name" placeholder="Ingrese su nombre" value="{{ old('name')}}" autofocus>
@if ($errors->has('name'))
<span class="error text-danger" for="input-name">{{ $errors->first('name')}}</span>
@endif
</div>
</div>
<div class="row">
<label for="username" class="col-sm-2 col-form-label">Nombre de usuario</label>
<div class="col-sm-7">
<input type="text" class="form-control" name="username" placeholder="Ingrese su nombre de usuario" value="{{ old('username')}}" autofocus>
@if ($errors->has('username'))
<span class="error text-danger" for="input-username">{{ $errors->first('username')}}</span>
@endif
</div>
</div>
<div class="row">
<label for="email" class="col-sm-2 col-form-label">Correo</label>
<div class="col-sm-7">
<input type="email" class="form-control" name="email" placeholder="Ingrese su correo" value="{{ old('email')}}" autofocus>
@if ($errors->has('email'))
<span class="error text-danger" for="input-email">{{ $errors->first('email')}}</span>
@endif
</div>
</div>
<div class="row">
<label for="password" class="col-sm-2 col-form-label">Contraseña</label>
<div class="col-sm-7">
<input type="password" class="form-control" name="password" placeholder="Ingrese su contraseña" autofocus>
@if ($errors->has('password'))
<span class="error text-danger" for="input-password">{{ $errors->first('password')}}</span>
@endif
</div>
</div>
<div class="row">
<label for="roles" class="col-sm-2 col-form-label">Roles</label>
<div class="col-sm-7">
<div class="form-group">
<div class="tab-content">
<div class="tab-pane active">
<table class="table">
<tbody>
@foreach ($roles as $id => $role)
<tr>
<td>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox" name="roles[]"
value="{{ $id }}"
>
<span class="form-check-sign">
<span class="check"></span>
</span>
</label>
</div>
</td>
<td>
{{ $role }}
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card-footer ml-auto mr-atuto">
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
@endsection |
using System.IO;
using System.Web.Mvc;
namespace OnlineTestApp.UI
{
public static class ControllerExtensions
{
/// <summary>
/// this.RenderView("ViewName", model);
/// </summary>
/// <param name="controller"></param>
/// <param name="viewName"></param>
/// <param name="model"></param>
/// <returns></returns>
public static string RenderView(this Controller controller, string viewName, object model)
{
return RenderView(controller, viewName, new ViewDataDictionary(model));
}
/// <summary>
/// this.RenderView("ViewName", model);
/// </summary>
/// <param name="controller"></param>
/// <param name="viewName"></param>
/// <param name="viewData"></param>
/// <returns></returns>
public static string RenderView(this Controller controller, string viewName, ViewDataDictionary viewData)
{
var controllerContext = controller.ControllerContext;
var viewResult = ViewEngines.Engines.FindView(controllerContext, viewName, null);
StringWriter stringWriter;
using (stringWriter = new StringWriter())
{
var viewContext = new ViewContext(
controllerContext,
viewResult.View,
viewData,
controllerContext.Controller.TempData,
stringWriter);
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
}
return stringWriter.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="controller"></param>
/// <param name="viewName"></param>
/// <param name="model"></param>
/// <returns></returns>
public static string RenderPartialView(this Controller controller, string viewName, object model)
{
return RenderPartialView(controller, viewName, new ViewDataDictionary(model));
}
/// <summary>
///
/// </summary>
/// <param name="controller"></param>
/// <param name="viewName"></param>
/// <param name="viewData"></param>
/// <returns></returns>
public static string RenderPartialView(this Controller controller, string viewName, ViewDataDictionary viewData)
{
var controllerContext = controller.ControllerContext;
var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
StringWriter stringWriter;
using (stringWriter = new StringWriter())
{
var viewContext = new ViewContext(
controllerContext,
viewResult.View,
viewData,
controllerContext.Controller.TempData,
stringWriter);
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
}
return stringWriter.ToString();
}
}
} |
import React, { createContext, useState, useContext } from 'react';
// Create context
const SelectedProductsContext = createContext();
// Custom hook to use selectedProducts context
export const useSelectedProducts = () => {
return useContext(SelectedProductsContext);
};
// Context Provider
export const SelectedProductsProvider = ({ children }) => {
const [selectedProducts, setSelectedProducts] = useState([]);
return (
<SelectedProductsContext.Provider value={{ selectedProducts, setSelectedProducts }}>
{children}
</SelectedProductsContext.Provider>
);
}; |
import { useForm } from "react-hook-form";
import "./Login.css";
import { CredentialsModel } from "../../../Models/CredentialsModel";
import { useNavigate } from "react-router-dom";
import { authService } from "../../../Services/AuthService";
import { notify } from "../../../Utils/Notify";
export function Login(): JSX.Element {
const { register, handleSubmit } = useForm<CredentialsModel>();
const navigate = useNavigate();
async function send(credentials: CredentialsModel) {
try {
await authService.login(credentials);
notify.success("Welcome Back!");
navigate("/home");
}
catch (err: any) {
notify.error(err);
}
}
return (
<div className="Login">
<form onSubmit={handleSubmit(send)}>
<label>Email:</label>
<input type="email" {...register("email")} />
<label>Password:</label>
<input type="password" {...register("password")} />
<button>Login</button>
</form>
</div>
);
} |
package com.example.artworksharingplatform.controller;
import java.sql.Timestamp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.artworksharingplatform.entity.Artworks;
import com.example.artworksharingplatform.entity.Order;
import com.example.artworksharingplatform.entity.User;
import com.example.artworksharingplatform.mapper.OrderMapper;
import com.example.artworksharingplatform.model.ApiResponse;
import com.example.artworksharingplatform.model.OrderDTO;
import com.example.artworksharingplatform.service.ArtworkService;
import com.example.artworksharingplatform.service.EWalletService;
import com.example.artworksharingplatform.service.OrderService;
import com.example.artworksharingplatform.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.GetMapping;
@RestController
@RequestMapping("api/auth/order")
public class OrderController {
@Autowired
OrderService orderService;
@Autowired
EWalletService eWalletService;
@Autowired
UserService userService;
@Autowired
ArtworkService artworkService;
@Autowired
OrderMapper orderMapper;
@PostMapping("add")
@PreAuthorize("hasRole('ROLE_AUDIENCE') or hasRole('ROLE_CREATOR')")
public ResponseEntity<ApiResponse<OrderDTO>> downloadArtwork(@RequestBody OrderDTO orderDTO) {
ApiResponse<OrderDTO> apiResponse = new ApiResponse<OrderDTO>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String email = userDetails.getUsername();
User user = userService.findByEmail(email);
try {
Artworks artworks = artworkService.geArtworksById(orderDTO.getArtwork().getArtId());
Order order = new Order();
order.setArtwork(artworks);
order.setAudience(user);
order.setOrderDate(new Timestamp(System.currentTimeMillis()));
order.setTotalPrice(orderDTO.getTotalPrice());
Order o = orderService.addOrder(order);
OrderDTO oDto = orderMapper.toOrderDTO(o);
apiResponse.ok(oDto);
return ResponseEntity.ok(apiResponse);
} catch (Exception e) {
apiResponse.error(e);
return new ResponseEntity<>(apiResponse, HttpStatus.BAD_REQUEST);
}
}
@GetMapping("viewList")
@PreAuthorize("hasRole('ROLE_AUDIENCE') or hasRole('ROLE_CREATOR')")
public ResponseEntity<ApiResponse<List<OrderDTO>>> viewOrdersList() {
ApiResponse<List<OrderDTO>> apiResponse = new ApiResponse<List<OrderDTO>>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String email = userDetails.getUsername();
User user = userService.findByEmail(email);
try {
List<Order> orders = orderService.getOrdersByUserId(user.getId());
List<OrderDTO> orderDTOs = orderMapper.toOrderDTOsList(orders);
apiResponse.ok(orderDTOs);
return ResponseEntity.ok(apiResponse);
} catch (Exception e) {
apiResponse.error(e);
return new ResponseEntity<>(apiResponse, HttpStatus.BAD_REQUEST);
}
}
} |
<?php
namespace core\services;
use core\daoimpl\CopsAutopsieDaoImpl;
use core\domain\CopsAutopsieClass;
/**
* Classe CopsAutopsieServices
* @author Hugues
* @since 1.22.10.09
* @version v1.23.08.12
*/
class CopsAutopsieServices extends LocalServices
{
// CONSTRUCT
/**
* Class constructor
* @since 1.22.10.09
* @version v1.23.07.29
*/
public function __construct()
{
$this->initDao();
}
// METHODS
private function initDao(): void
{
if ($this->objDao==null) {
$this->objDao = new CopsAutopsieDaoImpl();
}
}
/**
* @since 1.22.10.09
* @version v1.23.08.12
*/
public function getAutopsie(int $autopsieId=-1): CopsAutopsieClass
{
$objs = $this->objDao->getAutopsies([self::FIELD_ID=>$autopsieId]);
return empty($objs) ? new CopsAutopsieClass() : array_shift($objs);
}
/**
* @since 1.22.10.09
* @version v1.23.08.12
*/
public function getAutopsies(array $attributes=[]): array
{
$prepAttributes = [
$attributes[self::FIELD_ID] ?? self::SQL_JOKER_SEARCH,
$attributes[self::FIELD_IDX_ENQUETE] ?? self::SQL_JOKER_SEARCH,
$attributes[self::SQL_ORDER_BY] ?? self::FIELD_DSTART,
$attributes[self::SQL_ORDER] ?? self::SQL_ORDER_DESC,
$attributes[self::SQL_LIMIT] ?? 9999,
];
return $this->objDao->getAutopsies($prepAttributes);
}
/**
* @since 1.22.10.10
* @version v1.23.08.12
*/
public function updateAutopsie(CopsAutopsieClass $objCopsAutopsie): void
{ $this->objDao->updateAutopsie($objCopsAutopsie); }
/**
* @since 1.22.10.10
* @version v1.23.08.12
*/
public function insertAutopsie(CopsAutopsieClass &$objCopsAutopsie): void
{ $this->objDao->insertAutopsie($objCopsAutopsie); }
} |
import { useState } from 'react'
import PropTypes from 'prop-types'
import { Switch, makeStyles } from '@material-ui/core'
import Button from 'components/CustomButtons/Button.js'
import imagine1 from 'assets/img/sidebar-1.jpg'
import imagine2 from 'assets/img/sidebar-1.jpg'
import imagine3 from 'assets/img/sidebar-1.jpg'
import imagine4 from 'assets/img/sidebar-1.jpg'
import styles from 'assets/jss/material-ui-react/customCheckboxRadioSwitch'
const useStyles = makeStyles(styles)
const FixedPlugin = (props) => {
const classesObj = useStyles()
const [bgImage, setBgImage] = useState(props.bgImage)
const [showImage, setShowImage] = useState(false)
const handleClick = () => {
props.handleFixedClick()
}
const handleChange = (name) => (event) => {
switch (name) {
case 'miniActive':
props.sidebarMinimize()
break
case 'image':
if (event.target.checked) {
props.handleImageClick(bgImage)
} else {
props.handleImageClick()
}
setShowImage(event.target.checked)
break
default:
break
}
}
return (
<div className={'fixed-plugin' + (props.rtlActive ? ' fixed-plugin-rtl' : '')}>
<div id='fixedPluginClasses' className={props.fixedClasses}>
<div onClick={handleClick}>
<i className='fa fa-cog fa-2x' />
</div>
<ul className='dropdown-menu'>
<li className='header-title'>SIDEBAR FILTERS</li>
<li className='adjustments-line'>
<a className='switch-trigger active-color'>
<div className='badge-colors text-center'>
<span
className={
props.color === 'purple' ? 'badge filter badge-purple active' : 'badge filter badge-purple'
}
data-color='purple'
onClick={() => {
props.handleColorClick('purple')
}}
/>
<span
className={props.color === 'blue' ? 'badge filter badge-blue active' : 'badge filter badge-blue'}
data-color='blue'
onClick={() => {
props.handleColorClick('blue')
}}
/>
<span
className={props.color === 'green' ? 'badge filter badge-green active' : 'badge filter badge-green'}
data-color='green'
onClick={() => {
props.handleColorClick('green')
}}
/>
<span
className={props.color === 'red' ? 'badge filter badge-red active' : 'badge filter badge-red'}
data-color='red'
onClick={() => {
props.handleColorClick('red')
}}
/>
<span
className={
props.color === 'orange' ? 'badge filter badge-orange active' : 'badge filter badge-orange'
}
data-color='orange'
onClick={() => {
props.handleColorClick('orange')
}}
/>
<span
className={props.color === 'white' ? 'badge filter badge-white active' : 'badge filter badge-white'}
data-color='orange'
onClick={() => {
props.handleColorClick('white')
}}
/>
<span
className={props.color === 'rose' ? 'badge filter badge-rose active' : 'badge filter badge-rose'}
data-color='orange'
onClick={() => {
props.handleColorClick('rose')
}}
/>
</div>
<div className='clearfix' />
</a>
</li>
<li className='header-title'>SIDEBAR BACKGROUND</li>
<li className='adjustments-line'>
<a className='switch-trigger active-color'>
<div className='badge-colors text-center'>
<span
className={props.bgColor === 'blue' ? 'badge filter badge-blue active' : 'badge filter badge-blue'}
data-color='orange'
onClick={() => {
props.handleBgColorClick('blue')
}}
/>
<span
className={props.bgColor === 'white' ? 'badge filter badge-white active' : 'badge filter badge-white'}
data-color='orange'
onClick={() => {
props.handleBgColorClick('white')
}}
/>
<span
className={props.bgColor === 'black' ? 'badge filter badge-black active' : 'badge filter badge-black'}
data-color='orange'
onClick={() => {
props.handleBgColorClick('black')
}}
/>
</div>
<div className='clearfix' />
</a>
</li>
<li className='adjustments-line'>
<a className='switch-trigger'>
<p className='switch-label'>Sidebar Mini</p>
<Switch
checked={props.miniActive}
onChange={handleChange('miniActive')}
value='sidebarMini'
classes={{
switchBase: classesObj.switchBase,
checked: classesObj.switchChecked,
thumb: classesObj.switchIcon,
track: classesObj.switchBar,
}}
/>
<div className='clearfix' />
</a>
</li>
<li className='adjustments-line'>
<a className='switch-trigger'>
<p className='switch-label'>Sidebar Image</p>
<Switch
checked={showImage}
onChange={handleChange('image')}
value='sidebarMini'
classes={{
switchBase: classesObj.switchBase,
checked: classesObj.switchChecked,
thumb: classesObj.switchIcon,
track: classesObj.switchBar,
}}
/>
<div className='clearfix' />
</a>
</li>
<li className='header-title'>Images</li>
<li className={bgImage === imagine1 ? 'active' : ''}>
<a
className='img-holder switch-trigger'
onClick={() => {
setShowImage(true)
setBgImage(imagine1)
props.handleImageClick(imagine1)
}}
>
<img src={imagine1} alt='...' />
</a>
</li>
<li className={bgImage === imagine2 ? 'active' : ''}>
<a
className='img-holder switch-trigger'
onClick={() => {
setShowImage(true)
setBgImage(imagine2)
props.handleImageClick(imagine2)
}}
>
<img src={imagine2} alt='...' />
</a>
</li>
<li className={bgImage === imagine3 ? 'active' : ''}>
<a
className='img-holder switch-trigger'
onClick={() => {
setShowImage(true)
setBgImage(imagine3)
props.handleImageClick(imagine3)
}}
>
<img src={imagine3} alt='...' />
</a>
</li>
<li className={bgImage === imagine4 ? 'active' : ''}>
<a
className='img-holder switch-trigger'
onClick={() => {
setShowImage(true)
setBgImage(imagine4)
props.handleImageClick(imagine4)
}}
>
<img src={imagine4} alt='...' />
</a>
</li>
<li className='button-container'>
<div>
<Button color='warning' href='https://actividades.com' target='_blank' fullWidth>
Buy now
</Button>
</div>
</li>
<li className='button-container'>
<div>
<Button
color='info'
href='https://demos.creative-tim.com/material-ui-react/#/documentation/tutorial?ref=mdpr-fixed-plugin'
target='_blank'
fullWidth
>
Documentation
</Button>
</div>
</li>
<li className='header-title' id='sharrreTitle'>
Thank you for sharing!
<br />
</li>
</ul>
</div>
</div>
)
}
FixedPlugin.propTypes = {
bgImage: PropTypes.string,
handleFixedClick: PropTypes.func,
miniActive: PropTypes.bool,
fixedClasses: PropTypes.string,
bgColor: PropTypes.oneOf(['white', 'black', 'blue']),
color: PropTypes.oneOf(['white', 'red', 'orange', 'green', 'blue', 'purple', 'rose']),
handleBgColorClick: PropTypes.func,
handleColorClick: PropTypes.func,
handleImageClick: PropTypes.func,
sidebarMinimize: PropTypes.func,
rtlActive: PropTypes.bool,
}
export default FixedPlugin |
<?php
namespace Drupal\university\Entity;
use Drupal\Core\Entity\RevisionLogInterface;
use Drupal\Core\Entity\RevisionableInterface;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\user\EntityOwnerInterface;
/**
* Provides an interface for defining Course entities.
*
* @ingroup university
*/
interface CourseInterface extends RevisionableInterface, RevisionLogInterface, EntityChangedInterface, EntityOwnerInterface {
// Add get/set methods for your configuration properties here.
/**
* Gets the Course name.
*
* @return string
* Name of the Course.
*/
public function getName();
/**
* Sets the Course name.
*
* @param string $name
* The Course name.
*
* @return \Drupal\university\Entity\CourseInterface
* The called Course entity.
*/
public function setName($name);
/**
* Gets the Course creation timestamp.
*
* @return int
* Creation timestamp of the Course.
*/
public function getCreatedTime();
/**
* Sets the Course creation timestamp.
*
* @param int $timestamp
* The Course creation timestamp.
*
* @return \Drupal\university\Entity\CourseInterface
* The called Course entity.
*/
public function setCreatedTime($timestamp);
/**
* Returns the Course published status indicator.
*
* Unpublished Course are only visible to restricted users.
*
* @return bool
* TRUE if the Course is published.
*/
public function isPublished();
/**
* Sets the published status of a Course.
*
* @param bool $published
* TRUE to set this Course to published, FALSE to set it to unpublished.
*
* @return \Drupal\university\Entity\CourseInterface
* The called Course entity.
*/
public function setPublished($published);
/**
* Gets the Course revision creation timestamp.
*
* @return int
* The UNIX timestamp of when this revision was created.
*/
public function getRevisionCreationTime();
/**
* Sets the Course revision creation timestamp.
*
* @param int $timestamp
* The UNIX timestamp of when this revision was created.
*
* @return \Drupal\university\Entity\CourseInterface
* The called Course entity.
*/
public function setRevisionCreationTime($timestamp);
/**
* Gets the Course revision author.
*
* @return \Drupal\user\UserInterface
* The user entity for the revision author.
*/
public function getRevisionUser();
/**
* Sets the Course revision author.
*
* @param int $uid
* The user ID of the revision author.
*
* @return \Drupal\university\Entity\CourseInterface
* The called Course entity.
*/
public function setRevisionUserId($uid);
} |
function output=getGlobalParameters(var_name_str,field_name_str)
% gets global parameters for more flexible config file setups.
% function output=getGlobalParameters(var_name_str,:field_name_str)
% (: is optional)
%
% This function returns the global parameter or its field value(s).
% The returned value(s) can be used to set the parameters in the
% config files with more flexibility.
%
% [input]
% var_name_str : the name of the global variable you want to get, string.
% currently, the acceptable variable name is one of
% 'subj', 'acq', 'session', 'vparam', 'dparam', 'prt', and 'imgs'.
% field_name_str : (optional) the field name of the var_name_str, string.
%
% [output]
% output : output variable or field value you want to extract.
%
% [note]
% Please use this function is your protocolfile, imgdbfile, viewfile, or optionfile.
% Then you can use the global parameters as references, which enables users to create
% config files with more flexiblity.
%
%
% Created : "2015-07-14 13:42:40 ban"
% Last Update: "2015-07-14 13:55:13 ban"
global subj acq session vparam dparam prt imgs; %#ok
% check input variable
if nargin<1 || isempty(var_name_str), help(mfilename()); return; end
if nargin<2 || isempty(field_name_str), field_name_str=''; end
if ~ismember(var_name_str,{'subj', 'acq', 'session', 'vparam', 'dparam', 'prt','imgs'})
error('var_name_str should be one of ''subj'', ''acq'', ''session'', ''vparam'', ''dparam'', ''prt'', and ''imgs''. check input variable.');
end
if ~isempty(field_name_str)
output=eval(sprintf('%s.%s;',var_name_str,field_name_str));
else
output=eval(sprintf('%s;',var_name_str));
end
return |
/**
* _strstr - a function that locates a substring
*
* @haystack: input string to search for similar
* substrings
* @needle: subtring to search for
*
* Return: a pointer to the beginning
* of the located substring or
* NULL if substring wasn't found
*/
char *_strstr(char *haystack, char *needle)
{
/**
* We set up a helping variable
* to aid us retrieve
* our parameter references haystack
*/
char *h, *n;
while (*haystack != '\0')
{
h = haystack;
n = needle;
while (*n != '\0' && *haystack == *n)
{
haystack++;
n++;
}
if (!*n)
return (h);
haystack++;
}
return ('\0');
} |
#include <stdio.h>
#include <stdlib.h>
#include "dog.h"
/**
* print_dog - prints the details of an instance of a dog
* @d: the dog in question
*/
void print_dog(struct dog *d)
{
if (d == NULL)
{
return;
}
if (d->name == NULL)
{
printf("Name: (nil)\n");
}
else
{
printf("Name: %s\n", d->name);
}
printf("Age: %f\n", d->age);
if (d->owner == NULL)
{
printf("Owner: (nil)\n");
}
else
{
printf("Owner: %s\n", d->owner);
}
} |
package com.example.cocina.JWT;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
//La clase abstracta sirve para crear filtros personalizdos
//Tambien hace que el filtro se ejecute solo 1 vez por cada solicitud HTTP
@Component
public class jwtAuthFilter extends OncePerRequestFilter {
@Autowired
private JwtServicio jwtServicio;
@Autowired
private UserDetailsService userDetailsService;
//Este el metodo/filtro que va a comprobar el JWT este bien formado.
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
final String token = getTokenRequest(request);
final String username;
if(token == null) {
filterChain.doFilter(request, response);
return;
}
username = jwtServicio.getUsernameFromToken(token);
if(username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userdetails = userDetailsService.loadUserByUsername(username);
if(jwtServicio.isTokenValid(token, userdetails)) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userdetails,null,userdetails.getAuthorities());
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);
}
//Metodo para obtener el JWT
private String getTokenRequest(HttpServletRequest request) {
final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
if(StringUtils.hasText(authHeader) && authHeader.startsWith("Bearer ")) {
return authHeader.substring(7);
}
return null;
}
} |
package com.fa.sonagi.record.health.repository;
import static com.fa.sonagi.record.health.entity.QFever.*;
import java.time.LocalDate;
import java.util.Map;
import java.util.stream.Collectors;
import com.fa.sonagi.record.health.dto.FeverResDto;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.MathExpressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class FeverRepositoryImpl implements FeverRepositoryCustom {
private final JPAQueryFactory queryFactory;
@Override
public FeverResDto findFeverRecord(Long feverId) {
FeverResDto fevers = queryFactory
.select(Projections.bean(FeverResDto.class,
fever.id.as("healthId"),
fever.createdTime,
fever.bodyTemperature,
fever.memo))
.from(fever)
.where(fever.id.eq(feverId))
.fetchOne();
return fevers;
}
@Override
public Double findFeverAvg(Long babyId, LocalDate createdDate) {
Double bodyTemperature = queryFactory
.select(MathExpressions.round(fever.bodyTemperature.avg(), 1).coalesce((double)0))
.from(fever)
.where(fever.babyId.eq(babyId), fever.createdDate.eq(createdDate))
.fetchOne();
return bodyTemperature;
}
@Override
public Map<LocalDate, Double> findFeverAvg(Long babyId, LocalDate monday, LocalDate sunday) {
Map<LocalDate, Double> bodyTemperatures = queryFactory
.select(fever.createdDate,
MathExpressions.round(fever.bodyTemperature.avg(), 1).coalesce((double)0))
.from(fever)
.where(fever.babyId.eq(babyId),
fever.createdDate.goe(monday), fever.createdDate.loe(sunday))
.groupBy(fever.createdDate)
.fetch()
.stream()
.collect(Collectors.toMap(
tuple -> tuple.get(fever.createdDate),
tuple -> tuple.get(MathExpressions.round(fever.bodyTemperature.avg(), 1).coalesce((double)0))
));
return bodyTemperatures;
}
@Override
public Double findFeverAvgByWeek(Long babyId, LocalDate monday, LocalDate sunday) {
Double bodyTemperature = queryFactory
.select(MathExpressions.round(fever.bodyTemperature.avg(), 1).coalesce((double)0))
.from(fever)
.where(fever.babyId.eq(babyId),
fever.createdDate.goe(monday), fever.createdDate.loe(sunday))
.fetchFirst();
return bodyTemperature;
}
} |
* {
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
body {
background: linear-gradient(112deg,rgb(1, 85, 129) 30%,rgb(238, 47, 47) 100%);
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
width: 80%;
height: 70%;
position: relative;
box-shadow: 0 0 1rem 0 rgba(0, 0, 0, 0.2);
border-radius: 20px;
background: inherit;
overflow: hidden;
z-index: 1;
display: flex;
flex-direction: column;
}
.container:before {
content: "";
position: absolute;
background: inherit;
z-index: -1;
top: 0;
left: 0;
right: 0;
bottom: 0;
box-shadow: inset 0 0 2000px rgba(255, 255, 255, 0.5);
filter: blur(10px);
margin: -20px;
}
header {
display: flex;
justify-content: space-between;
padding: 15px 30px;
font-weight: bold;
ul {
list-style: none;
display: flex;
color: white;
padding: 0;
li {
margin: 0 15px;
display: flex;
align-items: center;
// &.active {
// background: #de0108;
// padding: 3px 15px;
// border-radius: 8px;
// }
}
a{
text-decoration: none;
color: white;
}
a:hover{
background: #de0108;
padding: 3px 15px;
border-radius: 8px;
transition-duration: 1s;
transform: scale3d(1.5,1.5,1.5);
}
}
}
.content {
display: flex;
height: 100%;
align-items: center;
position: relative;
img {
position: absolute;
width: 20%;
top: 50%;
left: 52%;
transform: translate(-50%, -50%) ;
animation: move 2s infinite alternate ease-in-out;
border-radius: 5px;
}
.social-media {
display: flex;
flex-direction: column;
justify-content: center;
width: fit-content;
height: 100%;
color: white;
a{
color: white;
}
a:hover{
transform: scale3d(1.5,1.5,1.5);
}
svg {
margin: 15px 30px;
}
}
&-text {
color: white;
width: 100%;
padding: 0 50px;
h1,
h3 {
margin: 0;
}
h1 {
font-size: 56px;
}
&.right {
text-align: right;
margin-top: 170px;
}
&.left {
margin-top: -300px;
}
}
}
.pre-order {
background: #de0108;
margin-left: auto;
width: 200px;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: bold;
border-radius: 8px 0 0 0;
svg {
margin-right: 15px;
}
}
@keyframes move {
from {
transform: translate(-50%, -55%);
}
} |
package com.santechture.api.security;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.stereotype.Component;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import javax.annotation.PostConstruct;
import org.apache.commons.codec.*;
@Component
public class JwtTokenProvider {
@Value("${lifeTimeToken.in.milliseconds}")
Integer validityInMs;
@Autowired
JwtProperties jwtProperties;
private PrivateKey privateKey;
private PublicKey publicKey;
@PostConstruct
protected void init() throws NoSuchAlgorithmException, DecoderException, InvalidKeySpecException {
KeyFactory kf = KeyFactory.getInstance("RSA");
byte[] privateKeyBinary = Hex.decode(jwtProperties.getPrivateKey());
PKCS8EncodedKeySpec privateSpecs = new PKCS8EncodedKeySpec(privateKeyBinary);
privateKey = kf.generatePrivate(privateSpecs);
byte[] publicKeyBinary = Hex.decode(jwtProperties.getPublicKey());
X509EncodedKeySpec pubSpecs = new X509EncodedKeySpec(publicKeyBinary);
publicKey = kf.generatePublic(pubSpecs);
}
public String getUsername(String token) {
return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token).getBody().getSubject();
}
public boolean validate(String token) {
if (getUsername(token) != null && isExpired(token)) {
return true;
}
return false;
}
public String generate(String username) {
Date now = new Date();
Date validity = new Date(now.getTime() + validityInMs);
return Jwts.builder()//
.setSubject(username)
// .setClaims(claims)//
.setIssuedAt(new Date(System.currentTimeMillis()))//
.setExpiration(validity)//
.signWith(SignatureAlgorithm.RS256, privateKey)//
.compact();
}
public boolean isExpired(String token) {
Claims claims = getClaims(token);
return claims.getExpiration().after(new Date(System.currentTimeMillis()));
}
private Claims getClaims(String token) {
return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token).getBody();
}
} |
package tobyboot.helloboot;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
@Configuration
@ComponentScan
public class HellobootApplication {
@Bean
public ServletWebServerFactory servletWebServerFactory() {
return new TomcatServletWebServerFactory();
}
@Bean
public DispatcherServlet dispatcherServlet() {
return new DispatcherServlet();
}
public static void main(String[] args) {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext() {
@Override
protected void onRefresh() {
super.onRefresh();
ServletWebServerFactory serverF = this.getBean(ServletWebServerFactory.class);
DispatcherServlet dispatcherServlet = this.getBean(DispatcherServlet.class);
// dispatcherServlet.setApplicationContext(this); //spring container가 주입해준다!
WebServer webServer = serverF.getWebServer(servletContext -> {
servletContext.addServlet("dispatcher_servlet",
new DispatcherServlet(this)
).addMapping("/*");
});
webServer.start();
}
};
applicationContext.register(HellobootApplication.class);
applicationContext.refresh();
}
} |
import {Command} from "../abstract/command";
import {Mediator} from "./mediator";
//Colega Concreto
export class TurnOnAllLightsCommand implements Command {
private mediator: Mediator;
constructor(mediator: Mediator) {
this.mediator = mediator;
}
public execute(): void {
this.mediator.turnOnAllLights();
}
} |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
import 'package:travel_booking/constants/app_colors.dart' as appcolors;
import 'package:travel_booking/providers/holiday_package_view_model.dart';
import 'package:travel_booking/providers/hotel_view_model.dart';
import 'package:travel_booking/widgets/hotel_card.dart';
import 'package:travel_booking/widgets/package_card.dart';
import '../../../providers/day_coun_provider.dart';
import '../../../widgets/custom_button.dart';
import '../../../widgets/custom_date_picker.dart';
import '../../../widgets/custom_slider.dart';
import '../../../widgets/date_formatter.dart';
import '../../../widgets/date_picker.dart';
class HolidayPackageScreen extends StatefulWidget {
const HolidayPackageScreen({super.key});
@override
_HolidayPackageScreenState createState() => _HolidayPackageScreenState();
}
class _HolidayPackageScreenState extends State<HolidayPackageScreen> {
final TextEditingController _checkInDateController = TextEditingController();
final TextEditingController _checkOutDateController = TextEditingController();
String? initialDate, finalDate;
dayCountProvider() async {
_checkInDateController.text = dateFormatter(
Provider.of<DayCounter>(context, listen: false).initialDate!);
_checkOutDateController.text = dateFormatter(
Provider.of<DayCounter>(context, listen: false).finalDate!);
finalDate = _checkOutDateController.text;
initialDate = _checkInDateController.text;
}
late HolidayPackageViewModel _holidayPackageViewModel;
@override
void initState() {
// TODO: implement initState
WidgetsBinding.instance.addPostFrameCallback((_) {
_holidayPackageViewModel = Provider.of<HolidayPackageViewModel>(context, listen: false);
_holidayPackageViewModel.getHolidayPackage();
});
super.initState();
}
@override
void didChangeDependencies() {
dayCountProvider();
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Holiday Package'),
elevation: 5,
automaticallyImplyLeading: false,
centerTitle: true,
),
body: SingleChildScrollView(
padding: const EdgeInsets.only(top: 24, left: 20, right: 20),
child: Column(
children: [
Consumer<HolidayPackageViewModel>(builder: (context, packages, child) {
return GridView.count(
crossAxisSpacing: 10,
mainAxisSpacing: 10,
childAspectRatio: 0.7,
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
crossAxisCount: 2,
children: [
...packages.holidayPackage.map((e) => HolidayPackageCard(
e: e,
))
],
);
}),
],
),
));
}
} |
var crypto = require('crypto');
var async = require('async');
var util = require('util');
var mongoose = require('libs/mongoose'),
Schema = mongoose.Schema;
var user = new Schema({
username: {
type: String,
unique: true,
required: true
},
hashedPassword: {
type: String,
required: true
},
salt: {
type: String,
required: true
},
created: {
type: Date,
default: Date.now
}
});
user.methods.encryptPassword = function(password) {
return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
};
user.virtual('password')
.set(function(password) {
this._plainPassword = password;
this.salt = Math.random() + '';
this.hashedPassword = this.encryptPassword(password);
})
.get(function() { return this._plainPassword; });
user.methods.checkPassword = function(password) {
return this.encryptPassword(password) === this.hashedPassword;
};
user.statics.authorize = function(username, password, callback) {
var User = this;
async.waterfall([
function(callback) {
User.findOne({username: username}, callback);
},
function(user, callback) {
if (user) {
if (user.checkPassword(password)) {
callback(null, user);
} else {
callback(new AuthError("Password is illegal"));
}
} else {
var user = new User({username: username, password: password});
user.save(function(err) {
if (err) return callback(err);
callback(null, user);
});
}
}
], callback);
};
exports.User = mongoose.model('User', user);
function AuthError(message) {
Error.apply(this, arguments);
Error.captureStackTrace(this, AuthError);
this.message = message;
}
util.inherits(AuthError, Error);
AuthError.prototype.name = 'AuthError';
exports.AuthError = AuthError; |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:get/get.dart';
import 'package:tickets/utils/app_styles.dart';
import 'package:tickets/widgets/thick_container.dart';
import '../utils/app_layout.dart';
class TicketView extends StatelessWidget {
final Map<String, dynamic> ticket;
final bool? isColor;
const TicketView({
Key? key,
required this.ticket,
this.isColor,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final size = AppLayout.getSize(context);
return SizedBox(
width: size.width * 0.85,
height: AppLayout.getHeight(GetPlatform.isAndroid == true ? 180 : 200),
child: Container(
margin: EdgeInsets.only(right: AppLayout.getHeight(16)),
child: Column(
children: [
Container(
decoration: BoxDecoration(
color:
isColor == null ? const Color(0xFF526799) : Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(AppLayout.getHeight(21)),
topRight: Radius.circular(AppLayout.getHeight(21)))),
padding: EdgeInsets.all(AppLayout.getHeight(16)),
child: Column(
children: [
Row(
children: [
Text(
ticket['from']['code'],
style: isColor == null
? Styles.headLineStyle3
.copyWith(color: Colors.white)
: Styles.headLineStyle3
.copyWith(color: Colors.black),
),
Expanded(child: Container()),
const ThickContainer(
isColor: true,
),
Expanded(
child: Stack(
children: [
SizedBox(
height: AppLayout.getHeight(24),
child: LayoutBuilder(
builder: (BuildContext context,
BoxConstraints constraints) {
print(
"the width is ${constraints.constrainWidth()}");
return Flex(
direction: Axis.horizontal,
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: List.generate(
((constraints.constrainWidth() / 6)
.floor()),
(index) => SizedBox(
width: AppLayout.getWidth(3),
height: AppLayout.getHeight(1),
child: DecoratedBox(
decoration: BoxDecoration(
color: isColor == null
? Colors.white
: Colors.black),
),
),
),
);
},
),
),
Center(
child: Transform.rotate(
angle: 1.5,
child: Icon(
Icons.local_airport_rounded,
color: isColor == null
? Colors.white
: Colors.red,
),
),
),
],
),
),
const ThickContainer(
isColor: true,
),
const Spacer(),
Text(
ticket['to']['code'],
style: isColor == null
? Styles.headLineStyle3
.copyWith(color: Colors.white)
: Styles.headLineStyle3
.copyWith(color: Colors.black),
),
],
),
const Gap(3),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
width: AppLayout.getWidth(100),
child: Text(
ticket['from']['name'],
style: isColor == null
? Styles.headLineStyle4
.copyWith(color: Colors.white)
: Styles.headLineStyle4
.copyWith(color: Colors.grey),
),
),
Text(
ticket['flying_time'],
style: Styles.headLineStyle3.copyWith(
color:
isColor == null ? Colors.white : Colors.black),
),
SizedBox(
width: AppLayout.getWidth(100),
child: Text(
ticket['to']['name'],
textAlign: TextAlign.end,
style: isColor == null
? Styles.headLineStyle4.copyWith(
color: Colors.white,
)
: Styles.headLineStyle4.copyWith(
color: Colors.grey,
),
),
),
],
),
],
),
),
Container(
color: isColor == null
? const Color.fromARGB(255, 233, 127, 41)
: Colors.white,
child: Row(
children: [
SizedBox(
height: AppLayout.getHeight(20),
width: AppLayout.getWidth(10),
child: const DecoratedBox(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topRight: Radius.circular(10),
bottomRight: Radius.circular(10),
),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(11.0),
child: LayoutBuilder(
builder:
(BuildContext context, BoxConstraints constraints) {
return Flex(
direction: Axis.horizontal,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: List.generate(
((constraints.constrainWidth() / 15).floor()),
(index) => SizedBox(
width: AppLayout.getWidth(5),
height: AppLayout.getHeight(2),
child: DecoratedBox(
decoration: BoxDecoration(
color: isColor == null
? Colors.white
: Colors.grey),
),
),
),
);
},
),
),
),
SizedBox(
height: AppLayout.getHeight(20),
width: AppLayout.getWidth(10),
child: const DecoratedBox(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
bottomLeft: Radius.circular(10),
),
),
),
),
],
),
),
Container(
decoration: BoxDecoration(
color: isColor == null
? Color.fromARGB(255, 233, 127, 41)
: Colors.white,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(isColor == null ? 21 : 0),
bottomRight: Radius.circular(isColor == null ? 21 : 0),
),
),
padding: const EdgeInsets.only(
left: 16, top: 10, right: 16, bottom: 16),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
ticket['date'],
style: Styles.headLineStyle3.copyWith(
color: isColor == null
? Colors.white
: Colors.black),
),
const Gap(5),
Text(
"Date",
style: Styles.headLineStyle4.copyWith(
color: isColor == null
? Colors.white
: Colors.grey),
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
ticket['departure_time'],
style: Styles.headLineStyle3.copyWith(
color: isColor == null
? Colors.white
: Colors.black),
),
const Gap(5),
Text(
"Departure Time",
style: Styles.headLineStyle4.copyWith(
color: isColor == null
? Colors.white
: Colors.grey),
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
ticket['number'].toString(),
style: Styles.headLineStyle3.copyWith(
color: isColor == null
? Colors.white
: Colors.black),
),
const Gap(5),
Text(
"Number",
style: Styles.headLineStyle4.copyWith(
color: isColor == null
? Colors.white
: Colors.grey),
),
],
),
],
)
],
),
),
],
),
),
);
}
} |
package io.locarro
import grails.rest.*
import grails.converters.*
import grails.validation.ValidationException
import static org.springframework.http.HttpStatus.*
class PagamentoController extends RestfulController<Pagamento> {
PagamentoService pagamentoService
static responseFormats = ['json', 'xml']
static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
PagamentoController() {
super(Pagamento)
}
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
respond pagamentoService.list(params), model:[pagamentoCount: pagamentoService.count()]
}
def show(Long id) {
respond pagamentoService.get(id)
}
def create() {
respond new Pagamento(params)
}
def save(Pagamento pagamento) {
if (pagamento == null) {
notFound()
return
}
try {
pagamentoService.save(pagamento)
} catch (ValidationException e) {
respond pagamento.errors, view:'create'
return
}
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.created.message', args: [message(code: 'pagamento.label', default: 'Pagamento'), pagamento.id])
redirect pagamento
}
'*' { respond pagamento, [status: CREATED] }
}
}
def edit(Long id) {
respond pagamentoService.get(id)
}
def update(Pagamento pagamento) {
if (pagamento == null) {
notFound()
return
}
try {
pagamentoService.save(pagamento)
} catch (ValidationException e) {
respond pagamento.errors, view:'edit'
return
}
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.updated.message', args: [message(code: 'pagamento.label', default: 'Pagamento'), pagamento.id])
redirect pagamento
}
'*'{ respond pagamento, [status: OK] }
}
}
def delete(Long id) {
if (id == null) {
notFound()
return
}
pagamentoService.delete(id)
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.deleted.message', args: [message(code: 'pagamento.label', default: 'Pagamento'), id])
redirect action:"index", method:"GET"
}
'*'{ render status: NO_CONTENT }
}
}
protected void notFound() {
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'pagamento.label', default: 'Pagamento'), params.id])
redirect action: "index", method: "GET"
}
'*'{ render status: NOT_FOUND }
}
}
} |
import { CssBaseline } from '@material-ui/core';
import { ThemeProvider } from '@material-ui/styles';
import App, { Container } from 'next/app';
import Head from 'next/head';
import React from 'react';
import theme from '../theme';
class MyApp extends App {
componentDidMount() {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles) {
jssStyles.parentNode.removeChild(jssStyles);
}
}
render() {
const { Component, pageProps } = this.props;
return (
<Container>
<Head>
<title>Page Title</title>
</Head>
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</Container>
);
}
}
export default MyApp; |
#pragma once
#include <glew.h>
#include <glm/glm.hpp>
#include <vector>
#include <stack>
using namespace glm;
struct Vertex
{
vec3 position;
vec2 uv;
Vertex(vec3 pos, vec2 u)
: position(pos), uv(u)
{ }
};
struct Material
{
int materialID;
GLuint shader;
GLuint texture;
};
struct Sprite
{
Material* material;
vec3 position;
vec2 size;
};
struct Batch
{
int renderObjectCount = 0;
Material* material;
std::vector<Vertex> vertDatas;
std::vector<GLuint> indices;
GLuint vertexBuffer;
GLuint indexBuffer;
void add(const std::vector<Vertex>& vertices, const std::vector<GLuint>& index)
{
for (int i = 0; i < vertices.size(); ++i)
{
vertDatas.push_back(vertices[i]);
}
int offset = renderObjectCount * vertices.size();
for (int i = 0; i < index.size(); ++i)
{
indices.push_back(index[i] + offset);
}
++renderObjectCount;
}
};
class BatchRenderer
{
private:
int currentID = -1;
std::stack<Batch> _batches;
public:
void addSprite(Sprite* sprite)
{
if (currentID != sprite->material->materialID)
{
currentID = sprite->material->materialID;
_batches.push(Batch());
_batches.top().material = sprite->material;
}
vec3 baseVertices[] =
{
vec3(1.0f, 1.0f, 0.0f),
vec3(1.0f, 0.0f, 0.0f),
vec3(0.0f, 0.0f, 0.0f),
vec3(0.0f, 1.0f, 0.0f),
};
vec2 baseUV[] =
{
vec2(1.0f, 1.0f),
vec2(1.0f, 0.0f),
vec2(0.0f, 0.0f),
vec2(0.0f, 1.0f)
};
GLuint baseIndices[] =
{
0, 1, 3,
1, 2, 3
};
mat4 model;
model = glm::translate(model, sprite->position);
model = glm::scale(model, vec3(sprite->size.x, sprite->size.y, 1.0f));
for (int i = 0; i < 4; ++i)
{
vec3 vert = VectorMultiple(model, baseVertices[i]);
_batches.top().vertDatas.push_back(Vertex(vert, baseUV[i]));
}
int offset = _batches.top().renderObjectCount * _batches.top().vertDatas.size();
for (int i = 0; i < 6; ++i)
{
_batches.top().indices.push_back(baseIndices[i] + offset);
}
++_batches.top().renderObjectCount;
}
void render(mat4 pv)
{
while (!_batches.empty())
{
Batch temp = _batches.top();
setBatchShaderUniform(temp.material->shader, pv);
// Bind vertex buffer
glGenBuffers(1, &temp.vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, temp.vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, temp.vertDatas.size() * sizeof(temp.vertDatas[0]), temp.vertDatas.data(), GL_DYNAMIC_DRAW);
glGenBuffers(1, &temp.indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, temp.indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, temp.indices.size() * sizeof(GLuint), temp.indices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (const GLvoid*)offsetof(Vertex, position));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (const GLvoid*)offsetof(Vertex, uv));
glBindTexture(GL_TEXTURE_2D, temp.material->texture);
glDrawElements(GL_TRIANGLES, temp.indices.size(), GL_UNSIGNED_INT, 0);
glDeleteBuffers(1, &temp.vertexBuffer);
glDeleteBuffers(1, &temp.indexBuffer);
_batches.pop();
}
currentID = -1;
}
void setBatchShaderUniform(GLuint shader, mat4 pv)
{
glUseProgram(shader);
shaderUniform(shader, "ML_PV", pv);
shaderUniform(shader, "ML_COLOR", vec4(1.0f, 1.0f, 1.0f, 1.0f));
}
}; |
import { yupResolver } from '@hookform/resolvers/yup';
import React from 'react';
import './style.scss';
import { Controller, useForm, useFormState } from 'react-hook-form';
import { ContentWrapper } from '../../../../components';
import { EditSchema } from '../../../../validates';
import { FormTitle } from '../../../Home/components';
import defaultAvatar from '../../../../images/Logo128.png';
import Select from 'react-select';
import addressApi from '../../../../apis/Apis/addressApi';
import { ColorLabel } from '../../../../components/PinkLabel';
import { IUpdateUserBody } from '../../../../apis/body/authBody';
import authApi from '../../../../apis/Apis/authApi';
import { notifyError, notifySuccess } from '../../../../utils/notify';
import { getDownloadURL, ref, uploadBytesResumable } from '@firebase/storage';
import storage from '../../../../firebase';
import { DEFAULT_AVATAR } from '../../../../static/DefaultAvatar';
interface ProfileProps {
displayName?: string;
phone?: string;
avatar?: string;
address?: string;
code?: string;
}
export const Profile = (props: ProfileProps) => {
const { displayName, phone, avatar, address, code } = props;
const [options, setOptions] = React.useState([]);
const [editAvatar, setEditAvatar] = React.useState(false);
const avatarInput = React.useRef<any>(null);
const {
register,
handleSubmit,
formState: { errors, isSubmitting, isDirty },
control,
reset,
} = useForm({
resolver: yupResolver(EditSchema),
defaultValues: {
displayName: displayName,
phone: phone,
address: address,
code: code,
avatar: avatar,
},
});
React.useEffect(() => {
const getAddress = async () => {
const res: any = await addressApi.getAllAddress();
const newOptions = res.data.map((e: any) => ({
value: e.code,
label: `${e.address} (${
e.key === 'PTN' ? 'Nội thành' : 'Ngoại thành'
})`,
}));
setOptions(newOptions);
};
getAddress();
}, []);
const onAvatarClick = () => {
avatarInput.current.click();
};
const showNewAvatar = async () => {
const validImageTypes = [
'image/jpg',
'image/jpeg',
'image/png',
'image/svg',
];
if (!validImageTypes.includes(avatarInput.current.files[0].type)) {
notifyError('File không phải hình ảnh');
} else if (avatarInput.current.files && avatarInput.current.files[0]) {
const reader = new FileReader();
reader.onload = function (e: any) {
setEditAvatar(true);
document
.getElementById('user-avatar')!
.setAttribute('src', e.target.result);
};
reader.readAsDataURL(avatarInput.current.files[0]);
}
};
const uploadAvatar = () => {
const storageRef = ref(
storage,
'images/' + avatarInput.current.files[0].name
);
const uploadTask = uploadBytesResumable(
storageRef,
avatarInput.current.files[0]
);
uploadTask.on(
'state_changed',
(snapshot: any) => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
},
(error: any) => {
switch (error.code) {
case 'storage/unauthorized':
console.log(
"User doesn't have permission to access the object"
);
break;
case 'storage/canceled':
console.log('User canceled the upload');
break;
case 'storage/unknown':
console.log(
'Unknown error occurred, inspect error.serverResponse'
);
break;
}
},
() => {
getDownloadURL(uploadTask.snapshot.ref).then(
(downloadURL: string) => {
setTimeout(async () => {
const body: IUpdateUserBody = {
displayName: displayName,
phone: phone,
address: address,
avatar: downloadURL,
code: code,
};
const res: any = await authApi.updateUser(body);
if (res.data) {
notifySuccess(
'Cập nhật ảnh đại diện thành công'
);
setEditAvatar(false);
} else {
notifyError('Cập nhật ảnh đại diện thất bại');
}
}, 1000);
}
);
}
);
};
const onSubmit = (data: any, e: any) => {
e.preventDefault();
return new Promise((resolve) => {
setTimeout(async () => {
const body: IUpdateUserBody = {
displayName: data.displayName,
phone: data.phone,
address: data.address,
avatar: DEFAULT_AVATAR,
code: data.code,
};
const res: any = await authApi.updateUser(body);
if (res.data) {
notifySuccess('Cập nhật thành công');
} else {
notifyError('Cập nhật thất bại');
}
resolve(true);
}, 2000);
});
};
return (
<ContentWrapper>
<form onSubmit={handleSubmit(onSubmit)}>
<FormTitle title="THÔNG TIN CÁ NHÂN" center />
<div className="d-flex profile">
<div className="profile-avatar d-flex flex-column align-items-center p-2">
<div className="avatar-container mb-3">
<img
src={avatar || defaultAvatar}
id="user-avatar"
/>
<input
type="file"
id="file"
accept=".jpg,.png,.jpeg"
ref={avatarInput}
onChange={showNewAvatar}
hidden
/>
</div>
<button
type="button"
className="btn btn-primary mb-3"
onClick={onAvatarClick}
>
Chọn ảnh đại diện
</button>
{editAvatar && (
<button
type="button"
className="btn btn-success"
onClick={uploadAvatar}
>
{!isSubmitting ? (
'Lưu ảnh'
) : (
<span
className="spinner-border spinner-border-sm"
role="status"
aria-hidden="true"
></span>
)}
</button>
)}
<p>* Nên chọn ảnh vuông để hiển thị tốt hơn</p>
</div>
<div className="profile-info p-2">
<div className="form-group mb-2">
<ColorLabel title="Tên của bạn" for="displayName" />
<input
type="text"
className="form-control"
{...register('displayName')}
id="displayName"
placeholder="Tên của bạn"
/>
<p className="text-danger">
{errors.displayName?.message}
</p>
</div>
<div className="form-group mb-2">
<ColorLabel title="Số điện thoại" for="phone" />
<input
type="text"
className="form-control"
{...register('phone')}
id="phone"
placeholder="Số điện thoại"
/>
<p className="text-danger">
{errors.phone?.message}
</p>
</div>
<div className="form-group mb-2">
<ColorLabel title="Địa chỉ" for="address" />
<input
type="text"
className="form-control"
{...register('address')}
id="address"
placeholder="Địa chỉ"
/>
<p className="text-danger">
{errors.address?.message}
</p>
</div>
<div className="form-group mb-2">
<ColorLabel title="Khu vực" for="code" />
<Controller
control={control}
name="code"
render={({
field: { onChange, onBlur, value, name },
}) => (
<Select
name={name}
id="code"
options={options}
value={options?.find(
(option: any) =>
option.value === value
)}
onChange={(val: any) =>
onChange(val.value)
}
onBlur={onBlur}
/>
)}
/>
<p className="text-danger">
{errors.code?.message}
</p>
</div>
<button
type="submit"
className="btn btn-success me-3"
disabled={!isDirty}
>
{!isSubmitting ? (
'Lưu thông tin'
) : (
<span
className="spinner-border spinner-border-sm"
role="status"
aria-hidden="true"
></span>
)}
</button>
<button
type="button"
className="btn btn-primary"
onClick={() => reset()}
disabled={!isDirty}
>
<i className="bi bi-arrow-repeat"></i> Reset
</button>
</div>
</div>
</form>
</ContentWrapper>
);
}; |
#include <stdlib.h>
/*
* matrix manipulation.
*
* types defined : matrix
* prefix used for functions : matrix_.
*
*/
typedef struct matrix {
size_t lines;
size_t cols;
double *values;
} matrix;
matrix *matrix_new(size_t lines, size_t cols, double init_value);
matrix *matrix_new_id(size_t n);
void matrix_free(matrix *m);
void matrix_print(matrix *m);
/* helpers */
matrix *matrix_set_value(matrix *m, size_t l, size_t c, double value);
matrix *matrix_set_values(matrix *m, double *values);
matrix *matrix_set_all(matrix *m, double value);
double matrix_get_value(matrix *m, size_t l, size_t c);
double *matrix_get_value_pointer(matrix *m, size_t l, size_t c);
/* operations on matrices */
matrix *matrix_copy(matrix *m);
matrix *matrix_add(matrix *m1, matrix *m2);
matrix *matrix_sub(matrix *m1, matrix *m2);
matrix *matrix_mult(matrix *m1, matrix *m2);
matrix *matrix_mult_scal(matrix *m, double scal);
/* decide wether 2 matrices are identical based on the given double equality function given */
int matrix_equal(matrix *m1, matrix *m2, int (*double_equal)(double, double)); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.