text
stringlengths 184
4.48M
|
---|
# HTMLAreaElement.pathname
The `HTMLAreaElement.pathname` property is a [`USVString`](../usvstring) containing an initial `'/'` followed by the path of the URL not including the query string or fragment (or the empty string if there is no path).
## Syntax
// Getter
string = area.pathname;
// Setter
area.pathname = string;
## Examples
// An <area id="myArea" href="/en-US/docs/HTMLAreaElement"> element is in the document
const area = document.getElementById("myArea");
area.pathname; // returns '/en-US/docs/HTMLAreaElement'
## Specifications
<table><thead><tr class="header"><th>Specification</th></tr></thead><tbody><tr class="odd"><td><a href="https://html.spec.whatwg.org/multipage/#dom-hyperlink-pathname">HTML Living Standard<br />
<span class="small">The definition of 'HTMLHyperlinkElementUtils.pathname' in that specification.</span></a></td></tr></tbody></table>
## Browser compatibility
Desktop
Mobile
Chrome
Edge
Firefox
Internet Explorer
Opera
Safari
WebView Android
Chrome Android
Firefox for Android
Opera Android
Safari on IOS
Samsung Internet
`pathname`
1
12
1
Before Firefox 53, the `pathname` and `search` `HTMLHyperlinkElementUtils` properties returned the wrong parts of the URL. For example, for a URL of `http://z.com/x?a=true&b=false`, `pathname` would return `'/x?a=true&b=false'` and `search` would return '', rather than `'/x'` and `'?a=true&b=false'` respectively. This has now been fixed.
5
15
1
1
18
4
Before Firefox 53, the `pathname` and `search` `HTMLHyperlinkElementUtils` properties returned the wrong parts of the URL. For example, for a URL of `http://z.com/x?a=true&b=false`, `pathname` would return `'/x?a=true&b=false'` and `search` would return '', rather than `'/x'` and `'?a=true&b=false'` respectively. This has now been fixed.
14
1
1.0
## See also
- The [`HTMLAreaElement`](../htmlareaelement) interface it belongs to.
<a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLAreaElement/pathname" class="_attribution-link">https://developer.mozilla.org/en-US/docs/Web/API/HTMLAreaElement/pathname</a> |
/*
Finish the specification of this reservation concept,
including its events, scenarios, and operational principles.
*/
sig Resource {}
sig User {
var reservations : set Resource
}
var sig Available in Resource {}
pred reserve[u : User, r : Resource] {
// Make a reservation
//guarda
r in Available
//effect
Available' = Available - r
u.reservations' = u.reservations+r
//frame
all x:User-u | r not in x.reservations
all y: User-u | y.reservations' = y.reservations
}
pred cancel[u : User, r : Resource] {
// Cancel a reservation
//guarda
r not in Available
//effect
Available' = Available + r
u.reservations' = u.reservations - r
//frame
all x : User - u | x.reservations' = x.reservations
all y : User - u | r not in y.reservations
}
pred use[u : User, r : Resource] {
// Use a reserved resource
//guarda
r in u.reservations
r not in Available
//effect
Available' = Available
u.reservations' = u.reservations - r
//frame
all y : User - u |y.reservations' = y.reservations
}
pred cleanup {
// Make all used resources available again
all r : Resource-Available-User.reservations | Available' = Available + r
}
pred stutter {
Available' = Available
reservations' = reservations
}
fact {
Available = Resource
no reservations
always {
stutter
or
cleanup
or
(some u : User , r : Resource| reserve[u,r] or cancel[u,r] or use[u,r])
}
}
// Validation
run Example {
// Empty run to be used for simulation
}
run Scenario1 {
// An user reserves a resource, uses it, and finally a cleanup occurs
some u : User, r : Resource {
reserve[u,r]; use[u,r]; cleanup
}
} expect 1
run Scenario2 {
// An user reserves a resource, cancels the reservation, and reserves again
some u : User, r : Resource {
reserve[u,r]; cancel[u,r]; reserve[u,r]
}
} expect 1
run Scenario3 {
// An user reserves two resources, cancels one, uses the other, and finally a cleanup occurs
} expect 1
run Scenario4 {
// Two users try to reserve the same resource
} expect 0
run Scenario5 {
// Eventually a cleanup is performed twice in a row
} expect 0
// Verification
check OP1 {
// Reserved resources aren't available
}
check OP2 {
// Used resources were reserved before
}
check OP3 {
// Used resourcse can only be reserved again after a cleanup
}
check OP4 {
// After a cleanup all unreserved resources are available
}
check OP5 {
// Cancel undoes reserve
}
check OP6 {
// If a cleanup occurs some resource was used before
}
check OP7 {
// Used resource were not canceled since being reserved
}
check OP8 {
// Reserved resources can be used while not used or cenceled
}
check OP9 {
// The first event to occur will be a reservation
}
check OP10 {
// If cleanups and cancels never occur the available resources keep diminishing
} |
import React, { useMemo } from "react"
import { useLocation, matchPath } from "react-router-dom";
import { FormType } from "../types/FromType";
export default function PostForm(props:
{
inputData: (e: React.ChangeEvent<HTMLInputElement>) => void,
btnFnc: () => void,
data: FormType
}) {
const { inputData, btnFnc, data } = props;
const { pathname } = useLocation();
const match = useMemo(() => {
return ["/posts", "/posts/edit/:id"].find((path) => !!matchPath(path, pathname));
}, [pathname]);
return (
<form className="postForm">
<input type="text" name="title" onChange={inputData} value={data.title} />
<p>{data.title}</p>
<input type="text" name="body" onChange={inputData} value={data.body} />
<p>{data.body}</p>
{/* <input type="file" name="file" id="" /> */}
{ match === '/posts' ? <button type="button" onClick={btnFnc}>投稿する</button> : "" }
{ match === '/posts/edit/:id' ? <button type="button" onClick={btnFnc}>更新する</button> : "" }
</form>
)
}; |
# Solar Explorer App
Welcome to Solar Explorer, a Flutter mobile application that takes you on a journey through our solar system. This app features an animative UI, Firebase authentication, and interactive login and signup pages.
## Table of Contents
- [Installation](#installation)
- [Features](#features)
- [Firebase Authentication](#firebase-authentication)
- [Solar System Exploration](#solar-system-exploration)
- [Screenshots](#screenshots)
- [Contributing](#contributing)
- [License](#license)
## Installation
To run the app locally, follow these steps:
1. Clone the repository:
```bash
git clone https://github.com/yourusername/solar-explorer-app.git
cd solar-explorer-app
Install dependencies:
flutter pub get
Run the app:
flutter run
Certainly! Below is a customized README template for your Flutter mobile application project that explores the solar system. Feel free to adjust it based on your project's specifics.
markdown
Copy code
# Solar Explorer App
Welcome to Solar Explorer, a Flutter mobile application that takes you on a journey through our solar system. This app features an animative UI, Firebase authentication, and interactive login and signup pages.
## Table of Contents
- [Installation](#installation)
- [Features](#features)
- [Firebase Authentication](#firebase-authentication)
- [Solar System Exploration](#solar-system-exploration)
- [Screenshots](#screenshots)
- [Contributing](#contributing)
- [License](#license)
## Installation
To run the app locally, follow these steps:
1. Clone the repository:
2.
git clone https://github.com/yourusername/solar-explorer-app.git
cd solar-explorer-app
Install dependencies:
flutter pub get
Run the app:
flutter run
## Features
Solar Explorer comes with a range of features designed to make your exploration of the solar system engaging and educational:
1. **Immersive Animations:**
- Experience a visually stunning and animative user interface that brings the solar system to life.
2. **Firebase Authentication:**
- Securely log in and sign up using Firebase Authentication.
- Safeguard your account and access personalized features.
3. **Interactive Login and Signup Pages:**
- User-friendly login and signup pages with smooth transitions and interactive elements.
4. **Solar System Exploration:**
- Explore detailed representations of each planet in our solar system.
- Learn fascinating facts about each planet's composition, orbit, and more.
- Navigate through an intuitive and informative user interface.
5. **Planet Details:**
- Dive deep into each planet's individual page.
- View high-quality images and read interesting details about the planet's characteristics.
6. **Educational Content:**
- Enjoy an educational journey through space with curated content about our solar system.
7. **Responsive Design:**
- The app is designed to provide a seamless experience on both smartphones and tablets.
Feel free to contribute and enhance the app by checking out our [contribution guidelines](CONTRIBUTING.md). |
<div class="col-sm-12">
<button class="btn btn-primary btn-sm" ng-back><i
class="fa fa-arrow-left fa-lg"></i> Back
</button>
</div>
<br><br>
<br>
<div class="col-sm-12">
<div class="panel profile-panel">
<div class="panel-heading panel-background">
<h3 class="panel-title">Update Question</h3>
</div>
<div class="panel-body">
<form name="editQuestion.form" class="form-horizontal" ng-submit="updateQuestion(editQuestion.form.$valid)"
novalidate>
<div class="form-group">
<div class="col-sm-12">
<span>Enter Question Title</span><span class="note-text">*</span>
<div ng-class="{'has-error': editQuestion.form.questionDesc.$invalid && (editQuestion.form.questionDesc.$dirty || editQuestion.form.$submitted)}">
<input class="form-control create-question-inputs" name="questionDesc"
placeholder="Enter Question Title"
ng-model="editQuestion.info.questionDesc" minlength="1" required>
<span class="help-block error-block basic-block pull-right" style="display: none">Question title is required field.</span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-6">
Select Genre<span class="note-text">*</span>
<div ng-class="{'has-error': editQuestion.form.questionType.$invalid && (editQuestion.form.questionType.$dirty || editQuestion.form.$submitted)}">
<select class="form-control create-question-inputs"
ng-model="editQuestion.info.genre"
id="questionType" name="questionType"
ng-options="item.name for item in genreList track by item.seq" required>
<option value="">Select Genre Type</option>
</select>
<span class="help-block error-block basic-block" style="display: none"></span>
</div>
</div>
<div class="col-sm-6">
Upload Image
<input class="form-control create-question-inputs" type="file"
ngf-select="uploadImage($file)"
ng-model="imageFile"
name="file"
accept="file_extension|audio/*|video/*|image/*|media_type"
ngf-max-size="10MB"><br>
</div>
</div>
</div>
</div>
<!-- <div class="form-group">
<div class="col-sm-5">
Upload Image
<input class="form-control create-question-inputs" type="file" ngf-select="uploadImage($file)"
ng-model="imageFile"
name="file"
accept="image/*" ngf-max-size="2MB"><br>
<!– <uib-progressbar ng-show="dynamic > 0 && dynamic < 100" class="progress-striped active"
animate="true" value="dynamic" type="success"><b>{{dynamic}}%</b>
</uib-progressbar>–>
<!– <button class="btn btn-danger btg-sm" ng-show="dynamic > 0 && dynamic <100"
ng-click="cancelUpload(imageFile)"><i class="fa fa-times" aria-hidden="true"></i>
</button>–>
</div>
</div>-->
<div class="form-group">
<div class="col-sm-12 col-md-12 col-lg-6 col-xs-12">
<div ng-class="{'has-error': editQuestion.form.answerOption.$invalid && (editQuestion.form.answerOption.$dirty || editQuestion.form.$submitted)}">
<div class="option-table">
Enter Option<span class="note-text">*</span>
<div class="row" ng-repeat="name in editQuestion.info.answerOption track by $index">
<div class="col-sm-6 col-md-8 col-lg-8 col-xs-6">
<input type="text"
class="form-control option-input "
ng-model="editQuestion.info.answerOption[$index].label"
placeholder="Enter Option">
</div>
<div class="col-sm-3 col-md-2 col-lg-2 col-xs-3">
<button type="button" class="form-control add-option"
ng-click="addRow($index)"
ng-show="$last">
<i class="fa fa-plus" aria-hidden="true"></i></button>
</button>
</div>
<div class="col-sm-3 col-md-2 col-lg-2 col-xs-3">
<button type="button" class="form-control delete-option"
ng-click="deleteRow($event,$index)"
ng-show="$index != 0">
<i class="fa fa-times" aria-hidden="true"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<span>Correct answer</span><span class="note-text">*</span>
<div ng-class="{'has-error': newQuestion.form.correctAnswer.$invalid && (newQuestion.form.correctAnswer.$dirty || newQuestion.form.$submitted)}">
<input class="form-control create-question-inputs" name="correctAnswer"
placeholder="Enter correct answer"
ng-model="editQuestion.info.correctAnswer" maxlength="1" required>
<span class="help-block error-block basic-block pull-right" style="display: none">Correct answer is required field.</span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary btn-raised"
ng-disabled="editQuestion.form.$invalid">Update
</button>
</div>
</div>
</form>
</div>
</div>
</div> |
## ESP32 Rapberry Pico Zero Example
This is similar the [pizero to pizero](https://github.com/jouellnyc/UART/tree/main/pizero_simple) example, here we we add an esp32.
## Prerequisites
- An esp32
- A Pi Zero W
These are the same we've been using in the previous projects.
# Why?
This is another physically connected alternative to wifi-based [wpa-ent-mschapv2-bridge](https://github.com/jouellnyc/wpa-ent-mschapv2-bridge), however, now we don't need a full operating system like on the pi zero, we can use a microcontroller, specifically the esp32, because it has the ppp software available.
| Cautionary Notes | Description |
|-----------------|---------------------------------------------------------|
| 1. | The ppp configs are not hardened - this is just starting out to get you going|
## Pi Zero Setup
- Setup the Pi Zero to [allow Serial Communications](https://learn.adafruit.com/raspberry-pi-zero-creation/enable-uart)
- see [config.txt](config.txt)
- see [cmdline.txt](cmdline.txt)
## Physical Connections / Pins
- Make sure the TX of the pi zero is connected to the RX of the esp32.
- Make sure the TX of the esp32 is connected to the RX of the pi.
- Here we are using:
| ESP32 Pin | Description |
|---|---|
| TX | GPIO 14 |
| RX | GPIO 13 |
These are again remapped because of SPIRAM usage and to remove any pin conflicts for the UART. Modify if needed.
| ESP32 Pin | Description |
|---|---|
| TX | GPIO 14 |
| RX | GPIO 15 |
These are the default pi zero pins
- See https://pinout.xyz/
- Also have a shared ground.
## Client
```
import machine
uart = machine.UART(2, baudrate=9600, tx=13, rx=14)
import network
ppp = network.PPP(uart)
ppp.active(True)
ppp.connect()
```
Once connected, the following should reveal True and the IP settings of the esp32:
```
>>> ppp.isconnected()
True
>>> ppp.ifconfig()
('10.0.5.2', '10.0.5.1', '255.255.255.255', '8.8.8.8')
```
## Server
- /etc/rc.local
```
#!/bin/sh -e
echo "Starting pppd..."
stty -F /dev/ttyAMA0 raw
pppd /dev/ttyAMA0 1000000 10.0.5.1:10.0.5.2 proxyarp local noauth debug nodetach dump nocrtscts passive persist maxfail 0 holdoff 1
```
## Pic
The connections are very straight forward. Here's a photo just the same:

## Takeaways/ Learnings
- Make sure both sides have the same line speed (`pppd /dev/ttyAMA0 9600` or whatever baud you choose). It's easy to forget that!
- Everything works without the esp32 needing to call ppp.ifconfig(()) to set anything at all. It picked up the details from the 'server'.
- We needed 'modules-load=dwc2,g_serial' in cmdline.txt for the communication to flow.
- Interesting how the latency of an icmp packet (much slower) compared to bare 'naked UARTS for [rs-485](https://github.com/jouellnyc/UART/blob/main/esp32_rs485/README.md) but how the ppp link could withstand higher baud rates.
| Connection | Lowest Latency |
|------------------------|----------------|
| Dupont Wires - 10 cm - 9600 BAUD | 180 ms |
| Dupont Wires - 10 cm - 19200 BAUD | 90 ms |
| Dupont Wires - 10 cm - 38400 BAUD | 47 ms |
| Dupont Wires - 10 cm - 57600 BAUD | 32 ms |
| Dupont Wires - 10 cm - 115200 BAUD | 16 ms |
| Dupont Wires - 10 cm - 230400 BAUD | 8.3 ms |
| Dupont Wires - 10 cm - 460800 BAUD | 4.4 ms (inconsistent) |
| Dupont Wires - 10 cm - 921600 BAUD | 2.5 ms (inconsistent) |
| Dupont Wires - 10 cm - 1843200 BAUD | speed not supported by pi zero |
## References
[Raspberry Pi Forums Post](https://forums.raspberrypi.com/viewtopic.php?p=2227171)
[Micropython Forum Post](https://github.com/orgs/micropython/discussions/14538)
[TI forum re: Baud](https://e2e.ti.com/support/microcontrollers/msp-low-power-microcontrollers-group/msp430/f/msp-low-power-microcontroller-forum/832781/ccs-msp430fr5994-what-is-the-max-uart-spi-baud-rates-using-only-dco)
## License
This project is licensed under the [MIT License](LICENSE).
Feel free to modify the content as needed, such as adding installation instructions, code examples, or any other relevant information for your project. |
<template>
<main v-if="data">
<DataTime :text="title" :dataDate="data.Date"/>
<DataBox :stats="stats"/>
<CountrySelect @get-country="setCountry" :countries="data.Countries" />
<button
v-if="stats.Country" @click="clearCountry"
class="w-full mb-6 bg-blue-700 text-white rounded p-3 focus:outline-none hover:bg-blue-500 hover:text-black">Clear Country</button>
</main>
<main v-else class="flex flex-col align-center justify-center text-center">
<div class="text-center text-gray-400 mb-4 ">
<p class="font-bold">Loading Data...</p>
<img :src="loadingImage" alt="" class="w-24 m-auto mt-10">
</div>
</main>
</template>
<script>
// @ is an alias to /src
import DataTime from '../components/DataTime';
import DataBox from '@/components/DataBox';
import CountrySelect from '@/components/CountrySelect';
import Footer from '@/components/Footer'
export default {
name: 'Home',
components: {
DataTime,
DataBox,
CountrySelect,
Footer
},
data(){
return{
data: null,
dataDate:'',
stats: {},
title:'Global',
countries: [],
loadingImage: require('../assets/loader.gif')
}
},
methods:{
async fetchApi(){
const res = await fetch('https://api.covid19api.com/summary');
const data = await res.json()
return data
},
setCountry(country){
// alert(country.Country)
this.stats = country;
this.title = country.Country
},
async clearCountry(){
this.data = null
this.data = await this.fetchApi();
this.stats = await this.data.Global
this.title ='Global'
}
},
async created(){
this.data = await this.fetchApi()
this.stats = await this.data.Global
this.date = await this.data.Date
// console.log(this.data)
}
}
</script> |
package com.yatish.presentation.ui.character_list
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yatish.domain.Result
import com.yatish.domain.usecase.GetAllCharactersUseCase
import com.yatish.presentation.base.ViewIntent
import com.yatish.presentation.di.IoDispatcher
import com.yatish.presentation.mapper.CharacterItemMapper
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class CharacterListViewModel @Inject constructor(
@IoDispatcher private val dispatcher: CoroutineDispatcher,
private val getAllCharactersUseCase: GetAllCharactersUseCase,
private val characterItemMapper: CharacterItemMapper
) : ViewModel(), CharacterListContract {
init {
sendIntent(CharacterListContract.ListScreenViewIntent.LoadData)
}
override fun createInitialState(): CharacterListContract.ListScreenViewState =
CharacterListContract.ListScreenViewState.Loading
private val _state = MutableStateFlow(createInitialState())
override val viewState: StateFlow<CharacterListContract.ListScreenViewState>
get() = _state.asStateFlow()
private val _sideEffect = MutableSharedFlow<CharacterListContract.ListScreenSideEffect>()
override val sideEffect: SharedFlow<CharacterListContract.ListScreenSideEffect>
get() = _sideEffect.asSharedFlow()
override fun sendIntent(intent: ViewIntent) {
when (intent) {
is CharacterListContract.ListScreenViewIntent.LoadData -> fetchCharacterList()
is CharacterListContract.ListScreenViewIntent.OnCharacterItemClick -> navigateToDetails(
intent.id,
intent.name
)
}
}
private fun fetchCharacterList() {
viewModelScope.launch(dispatcher) {
when (val result = getAllCharactersUseCase()) {
is Result.Success -> {
_state.emit(
CharacterListContract.ListScreenViewState.Success(characterItemMapper.map(result.data))
)
}
is Result.Error -> {
_state.emit(CharacterListContract.ListScreenViewState.Error(result.error))
}
}
}
}
private fun navigateToDetails(id: String, name: String) {
viewModelScope.launch {
_sideEffect.emit(CharacterListContract.ListScreenSideEffect.NavigateToDetails(id, name))
}
}
} |
// This file isn't processed by Vite, see https://github.com/vikejs/vike/issues/562
// Consequently:
// - When changing this file, you needed to manually restart your server for your changes to take effect.
// - To use your environment variables defined in your .env files, you need to install dotenv, see https://vike.dev/env
// - To use your path aliases defined in your vite.config.js, you need to tell Node.js about them, see https://vike.dev/path-aliases
// If you want Vite to process your server code then use one of these:
// - vavite (https://github.com/cyco130/vavite)
// - See vavite + Vike examples at https://github.com/cyco130/vavite/tree/main/examples
// - vite-node (https://github.com/antfu/vite-node)
// - HatTip (https://github.com/hattipjs/hattip)
// - You can use Bati (https://batijs.dev/) to scaffold a Vike + HatTip app. Note that Bati generates apps that use the V1 design (https://vike.dev/migration/v1-design) and Vike packages (https://vike.dev/vike-packages)
import express from 'express'
import compression from 'compression'
import { renderPage } from 'vike/server'
import { root } from '#root/server/root'
import {mockPages} from '#root/server/mockPages';
const isProd = process.env.NODE_ENV === 'production';
startServer();
async function startServer() {
const app = express();
app.enable('trust proxy');
app.use(compression())
if (!isProd) {
// We instantiate Vite's development server and integrate its middleware to our server.
// ⚠️ We instantiate it only in development. (It isn't needed in production and it
// would unnecessarily bloat our production server.)
const vite = await import('vite')
const viteDevMiddleware = (
await vite.createServer({
root,
server: { middlewareMode: true }
})
).middlewares
app.use(viteDevMiddleware)
} else {
// In deployed lower and live environments, we need to serve our static assets ourselves.
// (In dev, Vite's middleware serves our static assets.)
const sirv = (await import('sirv')).default
app.use(sirv(`${root}/dist/client`))
}
// ...
// Other middlewares (e.g. some RPC middleware such as Telefunc)
// ...
// Vike middleware. It should always be our last middleware (because it's a
// catch-all middleware superseding any middleware placed after it).
app.get('*', async (req: express.Request, res: express.Response, next: express.NextFunction) => {
const serverStart = new Date().getTime();
const host = req.get('host')
const mockSiteId = 'abcde';
const requestedPage = stripSlashAtStart(req.originalUrl?.replace('/index.pageContext.json', '')).split('?')[0];
const activeScreenId = mockPages.find(({page}) => page === requestedPage)?.id;
console.log(`requestedPage=${requestedPage}, activeScreenId=${activeScreenId}`);
const pageContextInit = {
urlOriginal: req.originalUrl,
host,
requestedPage,
site_id: mockSiteId,
activeScreenId,
serverStart,
};
const pageContext = await renderPage(pageContextInit);
if (pageContext.errorWhileRendering) {
// Install error tracking here, see https://vike.dev/errors
console.log(`errorWhileRendering=${pageContext.errorWhileRendering}`);
}
const { httpResponse } = pageContext
if (!httpResponse) {
return next()
} else {
const { body, statusCode, headers, earlyHints } = httpResponse
if (res.writeEarlyHints) res.writeEarlyHints({ link: earlyHints.map((e) => e.earlyHintLink) })
headers.forEach(([name, value]) => res.setHeader(name, value))
res.status(statusCode)
// For HTTP streams use httpResponse.pipe() instead, see https://vike.dev/streaming
res.send(body)
}
})
const port = process.env.PORT || 3005
app.listen(port)
console.log(`Server running at http://localhost:${port}`)
}
function stripSlashAtStart(str: string) {
if (str[0] === '/') {
str = str.substring(1, str.length);
}
return str;
} |
// This example illustates basic use of the NMEA library.
// It assumes that a GPS receiver is connected to serial
// port 'Serial1' at 4800 bps, and that a LED is connected
// to digital i/o pin 0.
//
// A GPS data connection of type GPRMC is created, and
// used to get distance to a destination. If the distance
// is under 500 meters, the LED lights up, otherwise it
// is off.
#include <nmea.h>
NMEA gps(GPRMC); // GPS data connection to GPRMC sentence type
// destination coordinates in degrees-decimal
float dest_latitude = 48.858342;
float dest_longitude = 2.294522;
void setup() {
Serial1.begin(4800);
pinMode(0, OUTPUT);
}
void loop() {
if (Serial1.available() > 0 ) {
// read incoming character from GPS
char c = Serial1.read();
// check if the character completes a valid GPS sentence
if (gps.decode(c)) {
// check if GPS positioning was active
if (gps.gprmc_status() == 'A') {
// read distance to destination in meters and set led accordingly
if (gps.gprmc_distance_to(dest_latitude, dest_longitude, MTR) < 500.0) {
digitalWrite(0, HIGH);
}
else {
digitalWrite(0, LOW);
}
}
}
}
} |
module Cloudflare::Caching
class Scanner
getter options : Options
getter entries : Hash(IPAddress, Set(Entry))
getter lastCleanedUp : Time
getter mutex : Mutex
def initialize(@options : Options)
@entries = Hash(IPAddress, Set(Entry)).new
@lastCleanedUp = Time.local
@mutex = Mutex.new :unchecked
end
def external_controller=(value : Bool)
@mutex.synchronize { @externalController = value }
end
def external_controller
@externalController
end
def restore(serialized_export : Serialized::Export::Scanner)
@mutex.synchronize do
@entries = serialized_export.unwrap_entries!
@lastCleanedUp = serialized_export.lastCleanedUp
end
true
end
private def refresh_last_cleaned_up
@mutex.synchronize { @lastCleanedUp = Time.local }
end
private def need_cleared? : Bool
interval = Time.local - lastCleanedUp
interval > options.scanner.caching.clearInterval
end
private def inactive_entry_cleanup : Bool
return false unless need_cleared?
starting_time = Time.local
entries.each do |ip_block, entry_set|
temporary_set = Set(Entry).new
entry_set.each do |entry|
next if options.scanner.caching.clearInterval <= (starting_time - entry.createdAt)
temporary_set << entry
end
entries[ip_block] = temporary_set
end
true
end
def set(ip_block : IPAddress, iata : Needles::IATA, priority : UInt8, ip_address : Socket::IPAddress)
@mutex.synchronize do
inactive_entry_cleanup
entry_set = entries[ip_block] ||= Set(Entry).new
if entry_set.size < options.scanner.caching.ipAddressCapacityPerIpBlock
entry_set << Entry.new iata: iata, priority: priority, ipAddress: ip_address
entries[ip_block] = entry_set
return
end
iata_count = entry_set.count { |entry| iata == entry.iata }
percentage = ((iata_count / entry_set.size) * 100_i32).round.to_i32
case iata_count
when .zero?
entry_set.delete entry_set.first
entry_set << Entry.new iata: iata, priority: priority, ipAddress: ip_address
entries[ip_block] = entry_set
else
case percentage
when .< 50_i32
entry_set.each do |entry|
next if iata == entry.iata
entry_set.delete entry
entry_set << Entry.new iata: iata, priority: priority, ipAddress: ip_address
entries[ip_block] = entry_set
return
end
else
entry_set.each do |entry|
next unless iata == entry.iata
entry_set.delete entry
entry_set << Entry.new iata: iata, priority: priority, ipAddress: ip_address
entries[ip_block] = entry_set
return
end
end
end
end
end
def to_tuple_ip_addresses : Array(Tuple(Needles::IATA, Socket::IPAddress))
_entries_dup = dup
list = [] of Tuple(UInt8, Needles::IATA, Socket::IPAddress)
_entries_dup.each do |ip_block, entry_set|
entry_set.each { |entry| list << Tuple.new entry.priority, entry.iata, entry.ipAddress }
end
list = list.sort { |x, y| x.first <=> y.first }
list.map do |item|
priority, iata, ip_address = item
Tuple.new iata, ip_address
end
end
def dup : Hash(IPAddress, Set(Entry))
@mutex.synchronize { entries.dup }
end
def to_serialized_entries : Hash(String, Array(Serialized::Export::Scanner::Entry))
serialized_entries = Hash(String, Array(Serialized::Export::Scanner::Entry)).new
_dup = dup
_dup.each do |ip_block, _entries|
_ip_block = String.build { |io| io << ip_block.address << '/' << ip_block.prefix }
ip_block_serialized_entries = serialized_entries[_ip_block]? || Array(Serialized::Export::Scanner::Entry).new
_entries.each { |entry| ip_block_serialized_entries << entry.to_serialized }
serialized_entries[_ip_block] = ip_block_serialized_entries
end
serialized_entries
end
def to_serialized : Serialized::Export::Scanner
Serialized::Export::Scanner.new entries: to_serialized_entries, lastCleanedUp: lastCleanedUp
end
struct Entry
property iata : Needles::IATA
property priority : UInt8
property ipAddress : Socket::IPAddress
property createdAt : Time
def initialize(@iata : Needles::IATA, @priority : UInt8, @ipAddress : Socket::IPAddress)
@createdAt = Time.local
end
def to_serialized : Serialized::Export::Scanner::Entry
Serialized::Export::Scanner::Entry.new iata: iata, priority: priority, ipAddress: String.build { |io| io << ipAddress.address << ':' << ipAddress.port }, createdAt: createdAt
end
end
end
end |
import { app, db, auth } from "./initFirebase";
import { signInWithEmailAndPassword, createUserWithEmailAndPassword, onAuthStateChanged } from "firebase/auth";
import { collection, setDoc, doc } from "firebase/firestore";
const userEmail = document.querySelector("#em");
const userPass = document.querySelector("#pass");
const signInButton = document.querySelector("#signIn");
const createAccountButton = document.querySelector("#create");
const signInUser = async () => {
const em = userEmail.value;
const pass = userPass.value;
await signInWithEmailAndPassword(auth, em, pass)
.then((userCred) => {
alert(userCred.user.email + " successfully signed in");
window.location.href = "./navigation.html";
}).catch((error) => {
alert(error.message);
});
}
const createUser = async () => {
const em = userEmail.value;
const pass = userPass.value;
await createUserWithEmailAndPassword(auth, em, pass)
.then(async (userCred) => {
await setDoc(doc(db, "patientData", userCred.user.uid), {
email: userCred.user.email,
Age: 25,
Gender: 1,
'Air Pollution': 3,
'Alcohol use': 5,
'Dust Allergy': 7,
'OccuPational Hazards': 9,
'Genetic Risk': 2,
'chronic Lung Disease': 4,
'Balanced Diet': 6,
'Obesity': 8,
'Smoking': 10,
'Passive Smoker': 1,
'Chest Pain': 5,
'Coughing of Blood': 3,
'Fatigue': 3,
'Weight Loss': 1,
'Shortness of Breath': 7,
'Wheezing': 9,
'Swallowing Difficulty': 1,
'Clubbing of Finger Nails': 1,
'Frequent Cold': 5,
'Dry Cough': 8,
'Snoring': 4,
'Level': "Medium"
}).then((resp) => {
console.log("Member successfully added")
}).catch((err) => {
console.log("error making new member");
console.log(error);
});
alert(userCred.user.email + " successfully created");
onAuthStateChanged(auth, (user) => {
if (user) {
window.location.href = "./navigation.html";
}
});
window.location.href = "./navigation.html";
}).catch((error) => {
alert(error);
console.log(error);
});
}
signInButton.addEventListener('click', signInUser);
createAccountButton.addEventListener('click', createUser); |
const chai = require('chai');
const chaiHttp = require('chai-http');
const { server } = require('./Server'); // Importing the server instance
const e = require('express');
const { before } = require('mocha');
const { expect } = chai;
chai.use(chaiHttp);
// Test suite for the Tic Tac Toe Server
describe('Tic Tac Toe Server', () => {
// now test cases go here
describe('Server End Points', () => {
it('should return the initial state of the board', (done) => {
chai
.request(server)
.get('/board')
.end((err, res) => {
expect(res).to.have.status(200);
expect(res.body).to.be.an('object');
expect(res.body.board).to.deep.equal([
['', '', ''],
['', '', ''],
['', '', ''],
]);
expect(res.body.winner).to.equal('');
expect(res.body.scoreX).to.equal(0);
expect(res.body.scoreO).to.equal(0);
done();
});
});
it('should allow a player to make a valid move', (done) => {
chai
.request(server)
.post('/move')
.send({ row: 0, col: 0 })
.end((err, res) => {
expect(res).to.have.status(200);
expect(res.body).to.be.an('object');
expect(res.body.success).to.be.true;
done();
});
});
it('should reset the game state', (done) => {
chai
.request(server)
.post('/reset')
.end((err, res) => {
expect(res).to.have.status(200);
expect(res.body).to.be.an('object');
expect(res.body.success).to.be.true;
done();
});
});
});
describe('Game Reset', () => {
it('it should reset the game board and scores', async function () {
// make a move
const res = await chai.request(server).post('/move').send({ row: 0, col: 0 });
const res_1 = await chai.request(server).get('/board');
// Asserting the state of the board
expect(res_1.body.board).to.deep.equal([
['X', '', ''],
['', '', ''],
['', '', ''],
]);
expect(res_1.body.scoreX).to.equal(0);
expect(res_1.body.scoreO).to.equal(0);
// Reset the game
const res_2 = await chai.request(server).post('/reset');
const res_3 = await chai.request(server).get('/board');
// Asserting the reset state of the board
expect(res_3.body.board).to.deep.equal([
['', '', ''],
['', '', ''],
['', '', ''],
]);
expect(res_3.body.scoreX).to.equal(0);
expect(res_3.body.scoreO).to.equal(0);
});
});
describe('Game Logic Tests', () => {
beforeEach((done) => {
chai
.request(server)
.post('/reset')
.end((err, res) => {
done();
});
});
it('should not allow a player to make an invalid move', (done) => {
chai
.request(server)
.post('/move')
.send({ row: 3, col: 3 })
.end((err, res) => {
expect(res).to.have.status(400);
expect(res.body).to.be.an('object');
expect(res.body.success).to.be.false;
expect(res.body.message).to.equal('Invalid move');
done();
});
});
it('should not allow a player to make a move on an occupied space', (done) => {
chai
.request(server)
.post('/move')
.send({ row: 0, col: 0 })
.end((err, res) => {
expect(res).to.have.status(200);
expect(res.body).to.be.an('object');
expect(res.body.success).to.be.true;
chai
.request(server)
.post('/move')
.send({ row: 0, col: 0 })
.end((err, res) => {
expect(res).to.have.status(400);
expect(res.body).to.be.an('object');
expect(res.body.success).to.be.false;
expect(res.body.message).to.equal('Invalid move');
done();
});
});
});
it('it should declare a winner if a row is completed', async () => {
const move1 = await chai.request(server).post('/move').send({ row: 0, col: 0 });
const move2 = await chai.request(server).post('/move').send({ row: 1, col: 0 });
const move3 = await chai.request(server).post('/move').send({ row: 0, col: 1 });
const move4 = await chai.request(server).post('/move').send({ row: 1, col: 1 });
const move5 = await chai.request(server).post('/move').send({ row: 0, col: 2 });
expect(move5).to.have.status(200);
expect(move5.body).to.be.an('object');
expect(move5.body.success).to.be.true;
expect(move5.body.winner).to.includes('X');
});
it('it should declare a winner if a column is completed', async () => {
const move1 = await chai.request(server).post('/move').send({ row: 0, col: 0 });
const move2 = await chai.request(server).post('/move').send({ row: 0, col: 1 });
const move3 = await chai.request(server).post('/move').send({ row: 1, col: 0 });
const move4 = await chai.request(server).post('/move').send({ row: 1, col: 1 });
const move5 = await chai.request(server).post('/move').send({ row: 2, col: 0 });
expect(move5).to.have.status(200);
expect(move5.body).to.be.an('object');
expect(move5.body.success).to.be.true;
expect(move5.body.winner).to.includes('X');
});
it('it should declare a winner if a diagonal is completed', async () => {
const move1 = await chai.request(server).post('/move').send({ row: 0, col: 0 });
const move2 = await chai.request(server).post('/move').send({ row: 0, col: 1 });
const move3 = await chai.request(server).post('/move').send({ row: 1, col: 1 });
const move4 = await chai.request(server).post('/move').send({ row: 1, col: 2 });
const move5 = await chai.request(server).post('/move').send({ row: 2, col: 2 });
expect(move5).to.have.status(200);
expect(move5.body).to.be.an('object');
expect(move5.body.success).to.be.true;
expect(move5.body.winner).to.includes('X');
});
});
describe('Board Extension', () => {
beforeEach((done) => {
chai
.request(server)
.post('/reset')
.end((err, res) => {
done();
});
});
const fillUpBoard = async () => {
let moves = [
{ row: 0, col: 0 },
{ row: 0, col: 1 },
{ row: 0, col: 2 },
{ row: 1, col: 0 },
{ row: 1, col: 2 },
{ row: 1, col: 1 },
{ row: 2, col: 1 },
{ row: 2, col: 2 },
{ row: 2, col: 0 },
];
for (let i = 0; i < moves.length; i++) {
const move = await chai.request(server).post('/move').send(moves[i]);
expect(move).to.have.status(200);
expect(move.body).to.be.an('object');
expect(move.body.success).to.be.true;
}
};
it('it should extend the board from 3x3 to 4x4 when the 3x3 board is full', async () => {
await fillUpBoard();
const res = await chai.request(server).get('/board');
const { board } = res.body;
expect(board.length).to.equal(4);
expect(board[0].length).to.equal(4);
expect(board[1].length).to.equal(4);
expect(board[2].length).to.equal(4);
expect(board[3].length).to.equal(4);
});
it('it should declare a winner if a Column is completed', async () => {
await fillUpBoard();
let moves = [
{ row: 0, col: 3 },
{ row: 3, col: 0 },
{ row: 1, col: 3 },
{ row: 3, col: 1 },
{ row: 2, col: 3 },
{ row: 3, col: 2 },
{ row: 3, col: 3 },
];
let move;
for (let i = 0; i < moves.length; i++) {
move = await chai.request(server).post('/move').send(moves[i]);
expect(move).to.have.status(200);
expect(move.body).to.be.an('object');
expect(move.body.success).to.be.true;
}
expect(move.body.winner).to.includes('X');
const res = await chai.request(server).get('/board');
const { board } = res.body;
expect(board.length).to.equal(3);
});
it('it should declare a winner if a Row is completed', async () => {
await fillUpBoard();
let moves = [
{ row: 3, col: 0 },
{ row: 0, col: 3 },
{ row: 3, col: 1 },
{ row: 1, col: 3 },
{ row: 3, col: 2 },
{ row: 2, col: 3 },
{ row: 3, col: 3 },
];
let move;
for (let i = 0; i < moves.length; i++) {
move = await chai.request(server).post('/move').send(moves[i]);
expect(move).to.have.status(200);
expect(move.body).to.be.an('object');
expect(move.body.success).to.be.true;
}
expect(move.body.winner).to.includes('X');
const res = await chai.request(server).get('/board');
const { board } = res.body;
expect(board.length).to.equal(3);
});
it('should avoid awarding 2 points for two triplets on the 4x4 board', async () => {
// Fill the board to create two triplets (e.g., two horizontal triplets)
const moves = [
{ row: 0, col: 0 }, { row: 1, col: 0 }, { row: 0, col: 1 },
{ row: 1, col: 1 }, { row: 0, col: 2 }, { row: 1, col: 2 },
{ row: 0, col: 3 }, { row: 1, col: 3 }
];
// Make the moves
for (const move of moves) {
const response = await chai.request(server).post('/move').send(move);
expect(response).to.have.status(200);
expect(response.body).to.be.an('object');
expect(response.body.success).to.be.true;
}
// Check the scores after making the moves
const scoresResponse = await chai.request(server).get('/board');
expect(scoresResponse).to.have.status(200);
expect(scoresResponse.body).to.be.an('object');
expect(scoresResponse.body.scoreX).to.equal(0); // Ensure no points are awarded for the scenario
expect(scoresResponse.body.scoreO).to.equal(0); // Ensure no points are awarded for the scenario
});
it('should handle a draw scenario on the 4x4 board', async () => {
// Fill the board to create a draw scenario
const moves = [
{ row: 0, col: 0 }, { row: 0, col: 1 }, { row: 0, col: 2 }, { row: 0, col: 3 },
{ row: 1, col: 0 }, { row: 1, col: 1 }, { row: 1, col: 2 }, { row: 1, col: 3 },
{ row: 2, col: 0 }, { row: 2, col: 1 }, { row: 2, col: 2 }, { row: 2, col: 3 },
{ row: 3, col: 0 }, { row: 3, col: 1 }, { row: 3, col: 2 }, { row: 3, col: 3 },
];
// Make the moves
for (const move of moves) {
const response = await chai.request(server).post('/move').send(move);
expect(response).to.have.status(200);
expect(response.body).to.be.an('object');
expect(response.body.success).to.be.true;
}
// Check that there is no winner and the game is a draw
const scoresResponse = await chai.request(server).get('/board');
expect(scoresResponse).to.have.status(200);
expect(scoresResponse.body).to.be.an('object');
expect(scoresResponse.body.winner).to.equal('');
expect(scoresResponse.body.scoreX).to.equal(0);
expect(scoresResponse.body.scoreO).to.equal(0);
});
});
}); |
import React from 'react';
import { Navigate, useNavigate, useParams } from 'react-router-dom';
import SuperInputText from '../../../components/SuperInputText/SuperInputText';
import SuperButton from '../../../components/SuperButton/SuperButton';
import s from '../CommonAuthStyles.module.scss';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import commonS from './../CommonAuthStyles.module.scss';
import { useDispatch, useSelector } from 'react-redux';
import { sendNewUserPassword } from '../../../../bll/new-pass-reducer';
import { RootStateType } from '../../../../bll/store';
import { ROUTES } from '../../../../router/routes';
type PropsType = {};
export const NewPassword = React.memo(({}: PropsType) => {
const { token } = useParams();
const dispatch = useDispatch();
const navigate = useNavigate();
const onNewPasswordHandler = (password: string) => {
dispatch(sendNewUserPassword(password, token));
setTimeout( () => {
navigate('/profile');
}, 1000 );
};
const formik = useFormik({
initialValues: {
password: ''
},
validationSchema: Yup.object({
password: Yup.string()
.min(8, 'Must be at least 8 characters long')
.required('This field is required'),
}),
onSubmit: (values) => {
onNewPasswordHandler(values.password);
formik.resetForm();
},
});
const isLoggedIn = useSelector<RootStateType, boolean>(state => state.auth.isLoggedIn);
if (isLoggedIn) {
return <Navigate to={ROUTES.PROFILE} />;
}
return (
<>
<h1 className={commonS.title}>It-incubator</h1>
<p className={commonS.subtitle}>Create new password</p>
<form onSubmit={formik.handleSubmit} className={commonS.form}>
<div className={s.formLine}>
<SuperInputText
id={'password'}
type={'password'}
{...formik.getFieldProps('password')}
placeholder={' '}
/>
<label className={commonS.formLabel}>Password</label>
{formik.touched.password && formik.errors.password ? (
<div className={commonS.error}>{formik.errors.password}</div>
) : null}
</div>
<p className={commonS.baselineText}>Create new password and we will send you further instructions to email</p>
<SuperButton type={'submit'}>Create new password</SuperButton>
</form>
</>
);
}); |
<template>
<section
class="bg-white"
>
<b-container class="pt-5 pb-5">
<b-row>
<b-col class="text-center">
<h3>
User Info
</h3>
<hr class="primary">
</b-col>
</b-row>
<b-row class="justify-content-center">
<b-col sm="6" class="mt-3 mb-3">
<b-card class="shadow">
<form
@submit.prevent="handleSubmit"
>
<div class="form-group">
<label>First Name</label>
<input
v-model="form.firstName"
class="form-control form-control-lg"
>
</div>
<div class="form-group">
<label>Last Name</label>
<input
v-model="form.lastName"
class="form-control form-control-lg"
>
</div>
<div class="form-group">
<label>Username</label>
<input
v-model="form.username"
class="form-control form-control-lg"
>
</div>
<div class="form-group">
<label>Email address</label>
<input
v-model="form.email"
required
type="email"
class="form-control form-control-lg"
>
</div>
<b-row class="justify-content-md-center">
<b-col sm="6">
<b-button
type="submit"
class="btn btn-dark btn-lg btn-block"
>
Update Info
</b-button>
</b-col>
</b-row>
<p v-if="errors.length">
<b>Please correct the following error(s):</b>
<ul>
<li v-for="error in errors">
{{ error }}
</li>
</ul>
</p>
<br>
</form>
<form
@submit.prevent="resetPasswordSubmit"
>
<div class="form-group">
<label>Password</label>
<input
v-model="password"
required
type="password"
class="form-control form-control-lg"
>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input
v-model="passwordConfirmation"
required
type="password"
class="form-control form-control-lg"
>
</div>
<b-row class="justify-content-md-center">
<b-col sm="6">
<b-button
type="submit"
class="btn btn-dark btn-lg btn-block"
>
Update Password
</b-button>
</b-col>
</b-row>
</form>
<p v-if="passwordErrors.length">
<b>Please correct the following error(s):</b>
<ul>
<li v-for="error in passwordErrors">
{{ error }}
</li>
</ul>
</p>
</b-card>
</b-col>
</b-row>
</b-container>
</section>
</template>
<script>
import { mapState, mapActions } from 'vuex'
import gql from 'graphql-tag'
export default {
data() {
return {
errors: [],
passwordErrors: [],
password: '',
passwordConfirmation: '',
form: {
firstName: '',
lastName: '',
email: '',
username: '',
}
}
},
computed: {
...mapState('account', ['user', 'role', 'status']),
},
watch: {
user(val) {
if (val) {
this.form = (({username, firstName, lastName, email, password}) => ({username, firstName, lastName, email, password}))(val);
}
}
},
mounted() {
this.form = (({username, firstName, lastName, email, password}) => ({username, firstName, lastName, email, password}))(this.user);
},
updated() {
},
methods: {
...mapActions('account', ['update'], { clearAlert: 'alert/clear' }),
validEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email)
},
handleSubmit(e) {
this.submitted = true
this.errors = []
if (!this.form.email) {
this.errors.push('Email required.')
} else if (!this.validEmail(this.form.email)) {
this.errors.push('Valid email required.')
}
if (!this.errors.length) {
this.update({ user: this.form, id: this.user.id}).then((response) => {
this.makeToast('success')
})
}
},
resetPasswordSubmit() {
this.submitted = true
const { password, passwordConfirmation } = this
this.passwordErrors = []
if (!password) {
this.passwordErrors.push('Password required.')
} else if (!passwordConfirmation) {
this.passwordErrors.push('Confirmation Password required.')
} else if (password !== passwordConfirmation) {
this.passwordErrors.push('Passwords must match.')
} else if (password && passwordConfirmation) {
this.update( { user: {password: password }, id: this.user.id}).then((response) => {
this.makeToast('success')
})
}
},
makeToast(variant) {
this.$bvToast.toast('Profile Updated!', {
variant,
solid: true,
})
},
}
}
</script>
<style>
</style> |
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
package org.opensearch.flowframework.model;
import org.opensearch.commons.authuser.User;
import org.opensearch.core.common.ParsingException;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParseException;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.flowframework.exception.FlowFrameworkException;
import org.opensearch.flowframework.util.ParseUtils;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken;
import static org.opensearch.flowframework.common.CommonValue.ERROR_FIELD;
import static org.opensearch.flowframework.common.CommonValue.PROVISIONING_PROGRESS_FIELD;
import static org.opensearch.flowframework.common.CommonValue.PROVISION_END_TIME_FIELD;
import static org.opensearch.flowframework.common.CommonValue.PROVISION_START_TIME_FIELD;
import static org.opensearch.flowframework.common.CommonValue.RESOURCES_CREATED_FIELD;
import static org.opensearch.flowframework.common.CommonValue.STATE_FIELD;
import static org.opensearch.flowframework.common.CommonValue.USER_FIELD;
import static org.opensearch.flowframework.common.CommonValue.USER_OUTPUTS_FIELD;
import static org.opensearch.flowframework.common.CommonValue.WORKFLOW_ID_FIELD;
import static org.opensearch.flowframework.util.ParseUtils.parseStringToStringMap;
/**
* The WorkflowState is used to store all additional information regarding a workflow that isn't part of the
* global context.
*/
public class WorkflowState implements ToXContentObject, Writeable {
private String workflowId;
private String error;
private String state;
// TODO: Transition the provisioning progress from a string to detailed array of objects
private String provisioningProgress;
private Instant provisionStartTime;
private Instant provisionEndTime;
private User user;
private Map<String, Object> userOutputs;
private List<ResourceCreated> resourcesCreated;
/**
* Instantiate the object representing the workflow state
*
* @param workflowId The workflow ID representing the given workflow
* @param error The error message if there is one for the current workflow
* @param state The state of the current workflow
* @param provisioningProgress Indicates the provisioning progress
* @param provisionStartTime Indicates the start time of the whole provisioning flow
* @param provisionEndTime Indicates the end time of the whole provisioning flow
* @param user The user extracted from the thread context from the request
* @param userOutputs A map of essential API responses for backend to use and lookup.
* @param resourcesCreated A map of all the resources created.
*/
public WorkflowState(
String workflowId,
String error,
String state,
String provisioningProgress,
Instant provisionStartTime,
Instant provisionEndTime,
User user,
Map<String, Object> userOutputs,
List<ResourceCreated> resourcesCreated
) {
this.workflowId = workflowId;
this.error = error;
this.state = state;
this.provisioningProgress = provisioningProgress;
this.provisionStartTime = provisionStartTime;
this.provisionEndTime = provisionEndTime;
this.user = user;
this.userOutputs = Map.copyOf(userOutputs);
this.resourcesCreated = List.copyOf(resourcesCreated);
}
private WorkflowState() {}
/**
* Instatiates a new WorkflowState from an input stream
* @param input the input stream to read from
* @throws IOException if the workflowId cannot be read from the input stream
*/
public WorkflowState(StreamInput input) throws IOException {
this.workflowId = input.readString();
this.error = input.readOptionalString();
this.state = input.readOptionalString();
this.provisioningProgress = input.readOptionalString();
this.provisionStartTime = input.readOptionalInstant();
this.provisionEndTime = input.readOptionalInstant();
// TODO: fix error: cannot access Response issue when integrating with access control
// this.user = input.readBoolean() ? new User(input) : null;
this.userOutputs = input.readBoolean() ? input.readMap() : null;
this.resourcesCreated = input.readList(ResourceCreated::new);
}
/**
* Constructs a builder object for workflowState
* @return Builder Object
*/
public static Builder builder() {
return new Builder();
}
/**
* Class for constructing a Builder for WorkflowState
*/
public static class Builder {
private String workflowId = null;
private String error = null;
private String state = null;
private String provisioningProgress = null;
private Instant provisionStartTime = null;
private Instant provisionEndTime = null;
private User user = null;
private Map<String, Object> userOutputs = null;
private List<ResourceCreated> resourcesCreated = null;
/**
* Empty Constructor for the Builder object
*/
public Builder() {}
/**
* Builder method for adding workflowID
* @param workflowId workflowId
* @return the Builder object
*/
public Builder workflowId(String workflowId) {
this.workflowId = workflowId;
return this;
}
/**
* Builder method for adding error
* @param error error
* @return the Builder object
*/
public Builder error(String error) {
this.error = error;
return this;
}
/**
* Builder method for adding state
* @param state state
* @return the Builder object
*/
public Builder state(String state) {
this.state = state;
return this;
}
/**
* Builder method for adding provisioningProgress
* @param provisioningProgress provisioningProgress
* @return the Builder object
*/
public Builder provisioningProgress(String provisioningProgress) {
this.provisioningProgress = provisioningProgress;
return this;
}
/**
* Builder method for adding provisionStartTime
* @param provisionStartTime provisionStartTime
* @return the Builder object
*/
public Builder provisionStartTime(Instant provisionStartTime) {
this.provisionStartTime = provisionStartTime;
return this;
}
/**
* Builder method for adding provisionEndTime
* @param provisionEndTime provisionEndTime
* @return the Builder object
*/
public Builder provisionEndTime(Instant provisionEndTime) {
this.provisionEndTime = provisionEndTime;
return this;
}
/**
* Builder method for adding user
* @param user user
* @return the Builder object
*/
public Builder user(User user) {
this.user = user;
return this;
}
/**
* Builder method for adding userOutputs
* @param userOutputs userOutputs
* @return the Builder object
*/
public Builder userOutputs(Map<String, Object> userOutputs) {
this.userOutputs = userOutputs;
return this;
}
/**
* Builder method for adding resourcesCreated
* @param resourcesCreated resourcesCreated
* @return the Builder object
*/
public Builder resourcesCreated(List<ResourceCreated> resourcesCreated) {
this.resourcesCreated = resourcesCreated;
return this;
}
/**
* Allows building a workflowState
* @return WorkflowState workflowState Object containing all needed fields
*/
public WorkflowState build() {
WorkflowState workflowState = new WorkflowState();
workflowState.workflowId = this.workflowId;
workflowState.error = this.error;
workflowState.state = this.state;
workflowState.provisioningProgress = this.provisioningProgress;
workflowState.provisionStartTime = this.provisionStartTime;
workflowState.provisionEndTime = this.provisionEndTime;
workflowState.user = this.user;
workflowState.userOutputs = this.userOutputs;
workflowState.resourcesCreated = this.resourcesCreated;
return workflowState;
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
XContentBuilder xContentBuilder = builder.startObject();
if (workflowId != null) {
xContentBuilder.field(WORKFLOW_ID_FIELD, workflowId);
}
if (error != null) {
xContentBuilder.field(ERROR_FIELD, error);
}
if (state != null) {
xContentBuilder.field(STATE_FIELD, state);
}
if (provisioningProgress != null) {
xContentBuilder.field(PROVISIONING_PROGRESS_FIELD, provisioningProgress);
}
if (provisionStartTime != null) {
xContentBuilder.field(PROVISION_START_TIME_FIELD, provisionStartTime.toEpochMilli());
}
if (provisionEndTime != null) {
xContentBuilder.field(PROVISION_END_TIME_FIELD, provisionEndTime.toEpochMilli());
}
if (user != null) {
xContentBuilder.field(USER_FIELD, user);
}
if (userOutputs != null && !userOutputs.isEmpty()) {
xContentBuilder.field(USER_OUTPUTS_FIELD, userOutputs);
}
if (resourcesCreated != null && !resourcesCreated.isEmpty()) {
xContentBuilder.field(RESOURCES_CREATED_FIELD, resourcesCreated.toArray());
}
return xContentBuilder.endObject();
}
@Override
public void writeTo(StreamOutput output) throws IOException {
output.writeString(workflowId);
output.writeOptionalString(error);
output.writeOptionalString(state);
output.writeOptionalString(provisioningProgress);
output.writeOptionalInstant(provisionStartTime);
output.writeOptionalInstant(provisionEndTime);
if (user != null) {
user.writeTo(output);
} else {
output.writeBoolean(false);
}
if (userOutputs != null) {
output.writeBoolean(true);
output.writeMap(userOutputs);
} else {
output.writeBoolean(false);
}
output.writeList(resourcesCreated);
}
/**
* Parse raw json content into a Template instance.
*
* @param parser json based content parser
* @return an instance of the template
* @throws IOException if content can't be parsed correctly
*/
public static WorkflowState parse(XContentParser parser) throws IOException {
String workflowId = null;
String error = null;
String state = null;
String provisioningProgress = null;
Instant provisionStartTime = null;
Instant provisionEndTime = null;
User user = null;
Map<String, Object> userOutputs = new HashMap<>();
List<ResourceCreated> resourcesCreated = new ArrayList<>();
ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser);
while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
String fieldName = parser.currentName();
parser.nextToken();
switch (fieldName) {
case WORKFLOW_ID_FIELD:
workflowId = parser.text();
break;
case ERROR_FIELD:
error = parser.text();
break;
case STATE_FIELD:
state = parser.text();
break;
case PROVISIONING_PROGRESS_FIELD:
provisioningProgress = parser.text();
break;
case PROVISION_START_TIME_FIELD:
provisionStartTime = ParseUtils.parseInstant(parser);
break;
case PROVISION_END_TIME_FIELD:
provisionEndTime = ParseUtils.parseInstant(parser);
break;
case USER_FIELD:
user = User.parse(parser);
break;
case USER_OUTPUTS_FIELD:
ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser);
while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
String userOutputsFieldName = parser.currentName();
switch (parser.nextToken()) {
case VALUE_STRING:
userOutputs.put(userOutputsFieldName, parser.text());
break;
case START_OBJECT:
userOutputs.put(userOutputsFieldName, parseStringToStringMap(parser));
break;
default:
throw new IOException("Unable to parse field [" + userOutputsFieldName + "] in a user_outputs object.");
}
}
break;
case RESOURCES_CREATED_FIELD:
try {
ensureExpectedToken(XContentParser.Token.START_ARRAY, parser.currentToken(), parser);
while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
resourcesCreated.add(ResourceCreated.parse(parser));
}
} catch (Exception e) {
if (e instanceof ParsingException || e instanceof XContentParseException) {
throw new FlowFrameworkException("Error parsing newly created resources", RestStatus.INTERNAL_SERVER_ERROR);
}
throw e;
}
break;
default:
throw new IOException("Unable to parse field [" + fieldName + "] in a workflowState object.");
}
}
return new Builder().workflowId(workflowId)
.error(error)
.state(state)
.provisioningProgress(provisioningProgress)
.provisionStartTime(provisionStartTime)
.provisionEndTime(provisionEndTime)
.user(user)
.userOutputs(userOutputs)
.resourcesCreated(resourcesCreated)
.build();
}
/**
* The workflowID associated with this workflow-state
* @return the workflowId
*/
public String getWorkflowId() {
return workflowId;
}
/**
* The main error seen in the workflow state if there is one
* @return the error
*/
public String getError() {
return error;
}
/**
* The state of the current workflow
* @return the state
*/
public String getState() {
return state;
}
/**
* The state of the current provisioning
* @return the provisioningProgress
*/
public String getProvisioningProgress() {
return provisioningProgress;
}
/**
* The start time for the whole provision flow
* @return the provisionStartTime
*/
public Instant getProvisionStartTime() {
return provisionStartTime;
}
/**
* The end time for the whole provision flow
* @return the provisionEndTime
*/
public Instant getProvisionEndTime() {
return provisionEndTime;
}
/**
* User that created and owns this workflow
* @return the user
*/
public User getUser() {
return user;
}
/**
* A map of essential API responses
* @return the userOutputs
*/
public Map<String, Object> userOutputs() {
return userOutputs;
}
/**
* A map of all the resources created
* @return the resources created
*/
public List<ResourceCreated> resourcesCreated() {
return resourcesCreated;
}
@Override
public String toString() {
return "WorkflowState [workflowId="
+ workflowId
+ ", error="
+ error
+ ", state="
+ state
+ ", provisioningProgress="
+ provisioningProgress
+ ", userOutputs="
+ userOutputs
+ ", resourcesCreated="
+ resourcesCreated
+ "]";
}
} |
/*
* Copyright (c) 2013, DIY-Remote Contributors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of the StrangeWay.org nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.strangeway.diyremote.scripting;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* @author Yuriy Artamonov
*/
public class HttpUtils {
public static String get(String url) {
HttpGet request = new HttpGet(url);
HttpClient client = HttpClientBuilder.create().build();
StringBuilder contentBuilder = new StringBuilder();
processRequest(request, client, contentBuilder);
return contentBuilder.toString();
}
public static String get(String url, String username, String password) {
HttpGet request = new HttpGet(url);
if (username == null)
username = "";
if (password == null)
password = "";
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
Credentials credentials = new UsernamePasswordCredentials(username, password);
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create()
.setDefaultCredentialsProvider(credentialsProvider)
.build();
StringBuilder contentBuilder = new StringBuilder();
processRequest(request, client, contentBuilder);
return contentBuilder.toString();
}
private static void processRequest(HttpGet request, HttpClient client, StringBuilder contentBuilder) {
try {
HttpResponse result = client.execute(request);
if (result.getStatusLine().getStatusCode() == 200) {
InputStream content = result.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = rd.readLine()) != null) {
contentBuilder.append(line).append("\n");
}
}
} catch (Exception ignored) {
}
}
} |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CurrencyAccountComponent } from './components/currency-account/currency-account.component';
import { HomeComponent } from './components/home/home.component';
import { ForgotPasswordComponent } from './components/login/forgot-password/forgot-password.component';
import { LoginComponent } from './components/login/login.component';
import { ConfirmComponent } from './components/register/confirm/confirm.component';
import { RegisterComponent } from './components/register/register.component';
import { UserOperationClaimComponent } from './components/user/user-operation-claim/user-operation-claim.component';
import { UserComponent } from './components/user/user.component';
import { LoginGuard } from './guards/login.guard';
import { CompanyComponent } from './components/company/company.component';
const routes: Routes = [
{ path: '', component: HomeComponent, canActivate: [LoginGuard] },
{ path: 'currency-account', component: CurrencyAccountComponent, canActivate: [LoginGuard] },
{ path: 'user', component: UserComponent, canActivate: [LoginGuard] },
{ path: 'company', component: CompanyComponent, canActivate: [LoginGuard] },
{ path: 'user-operation-claim', component: UserComponent, canActivate: [LoginGuard] },
{ path: 'user-operation-claim/:value', component: UserOperationClaimComponent, canActivate: [LoginGuard] },
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'registerConfirm', component: LoginComponent },
{ path: 'registerConfirm/:value', component: ConfirmComponent },
{ path: 'forgot-password/:value', component: ForgotPasswordComponent },
{ path: 'forgot-password', component: LoginComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { } |
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:page_transition/page_transition.dart';
import 'package:recipe_app/models/recipe.dart';
import 'package:recipe_app/pages/NavPage.dart';
import 'package:recipe_app/pages/landing.dart';
import 'package:recipe_app/pages/login.dart';
import 'package:recipe_app/pages/recentSearches.dart';
import 'package:recipe_app/pages/recipeInformation.dart';
import 'package:recipe_app/pages/reviews.dart';
import 'package:recipe_app/pages/signup.dart';
import 'package:recipe_app/pages/Data/recipes.dart' as recipes;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky); //to hide upper and lower bars
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
scaffoldBackgroundColor: const Color.fromRGBO(240, 240, 240, 1),
//colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
initialRoute: '/reviews',
routes: {
'/': (context) => const LandingPage(),
'/reviews': (context) => Reviews(recipe: recipes.recipes[1]),
},
onGenerateRoute: (settings) {
switch (settings.name) {
case '/login':
return PageTransition(
child: const LoginPage(),
type: PageTransitionType.fade,
duration: const Duration(milliseconds: 400),
reverseDuration: const Duration(milliseconds: 200),
settings: settings,
);
case '/signup':
return PageTransition(
child: const SignUpPage(),
type: PageTransitionType.fade,
duration: const Duration(milliseconds: 350),
reverseDuration: const Duration(milliseconds: 200),
settings: settings,
);
case '/navPage':
return PageTransition(
child: const NavPage(),
type: PageTransitionType.fade,
duration: const Duration(milliseconds: 350),
reverseDuration: const Duration(milliseconds: 200),
settings: settings,
);
case '/recentSearches':
return PageTransition(
child: const RecentSearches(),
type: PageTransitionType.fade,
duration: const Duration(milliseconds: 350),
reverseDuration: const Duration(milliseconds: 200),
settings: settings,
);
case '/reviews':
final args = settings.arguments;
if(args is Recipe) {
return PageTransition(
child: Reviews(recipe: args),
type: PageTransitionType.fade,
duration: const Duration(milliseconds: 350),
reverseDuration: const Duration(milliseconds: 200),
settings: settings,
);
}else{
return null;
}
case '/recipeInformation':
final args = settings.arguments;
if(args is Recipe) {
return PageTransition(
child: RecipeInformation(recipe: args),
type: PageTransitionType.fade,
duration: const Duration(milliseconds: 350),
reverseDuration: const Duration(milliseconds: 200),
settings: settings,
);
}else{
return null;
}
default:
return null;
}
},
);
}
} |
import { ActionRowBuilder, APISelectMenuOption, ApplicationCommand, ApplicationCommandData, ApplicationCommandType, AttachmentBuilder, ButtonBuilder, ButtonStyle, CacheType, ChatInputCommandInteraction, ForumChannel, OverwriteType, PermissionFlagsBits, SortOrderType, StringSelectMenuBuilder, ThreadAutoArchiveDuration } from "discord.js";
import fs from 'fs';
import BaseCommand from "../../structures/handlers/BaseCommand";
import Client from "../../structures/overwrite/Client";
import { CommandType, deferReply, getChannel, _replyNullChannel, _replyNullGuild } from "../../utils/ConfigUtil";
import { channel_about, main_guild, roles_botowner, roles_colors, roles_event, roles_server, roles_support, role_botowner_bot, role_event_toxic } from "../../utils/IDs";
export default class About extends BaseCommand {
// Основные параметры
name: string = "about";
usage: string = "Заполнить канал About";
type: string[] = [ CommandType.SlashApplication ];
slash: ApplicationCommandData = {
name: this.name,
description: this.usage,
type: ApplicationCommandType.ChatInput,
options: [],
dmPermission: false,
defaultMemberPermissions: PermissionFlagsBits.Administrator
};
requireClient: boolean = true;
constructor() { super(); }
async onChatInputCommand(interaction: ChatInputCommandInteraction<CacheType>, client: Client): Promise<boolean> {
client.logger.send(`[COMMANDS|${this.name.toUpperCase()}|${interaction.user.id}] ${this.usage}`);
if (!interaction.guild || !interaction.member) return _replyNullGuild(interaction);
const channel: ForumChannel | null = await getChannel(ForumChannel, client.channels, channel_about);
if (!channel) return _replyNullChannel(interaction);
channel.edit({
name: "「📓」о-сервере",
position: 1,
parent: null,
permissionOverwrites: [
{
id: main_guild,
type: OverwriteType.Role,
allow: [ PermissionFlagsBits.ViewChannel, PermissionFlagsBits.CreateInstantInvite, PermissionFlagsBits.AddReactions, PermissionFlagsBits.UseExternalEmojis, PermissionFlagsBits.ReadMessageHistory ],
deny: [ PermissionFlagsBits.SendMessages, PermissionFlagsBits.SendMessagesInThreads, PermissionFlagsBits.UseApplicationCommands ]
},
{
id: role_botowner_bot,
type: OverwriteType.Role,
deny: [ PermissionFlagsBits.ViewChannel ]
}
]
});
channel.setDefaultSortOrder(SortOrderType.CreationDate);
channel.setAvailableTags([ { name: "Правила" }, { name: "Оповещения" }, { name: "Инструкция" } ]);
const threads = (await channel.threads.fetch()).threads;
threads.forEach((t) => t.delete().catch(() => {}));
let topic = "Правила сервера $URL1" + "\n" +
"Новости сервера $URL2" + "\n" +
"Новоприбывшие $URL3" + "\n" +
"Роли $URL4" + "\n" +
"Бонусы подписки $URL5" + "\n" +
"Статистика $URL6" + "\n" +
"Правила приглашения ботов $URL7" + "\n" +
"Система уровней $URL8";
// Система уровней
let cmd: ApplicationCommand | undefined = client.application.commands.cache.find((c: ApplicationCommand) => c.name === 'profile');
let thread = await channel.threads.create({
name: 'Система уровней',
autoArchiveDuration: ThreadAutoArchiveDuration.OneWeek,
message: {
content: "На сервере работает система уровней, которая открывает доступ к различным способам кастомизации своего профиля и бонусам." + "\n\n" + "**Как посмотреть свой уровень?**" + "\n" + `С помощью команды ${cmd ? `</${cmd.name}:${cmd.id}>` : "`/profile`" } ты можешь открыть профиль любого пользователя.` + "\n\n" + "**Как фармить уровень?**" + "\n" + "За любые действия на сервере:" + "\n" + "> Отправка сообщений" + "\n" + "> Прикрепление эмодзи, стикеров и файлов" + "\n" + "> Общение в голосовом чате" + "\n" + "… и некоторые другие активности, тебе начисляется опыт. До 60го уровня кол-во опыта, необходимого для повышения лвл-а - равно 1000. Для получения 61го и выше - потребуется больше опыта. Максимальный уровень - 120." + "\n\n" + "**Какие есть бонусы за повышение уровня?**" + "\n" + "10+ - возможность создавать голосования и опросы." + "\n" + "20+ - возможность пригласить своего бота на сервер." + "\n" + "30+ - доступ к команде /selfsacrifice" + "\n" + "50+ - выбор цветной роли. При её получении открывается возможность встраивать ссылки, использовать внешние эмодзи, стикеры и др." + "\n" + "60+ - возможность изменить фон профиля." + "\n\n" + "**Почему бот не получает опыт?**" + "\n" + "По аналогии с политикой Discord - боты имеют свой профиль, однако какой-либо опыт получать не способы. Взаимодействие с ними, присваивается пользователю." + "\n\n" + "**Почему мой уровень понизился?**" + "\n" + "Первого числа каждого месяца происходит автоматический сброс уровней всех участников сервера:" + "\n" + "> с 1 по 9 - снижается до 1," + "\n" + "> с 10 по 19 - снижается до 10" + "\n" + "> с 20 по 29 - снижается до 20" + "\n" + "> с 30 до 120 - снижается до 30." + "\n" + "При ливе с сервера также производится сброс." + "\n\n---",
components: [
new ActionRowBuilder<ButtonBuilder>()
.addComponents([
new ButtonBuilder()
.setCustomId("button_profile_my")
.setLabel("Открыть профиль")
.setStyle(ButtonStyle.Primary)
])
],
files: [ new AttachmentBuilder("./assets/about_lvl.png", { name: "about_lvl.png" }) ]
}
}).catch(() => {});
if (thread && thread.lastMessage) topic = topic.replace("$URL8", thread.lastMessage.url);
// Приглашение ботов
cmd = client.application.commands.cache.find((c: ApplicationCommand) => c.name === 'botowner');
thread = await channel.threads.create({
name: 'Правила приглашения ботов',
autoArchiveDuration: ThreadAutoArchiveDuration.OneWeek,
message: {
content: "Опытные пользователи этого сервера с уровнем 30 и выше, могут пригласить своего бота на Не ITшники: Хвастаться, рекламировать и тестить свои команды здесь." + `\n${cmd ? `</${cmd.name}:${cmd.id}>` : "`/botowner`" }` + "\n\n" + "**Стоит соблюдать пару правил:**" + "\n\n" + "> Приглашать можно только своих ботов. Если увижу бота на лям серверов - устрою допрос." + "\n\n" + "> Добавить бота - это значит взять полную ответственность за его действия. Нарушение правил сообщества Discord, условий использования Discord или правил сервера приведет к блокировке аккаунта." + "\n\n" + "> Частое переприглашение ботов под запретом. Просьбы: кикни этого бота и пригласи другого - мы не терпим." + "\n\n" + "> Бот может быть автоматически выгнан с сервера после 45 (иногда 30) дней инактивности. Под активностью считаются: отправка сообщений / вход в голосовой чат." + "\n\n" + "> Бот может быть изгнан с сервера за многочисленные жалобы на спам." + "\n\n" + "> Нужны особые права для бота? Обращайся к модераторам." + "\n\n---",
files: [ new AttachmentBuilder("./assets/about_bot.png", { name: "about_bot.png" }) ],
components: [
new ActionRowBuilder<ButtonBuilder>()
.addComponents([
new ButtonBuilder()
.setCustomId("button_botowners_invite")
.setLabel("Пригласить бота")
.setStyle(ButtonStyle.Primary)
])
]
}
}).catch(() => {});
if (thread && thread.lastMessage) topic = topic.replace("$URL7", thread.lastMessage.url);
// Статистика
thread = await channel.threads.create({
name: 'Статистика',
autoArchiveDuration: ThreadAutoArchiveDuration.OneWeek,
message: {
content: "Статистика обновляется автоматически раз в час." + "\n\n---",
files: [ new AttachmentBuilder("./assets/about_stats.png", { name: "about_stats.png" }) ]
}
}).catch(() => {});
if (thread && thread.lastMessage) topic = topic.replace("$URL6", thread.lastMessage.url);
client.db.set("about_thread_stats", `${thread?.id}`);
// Бонусы подписки
cmd = client.application.commands.cache.find((c: ApplicationCommand) => c.name === 'role');
thread = await channel.threads.create({
name: 'Бонусы подписки',
autoArchiveDuration: ThreadAutoArchiveDuration.OneWeek,
message: {
content: "На данный момент существует два способа поддержать сервер финансово: **подписка на Boosty.to** и **Nitro-буст**." + "\n\n" + "**Boosty.to**" + "\n" + "Подписка на boosty.to разделена на несколько уровней:" + "\n" + "B0 - открывает доступ к приватным чатам и предоставляет специальную роль, предоставляющую бонусы эквивалентные 60-му уровню на сервере." + "\n" + "B1 - возможность создать свою уникальную роль на сервере (произвольные название и иконка, не нарушающие правилам сервера)." + `${cmd ? `</${cmd.name}:${cmd.id}>` : "`/role`" }` + "\n" + "B2 - доступ к переключателю `hoist` для кастомных ролей (Выделять роль в списке пользователей)." + "\n" + "B3 - TBD." + "\n\n" + "**Nitro-буст сервера**" + "\n" + "Бонусы эквивалентны уровню B1 подписки на Boosty.to." + "\n\n---",
components: [
new ActionRowBuilder<ButtonBuilder>()
.addComponents([
new ButtonBuilder()
.setLabel("Boosty.to")
.setURL("https://boosty.to/iamnotacoder")
.setStyle(ButtonStyle.Link)
])
],
files: [ new AttachmentBuilder("./assets/about_boost.png", { name: "about_boost.png" }) ]
}
}).catch(() => {});
if (thread && thread.lastMessage) topic = topic.replace("$URL5", thread.lastMessage.url);
// Роли
let options: APISelectMenuOption[] = [];
for(let role_id of roles_colors) {
const role = await interaction.guild.roles.fetch(role_id).catch(() => {});
if (role) options.push({
label: role.name,
value: role_id
});
}
thread = await channel.threads.create({
name: 'Роли',
autoArchiveDuration: ThreadAutoArchiveDuration.OneWeek,
message: {
content: "**Обслуживающий персонал сервера**:" + "\n" + roles_server.map((r) => `<@&${r}>`).join(", ") + "\n\n" + "**Роли саппортеров:**" + "\n" + roles_support.map((r) => `<@&${r}>`).join(", ") + (thread && thread.lastMessage ? "\n" + "Подробнее о них можешь посмотреть тут:" + "\n" + thread.lastMessage.url : "") + "\n" + "Все саппорт-роли выдаются и снимаются автоматически." + "\n\n" + "**Цветные роли**:" + "\n" + roles_colors.map((r) => `<@&${r}>`).join(", ") + "\n\n" + "**Особые роли**:" + "\n" + roles_event.map((r) => `<@&${r}>`).join(", ") + "\n" + `<@&${role_event_toxic}> можно получить самостоятельно по достижению 30го уровня, однако снять её уже не получится.` + "\n\n" + "**Приглашение ботов**:" + "\n" + roles_botowner.map((r) => `<@&${r}>`).join(", ") + "\n\n---",
components: [
new ActionRowBuilder<StringSelectMenuBuilder>()
.addComponents([
new StringSelectMenuBuilder()
.setCustomId("select_color_roles")
.setMinValues(0)
.setMaxValues(1)
.setPlaceholder("Выбери цветную роль [LVL 50+]")
.setOptions(options.splice(0, options.length > 25 ? 25 : options.length))
])
],
files: [ new AttachmentBuilder("./assets/about_roles.png", { name: "about_roles.png" }) ],
allowedMentions: {
roles: [],
users: []
}
}
}).catch(() => {});
if (thread && thread.lastMessage) topic = topic.replace("$URL4", thread.lastMessage.url);
// Новоприбывшие
thread = await channel.threads.create({
name: 'Новоприбывшие',
autoArchiveDuration: ThreadAutoArchiveDuration.OneWeek,
message: {
content: "Поприветствуем новичков на сервере!" + "\n\n---",
files: [ new AttachmentBuilder("./assets/about_joined.png", { name: "about_joined.png" }) ]
}
}).catch(() => {});
if (thread && thread.lastMessage) topic = topic.replace("$URL3", thread.lastMessage.url);
client.db.set("about_thread_joined", `${thread?.id}`);
// Новости сервера
thread = await channel.threads.create({
name: 'Новости сервера',
autoArchiveDuration: ThreadAutoArchiveDuration.OneWeek,
message: {
content: "Новости и оповещения об обновлении сервера!" + "\n\n---",
files: [ new AttachmentBuilder("./assets/about_news.png", { name: "about_news.png" }) ]
}
}).catch(() => {});
if (thread && thread.lastMessage) topic = topic.replace("$URL2", thread.lastMessage.url);
client.db.set("about_thread_news", `${thread?.id}`);
// Новости сервера
let rulesMessage = await fs.promises.readFile("./assets/rules.txt").catch(console.error) ?? "TBD";
thread = await channel.threads.create({
name: 'Правила сервера',
autoArchiveDuration: ThreadAutoArchiveDuration.OneWeek,
message: {
content: `${rulesMessage}` + "\n\n---",
files: [ new AttachmentBuilder("./assets/about_rules.png", { name: "about_rules.png" }) ]
}
}).catch(console.error);
if (thread && thread.lastMessage) topic = topic.replace("$URL1", thread.lastMessage.url);
channel.setTopic(topic);
return deferReply(interaction);
}
} |
import React, { useContext, useEffect, useState } from "react";
import PosContext from "../../../../../context/posContext";
import { getPlatosByCategoriaId } from "../../../../../services/categoriaService";
import PosPlato from "./PosPlato";
const PosPlatos = () => {
const [platos, setPlatos] = useState([]);
const { objCategoriaGlobal } = useContext(PosContext);
useEffect(() => {
if (objCategoriaGlobal) {
getPlatosByCategoriaId(objCategoriaGlobal.categoria_id).then((rpta) => {
if(rpta.data.ok) {
setPlatos(rpta.data.content.Platos)
};
});
}
}, [objCategoriaGlobal]);
return (
<div class="carta">
<h3>
Lista de Platos Categoria: {" "}
<span class="color-secundario">
{objCategoriaGlobal ? objCategoriaGlobal.categoria_nom : "Seleccione una categoria"}
</span>
</h3>
<div class="carta__platos">
{
platos.map((objPlato) => {
return <PosPlato key={objPlato.plato_id}
objPlato = {
objPlato
} />
})}
</div>
</div>
);
};
export default PosPlatos; |
#region
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ITC.Application.AppService.SystemManagers.ServerFileManagers;
using ITC.Application.Helpers;
using ITC.Domain.Core.Bus;
using ITC.Domain.Core.ModelShare.NewsManagers.NewsContentManagers;
using ITC.Domain.Core.ModelShare.PublishManagers;
using ITC.Domain.Core.ModelShare.SystemManagers.SeverFileManagers;
using ITC.Domain.Core.Notifications;
using ITC.Infra.CrossCutting.Identity.Authorization;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NCore.Enums;
using NCore.Modals;
using NCore.Responses;
using NCore.Systems;
#endregion
namespace ITC.Service.API.Controllers.SystemManagers;
/// <summary>
/// Sever-File
/// </summary>
[Route("[controller]")]
[ApiController]
[Authorize]
public class ServerFileController : ApiController
{
#region Fields
private readonly IServerFileAppService _serverFileAppService;
#endregion
#region Constructors
/// <summary>
/// Hàm dựng
/// </summary>
/// <param name="serverFileAppService"></param>
/// <param name="notifications"></param>
/// <param name="mediator"></param>
public ServerFileController(IServerFileAppService serverFileAppService,
INotificationHandler<DomainNotification> notifications,
IMediatorHandler mediator) :
base(notifications, mediator)
{
_serverFileAppService = serverFileAppService;
}
#endregion
/// <summary>
/// Upload file
/// </summary>
/// <param name="files">Tên file và dữ liệu upload</param>
/// <returns></returns>
[HttpPost("upload-server-file")]
[RequestFormLimits(MultipartBodyLengthLimit = DocHelper.SizeLimit)]
[RequestSizeLimit(DocHelper.SizeLimit)]
public async Task<IActionResult> UploadFile(IFormCollection files)
{
if (!ModelState.IsValid)
{
NotifyModelStateErrors();
return NResponseCommand(false, "");
}
// Lấy danh sách các file truyền lên
var lFile = files.Files.ToList();
// Gán dữ liệu các thông tin đính kèm vào model trước khi gửi đi xử lý
var model = new UploadFileEventModel
{
Link = "",
Name = files["name"],
Description = files["description"],
ParentId = files["ParentId"],
FileType = Convert.ToInt32(files["fileType"]),
VideoType = Convert.ToInt32(files["videoType"]),
IsLocal = true,
FileModels = lFile
};
var idFile = await _serverFileAppService.UploadFile(model);
var info = await _serverFileAppService.ViewFile(idFile);
if (info != null)
return Ok(new AvatarModal
{
Id = info.Id,
IsLocal = info.IsLocal,
Name = info.Name,
Link = info.IsLocal ? info.FilePath : info.LinkUrl
});
return Ok(new AvatarModal());
}
/// <summary>
/// Upload file
/// </summary>
/// <param name="files">Tên file và dữ liệu upload</param>
/// <returns></returns>
[HttpPost("upload-file")]
[RequestFormLimits(MultipartBodyLengthLimit = DocHelper.SizeLimit)]
[RequestSizeLimit(DocHelper.SizeLimit)]
public async Task<IActionResult> UploadServerFile(IFormCollection files)
{
if (!ModelState.IsValid)
{
NotifyModelStateErrors();
return NResponseCommand(false, "");
}
// Lấy danh sách các file truyền lên
var lFile = files.Files.ToList();
// Gán dữ liệu các thông tin đính kèm vào model trước khi gửi đi xử lý
var model = new UploadFileEventModel
{
Link = "",
Name = files["name"],
Description = files["description"],
ParentId = files["ParentId"],
FileType = Convert.ToInt32(files["fileType"]),
VideoType = Convert.ToInt32(files["videoType"]),
IsLocal = true,
FileModels = lFile
};
var idFile = await _serverFileAppService.UploadServerFile(model);
return Ok(new UploadFileDto()
{
Link = idFile
});
}
/// <summary>
/// Upload file đính kèm
/// </summary>
/// <param name="files">Tên file và dữ liệu upload</param>
/// <returns></returns>
[HttpPost("upload-file-attack")]
[RequestFormLimits(MultipartBodyLengthLimit = DocHelper.SizeLimit)]
[RequestSizeLimit(DocHelper.SizeLimit)]
public async Task<IActionResult> UploadFileAttack(IFormCollection files)
{
if (!ModelState.IsValid)
{
NotifyModelStateErrors();
return NResponseCommand(false, "");
}
// Lấy danh sách các file truyền lên
var lFile = files.Files.ToList();
// Gán dữ liệu các thông tin đính kèm vào model trước khi gửi đi xử lý
var model = new UploadFileEventModel
{
Link = "",
Name = "",
Description = "",
ParentId = "",
FileType = FileTypeEnumeration.File.Id,
VideoType = 0,
IsLocal = true,
FileModels = lFile
};
var result = await _serverFileAppService.UploadFileAttack(model);
return NResponseCommand(result.ResultCommand, result);
}
/// <summary>
/// Upload file đính kèm nhiều người dùng
/// </summary>
/// <param name="files">Tên file và dữ liệu upload</param>
/// <returns></returns>
[HttpPost("upload-file-attack-peoples")]
[RequestFormLimits(MultipartBodyLengthLimit = DocHelper.SizeLimit)]
[RequestSizeLimit(DocHelper.SizeLimit)]
public async Task<IActionResult> UploadFileAttackPeoples(IFormCollection files)
{
if (!ModelState.IsValid)
{
NotifyModelStateErrors();
return NResponseCommand(false, "");
}
// Lấy danh sách các file truyền lên
var lFile = files.Files.ToList();
// Gán dữ liệu các thông tin đính kèm vào model trước khi gửi đi xử lý
int.TryParse(files["fileType"], out var iFileType);
int.TryParse(files["fileGroup"], out var iGroupFile);
int.TryParse(files["isSaveSubmitDocument"], out var iSaveSubmitDocument);
int.TryParse(files["isSaveWithManagement"], out var iSaveWithManagement);
Guid.TryParse(files["managementId"], out _);
var model = new UploadFileEventModel
{
Link = "",
Name = "",
Description = "",
ParentId = "",
FileType = iFileType == 1 ? FileTypeEnumeration.Image.Id : FileTypeEnumeration.File.Id,
VideoType = 0,
IsLocal = true,
FileModels = lFile,
GroupFile = iGroupFile,
IsSaveSubmitDocument = iSaveSubmitDocument,
IsSaveWithManagement = iSaveWithManagement
};
var result = await _serverFileAppService.UploadFileAttack(model);
return NResponseCommand(result.ResultCommand, result);
}
/// <summary>
/// Danh sách server-file
/// </summary>
/// <returns></returns>
[HttpGet("get-paging")]
public async Task<JsonResponse<IEnumerable<ServerFilePagingDto>>> GetPaging(string search, Guid workManagerId)
{
return await Task.Run(() => new
OkResponse<IEnumerable<ServerFilePagingDto>>("",
_serverFileAppService
.GetPaging(search, workManagerId)
.Result));
}
/// <summary>
/// Danh sách server-file theo ID
/// </summary>
/// <returns></returns>
[HttpGet("get-paging-by-id")]
public async Task<JsonResponse<IEnumerable<ServerFilePagingDto>>> GetPagingById(string attackId)
{
return await Task.Run(() => new
OkResponse<IEnumerable<ServerFilePagingDto>>("",
_serverFileAppService
.GetPagingById(attackId).Result));
}
/// <summary>
/// Xóa file dữ liệu
/// </summary>
/// <param name="model">danh sách Id xóa</param>
/// <returns></returns>
[HttpPost("delete")]
public async Task<IActionResult> Delete([FromBody] DeleteModal model)
{
return NResponseCommand(await _serverFileAppService.Delete(model), model);
}
/// <summary>
/// Cập nhật đệ quy dữ liệu
/// </summary>
/// <returns></returns>
[HttpGet("call-de-quy")]
#pragma warning disable CS1998
public async Task<IActionResult> CallDeQuy()
#pragma warning restore CS1998
{
return NResponseCommand(await _serverFileAppService.CallDeQuy(), true);
}
/// <summary>
/// Cập nhật fileName
/// </summary>
/// <param name="model">Model menu</param>
/// <returns></returns>
[HttpPut("update-file-name")]
public IActionResult Edit([FromBody] UpdateFileNameModal model)
{
if (!ModelState.IsValid)
{
NotifyModelStateErrors();
return NResponseCommand(false, model);
}
return NResponseCommand(_serverFileAppService.UpdateFileName(model), model);
}
/// <summary>
/// [Treeview] Trả về tree-view
/// </summary>
/// <returns></returns>
// [CustomAuthorize(ModuleIdentity.MenuManager, TypeAudit.View)]
[HttpGet("get-treeview")]
[CustomAuthorize(ModuleIdentity.ServerFileManager, TypeAudit.View)]
public async Task<JsonResponse<IEnumerable<TreeViewProjectModel>>> GetTreeViewRoot(string userId)
{
return new OkResponse<IEnumerable<TreeViewProjectModel>>(
"", await _serverFileAppService
.GetTreeView(new TreeViewPagingModelLibrary
{
ModuleIdentity =
ModuleIdentity.ServerFileManager,
VSearch = "",
UserId = userId
}));
}
/// <summary>
/// Thêm mới Folder
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost("folder-create")]
[CustomAuthorize(ModuleIdentity.ServerFileManager, TypeAudit.Add)]
public IActionResult Add([FromBody] FolderServerFileEvent model)
{
if (!ModelState.IsValid)
{
NotifyModelStateErrors();
return NResponseCommand(false, model);
}
return NResponseCommand(_serverFileAppService.FolderAdd(model), model);
}
/// <summary>
/// Sửa Folder
/// </summary>
/// <param name="model">Model menu</param>
/// <returns></returns>
[HttpPut("folder-update")]
[CustomAuthorize(ModuleIdentity.ServerFileManager, TypeAudit.Edit)]
public IActionResult Edit([FromBody] FolderServerFileEvent model)
{
if (!ModelState.IsValid)
{
NotifyModelStateErrors();
return NResponseCommand(false, model);
}
return NResponseCommand(_serverFileAppService.FolderUpdate(model), model);
}
/// <summary>
/// Lấy dữ liệu thư mục theo ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("get-by-folder-id/{id:guid}")]
[CustomAuthorize(ModuleIdentity.NewsGroupType, TypeAudit.View)]
public IActionResult GetByFolderId(Guid id)
{
return NResponseCommand(null, _serverFileAppService.GetByFolderId(id));
}
/// <summary>
/// Cập nhật mã cha - con
/// </summary>
/// <param name="model">Model menu</param>
/// <returns></returns>
[HttpPut("parent-update")]
[CustomAuthorize(ModuleIdentity.ServerFileManager, TypeAudit.Edit)]
public IActionResult ParentUpdate([FromBody] FolderServerFileEvent model)
{
if (!ModelState.IsValid)
{
NotifyModelStateErrors();
return NResponseCommand(false, model);
}
return NResponseCommand(_serverFileAppService.ParentUpdate(model), model);
}
#endregion
/// <summary>
/// Dữ liệu chi tiết
/// </summary>
/// <returns></returns>
[HttpGet("detail-paging")]
[CustomAuthorize(ModuleIdentity.ServerFileManager, TypeAudit.Add)]
public async Task<JsonResponse<Pagination<ServerFileDetailPagingDto>>> GetServerFileDetailPagingDto(
string vSearch, int pageSize, int pageNumber, string authorId, Guid serverFileId, int groupContentTypeId)
{
return await Task.Run(() =>
{
var lData = _serverFileAppService.GetServerFileDetailPagingDto(vSearch,
pageSize,
pageNumber,
authorId,
serverFileId,
groupContentTypeId).Result.ToList();
return new OkResponse<Pagination<ServerFileDetailPagingDto>>("",
new Pagination<ServerFileDetailPagingDto>
{
PageLists = lData,
TotalRecord =
lData.Count > 0
? lData[0].TotalRecord
: 0
});
});
}
/// <summary>
/// Lấy dữ liệu ServerFile theo ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("get-detail-by-id/{id:guid}")]
[CustomAuthorize(ModuleIdentity.ServerFileManager, TypeAudit.View)]
public IActionResult GetById(Guid id)
{
return NResponseCommand(null, _serverFileAppService.ViewFile(id).Result);
}
/// <summary>
/// Thêm mới dữ liệu từ đường dẫn khác
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost("upload-difference")]
[CustomAuthorize(ModuleIdentity.ServerFileManager, TypeAudit.Add)]
public async Task<IActionResult> UploadDifference([FromBody] UploadDifferenceEventModal model)
{
if (!ModelState.IsValid)
{
NotifyModelStateErrors();
return NResponseCommand(false, model);
}
return NResponseCommand(await _serverFileAppService.UploadDifference(model), model);
}
/// <summary>
/// Xem file
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("view-file/{id:guid}")]
public async Task<IActionResult> ViewFile(Guid id)
{
var info = _serverFileAppService.ViewFile(id).Result;
if (info.IsLocal)
{
var fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", info.FilePath);
if (System.IO.File.Exists(fullPath))
{
var b = await System.IO.File.ReadAllBytesAsync(fullPath);
return File(b, "application/octet-stream", info.Name);
}
}
else
{
return Ok(info.LinkUrl);
}
return NResponseBadRequest(false);
}
/// <summary>
/// Xem file
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("view-file-link/{id:guid}")]
public async Task<IActionResult> ViewFileLink(Guid id)
{
var info = await _serverFileAppService.ViewFile(id);
return Ok(new AvatarModal
{
Id = info.Id,
IsLocal = info.IsLocal,
Name = info.Name,
Link = info.IsLocal ? info.FilePath : info.LinkUrl
});
// info.IsLocal ?
// // var fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", info.FilePath);
// // if (System.IO.File.Exists(fullPath))
// // {
// // var b = await System.IO.File.ReadAllBytesAsync(fullPath);
// // return File(b, "application/octet-stream", info.Name);
// // }
// Ok("local;" +info.FilePath) :
// Ok(info.LinkUrl);
// return NResponseBadRequest(false);
}
/// <summary>
/// Cập nhật tên file
/// </summary>
/// <param name="model">danh sách Id xóa</param>
/// <returns></returns>
[HttpPut("update-file-name-file")]
public async Task<IActionResult> UpdateFileName([FromBody] UpdateFileNameModal model)
{
if (!ModelState.IsValid)
{
NotifyModelStateErrors();
return NResponseCommand(false, model);
}
return NResponseCommand(await _serverFileAppService.UpdateNameFile(model), model);
}
/// <summary>
/// Trả về danh sách dữ liệu resize image
/// </summary>
/// <param name="model">danh sách dữ liệu nhận từ FE</param>
/// <returns></returns>
[HttpPost("resize-image-type")]
public async Task<JsonResponse<IEnumerable<ResizeImageDto>>> ResizeImageType([FromBody] ResizeImageModal model)
{
return new OkResponse<IEnumerable<ResizeImageDto>>("", await _serverFileAppService.ResizeImageType(model));
}
#endregion
} |
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:seerbit_flutter/new/customization.dart';
import 'package:seerbit_flutter/new/methods.dart';
import 'package:seerbit_flutter/new/payload.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MaterialApp(home: SeerbitTest()));
}
class SeerbitTest extends StatelessWidget {
SeerbitTest({Key? key}) : super(key: key);
SeerbitMethod SeerBit = new SeerbitMethod();
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
height: 1000,
width: 500,
child: Center(
child: TextButton(
onPressed: () => paymentStart(context),
child: Text(
"Checkout",
style: TextStyle(color: Colors.red),
),
),
),
);
}
paymentStart(context) {
PayloadModel payload = PayloadModel(
currency: 'NGN',
email: "hellxo@gmxail.com",
description: "Sneakers",
fullName: "General ZxXXod",
country: "NG",
amount: "102",
transRef: Random().nextInt(2000).toString(),
publicKey: "merchant_public_key",
pocketRef: "",
vendorId: "vendorId",
closeOnSuccess: false,
closePrompt: false,
setAmountByCustomer: false,
tokenize: false,
planId: "",
customization: CustomizationModel(
borderColor: "#000000",
backgroundColor: "#004C64",
buttonColor: "#0084A0",
paymentMethod: [
PayChannel.account,
PayChannel.transfer,
PayChannel.card,
PayChannel.momo
],
confetti: false,
logo: "logo_url || base64",
));
SeerBit.startPayment(context, payload: payload, onSuccess: (_) {
print(_);
}, onCancel: (_) {
print('*' * 400);
});
}
} |
sqrtMeanScaledRows <- function(X, genes_use, sigma, mu) {
if (missing(genes_use)) {
genes_use <- rownames(X)
} else {
if (!all(genes_use %in% rownames(X))) {
l_orig <- length(genes_use)
genes_use <- intersect(genes_use, rownames(X))
warning(sprintf('removing some genes, keeping %d/%d', length(genes_use), l_orig))
}
}
X <- X[genes_use, ]
## TODO: check that mu and sigma are named vectors
if (missing(sigma)) {
sigma <- rowSDs(X)
}
if (missing(mu)) {
mu <- rowMeans(X)
}
if ('dgCMatrix' %in% class(X)) {
# geneset_mask <- genes_use %in% rownames(X)
# res <- divRows_dgc(X@x, X@p, X@i, sigma[genes_use], geneset_mask, ncol(X))[, 1]
res <- enrich_dgc(X@x, X@p, X@i, sigma[genes_use], ncol(X))[, 1]
} else {
res <- Matrix::colSums(X / sigma[genes_use])
}
res <- (1 / sqrt(length(genes_use))) * (res - sum(mu[genes_use] / sigma[genes_use]))
return(res)
}
enrich_cells <- function(
exprs_norm, genesets, min_size=0, max_size=Inf,
mode=c('unweighted', 'weighted')[1],
do_par=FALSE
) {
## TODO: what if only 1 geneset?
## TODO: what if only 1 gene?
## TODO: check for SD=0
## filter genes and genesets
genesets <- lapply(genesets, function(x) intersect(x, rownames(exprs_norm)))
gsl <- lapply(genesets, length)
genesets <- genesets[which(gsl >= min_size & gsl <= max_size)]
## Keep only the relevant genes
genes_all <- Reduce(union, genesets)
exprs_norm <- exprs_norm[genes_all, ]
## Setup stuff for parallel execution
if (do_par) {
plan(multicore)
iter_fxn <- furrr::future_map
} else {
iter_fxn <- purrr::map
}
## Do the appropriate method
if (mode == 'unweighted') {
res <- enrich_cells.unweighted(exprs_norm, genesets, iter_fxn)
} else if (mode == 'weighted') {
res <- enrich_cells.weighted(exprs_norm, genesets, iter_fxn)
}
return(res)
}
enrich_cells.unweighted <- function(exprs_norm, genesets, iter_fxn) {
## precompute some statistics
sigma <- rowSDs(exprs_norm)
mu <- rowMeans(exprs_norm)
X <- genesets %>%
iter_fxn(function(genes_use) {
sqrtMeanScaledRows(exprs_norm, genes_use, sigma, mu)
}) %>%
bind_cols() %>%
data.frame()
colnames(X) <- names(genesets)
rownames(X) <- colnames(exprs_norm)
return(X)
}
enrich_cells.weighted <- function(exprs_norm, genesets, do_par=TRUE) {
## Get PC1 embeddings and loadings for each pathway
pca_res <- genesets %>%
map(intersect, rownames(exprs_norm)) %>%
future_map(function(genes_use) {
X <- Matrix::t(exprs_norm[genes_use, ])
## RSpectra does implicit scaling, which is more memory efficient
res <- RSpectra::svds(X, k=1, opts=list(center=TRUE, scale=TRUE))
loadings <- as.numeric(res$v)
names(loadings) <- genes_use
list(scores = res$u * res$d * sqrt(max(dim(X)) - 1), loadings = loadings)
})
## bind the cell-specific scores for each pathway into table
scores_df <- pca_res %>% map('scores') %>% bind_cols() %>% data.frame()
rownames(scores_df) <- colnames(exprs_norm)
## number of genes is different for each pathway, so we can't bind into table
loadings <- pca_res %>% map('loadings')
## because PCA is unique up to a sign flip, let's make sure that each pathway
## has mostly positive loadings, making it easier to interpret the scores
flip_sign <- loadings %>% map(function(x) as.numeric(sum(x > 0)) / length(x))
flip_sign <- c(-1, 1)[1 + as.integer(flip_sign > .5)]
names(flip_sign) <- names(loadings)
loadings <- map2(loadings, flip_sign, `*`)
scores_df <- data.frame(as.matrix(scores_df) %*% diag(x = flip_sign))
colnames(scores_df) <- names(loadings)
# return(scores_df)
return(list(scores = scores_df, loadings = loadings))
} |
package com.placementcell.services;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.placementcell.dto.StudyMaterialResponse;
import com.placementcell.entities.Links;
import com.placementcell.entities.StudyMaterial;
import com.placementcell.entities.Users;
import com.placementcell.repository.LinksRepository;
import com.placementcell.repository.StudyMaterialRepository;
import com.placementcell.repository.UserRepository;
import com.placementcell.request.StudyMaterialRequest;
import com.placementcell.utility.Message;
import jakarta.transaction.Transactional;
@Service
public class StudyMaterialService {
@Autowired
private StudyMaterialRepository studyMaterialRepository;
@Autowired
private JwtService jwtService;
@Autowired
private LinksRepository linksRepository;
@Autowired
private UserRepository userRepository;
@Transactional
public StudyMaterialResponse addStudyMaterial(StudyMaterialRequest studyMaterialRequest, String token) {
String username = jwtService.extractUserName(token);
Users user = userRepository.FindByEmail(username).get();
StudyMaterial studyMaterial = new StudyMaterial();
studyMaterial.setSubjectName(studyMaterialRequest.getSubjectName());
studyMaterial.setTopicName(studyMaterialRequest.getTopicName());
studyMaterial.setDescription(studyMaterialRequest.getDescription());
// studyMaterial.setLinks(studyMaterialRequest.getLinks());
List<Links> links = new ArrayList<>();
List<String> studyMaterialLinks = studyMaterialRequest.getLinks();
for (String link : studyMaterialLinks) {
Links newLink = new Links();
newLink.setLink(link);
newLink.setStudyMaterial(studyMaterial);
links.add(newLink);
}
linksRepository.saveAll(links);
studyMaterial.setLinks(links);
System.out.println(studyMaterial.getLinks());
studyMaterial.setSuperAdminId(user);
studyMaterial = studyMaterialRepository.save(studyMaterial);
StudyMaterialResponse studyMaterialResponse = new StudyMaterialResponse();
studyMaterialResponse.setTopicName(studyMaterial.getTopicName());
studyMaterialResponse.setSubjectName(studyMaterial.getSubjectName());
studyMaterialResponse.setDescription(studyMaterial.getDescription());
studyMaterialResponse.setLinks(studyMaterialLinks);
String name = ""
+ ((user.getUsersDetails() != null && user.getUsersDetails().getFirstName() != null)
? user.getUsersDetails().getFirstName()
: "")
+ " "
+ ((user.getUsersDetails() != null && user.getUsersDetails().getLastName() != null)
? user.getUsersDetails().getLastName()
: "");
studyMaterialResponse.setAdderName(name.trim());
return studyMaterialResponse;
}
public StudyMaterialResponse updateStudyMaterial(StudyMaterialRequest studyMaterialRequest) {
StudyMaterial studyMaterial = studyMaterialRepository.findById(studyMaterialRequest.getId()).get();
studyMaterial.setSubjectName(studyMaterialRequest.getSubjectName());
studyMaterial.setTopicName(studyMaterialRequest.getTopicName());
studyMaterial.setDescription(studyMaterialRequest.getDescription());
List<Links> links = new ArrayList<>();
List<String> studyMaterialLinks = studyMaterialRequest.getLinks();
for (String link : studyMaterialLinks) {
Links newLink = new Links();
newLink.setLink(link);
}
studyMaterial.setStudyMaterialId(studyMaterialRequest.getId());
studyMaterial.setLinks(links);
studyMaterial = studyMaterialRepository.save(studyMaterial);
StudyMaterialResponse studyMaterialResponse = new StudyMaterialResponse();
studyMaterialResponse.setSubjectName(studyMaterial.getSubjectName());
studyMaterialResponse.setTopicName(studyMaterial.getTopicName());
studyMaterialResponse.setDescription(studyMaterial.getDescription());
studyMaterialResponse.setLinks(studyMaterialLinks);
String name = ""
+ ((studyMaterial.getSuperAdminId().getUsersDetails() != null
&& studyMaterial.getSuperAdminId().getUsersDetails().getFirstName() != null)
? studyMaterial.getSuperAdminId().getUsersDetails().getFirstName()
: "")
+ " "
+ ((studyMaterial.getSuperAdminId().getUsersDetails() != null
&& studyMaterial.getSuperAdminId().getUsersDetails().getLastName() != null)
? studyMaterial.getSuperAdminId().getUsersDetails().getLastName()
: "");
studyMaterialResponse.setAdderName(name.trim());
return studyMaterialResponse;
}
public List<StudyMaterialResponse> getAll() {
List<StudyMaterial> studyMaterials = studyMaterialRepository.findAll();
List<StudyMaterialResponse> studyMaterialResponses = new ArrayList<>();
for (StudyMaterial studyMaterial : studyMaterials) {
StudyMaterialResponse studyMaterialResponse = new StudyMaterialResponse();
studyMaterialResponse.setId(studyMaterial.getStudyMaterialId());
studyMaterialResponse.setSubjectName(studyMaterial.getSubjectName());
studyMaterialResponse.setTopicName(studyMaterial.getTopicName());
studyMaterialResponse.setDescription(studyMaterial.getDescription());
List<Links> linksList = studyMaterial.getLinks(); // Assuming studyMaterial.getLinks() returns a List<Links>
List<String> linkStrings = linksList.stream().map(Links::getLink).collect(Collectors.toList());
studyMaterialResponse.setLinks(linkStrings);
Users user=userRepository.findById(studyMaterial.getSuperAdminId().getId()).get();
String name = ""
+ ((user.getUsersDetails() != null && user.getUsersDetails().getFirstName() != null)
? user.getUsersDetails().getFirstName()+" "
: "")
+ ((user.getUsersDetails() != null && user.getUsersDetails().getLastName() != null)
? user.getUsersDetails().getLastName()
: "");
studyMaterialResponse.setAdderName(name);
studyMaterialResponses.add(studyMaterialResponse);
}
return studyMaterialResponses;
}
public Message delete(int id) {
try {
studyMaterialRepository.deleteById(id);
return new Message("Study Material has been deleted");
} catch (Exception ee) {
ee.printStackTrace();
return new Message("Study Material does not exist");
}
}
} |
from pathlib import Path
import folium
import pandas as pd
import geopandas as gpd
import numpy as np
import streamlit as st
from polygeohasher import polygeohasher
from streamlit_folium import st_folium
#--- PATH SETTINGS ---
current_dir = Path(__file__).parent if "_file_" in locals() else Path.cwd()
css_file = current_dir / "styles" / "main.css"
CENTER_START = [-6.175337169759785, 106.82713616185086]
if "center" not in st.session_state:
st.session_state["center"] = [-6.175337169759785, 106.82713616185086]
string = st.text_input('Please copy paste your Geohash separated by comma here and avoid spaces between geohash character','qqguyu7,qqguyur,qqguyu4,qqguygg,qqguyu1,qqguygr,qqguyff,qqguyuq,qqguz50,qqguyfu,qqguz52,qqguyun,qqguygm,qqguygu,qqguyg7,qqguygq,qqguygx,qqguyup,qqguyfv,qqguyuk,qqguygk,qqguyfg,qqguyut,qqguygz,qqguyfy,qqguyfc,qqguygc,qqguyg4,qqguyfz,qqguyux,qqguyg9,qqguyg3,qqguyus,qqguyuw,qqguyg1,qqguygy,qqguygs,qqguyud,qqguyu3,qqguyue,qqguz4b,qqguyg6,qqguygd,qqguyum,qqguz58,qqguygh,qqguyuj,qqguygv,qqguygj,qqguygn,qqguyu5,qqguyg5,qqguyuh,qqguygp,qqguygf,qqguyu6,qqguyu9,qqguygw,qqguyge,qqguygt')
data_list = string.split(',')
df = pd.DataFrame(data_list)
df.columns = ['geohash']
geohash_df_list = polygeohasher.geohashes_to_geometry(df,'geohash')
gpd_geohash_geom = gpd.GeoDataFrame(geohash_df_list, geometry = geohash_df_list['geometry'], crs = "EPSG:4326")
geojson_geohash = gpd_geohash_geom.to_json()
centroid = gpd_geohash_geom.unary_union.centroid
try:
latitude = float(centroid.y)
longitude = float(centroid.x)
except ValueError:
latitude = None
longitude = None
if latitude is None or longitude is None:
st.error("Invalid latitude or longitude value. Please enter valid latitude and longitude values separated by a comma.")
else:
st.success("Successfully converted latitude and longitude values to float.")
st.session_state["center"] = [latitude, longitude]
m = folium.Map(location=CENTER_START,zoom_start=14)
folium.GeoJson(
geojson_geohash,
name="geohash",
tooltip = folium.GeoJsonTooltip(fields = ['geohash']),
style_function = lambda x: {
'color': 'red',
'weight': 4,
'interactive' : True
}).add_to(m)
st_data = st_folium(m,
center=st.session_state["center"],
width=1200,
height=800)
save = st.text_input('Write you files name here and press ENTER!!')
st.download_button(
label="Download data as JSON",
data=geojson_geohash,
file_name=save + '.geojson',
) |
---
title: Relay Module Reference
sidebar_label: wokwi-relay-module
---
Electrically operated switch

## Pin names
| Name | Description |
| ---- | ------------------------------------------- |
| VCC | Supply voltage |
| GND | Ground |
| IN | Control signal (e.g. from micro-controller) |
| NC | Normally closed |
| COM | Common pin |
| NO | Normally open |
## Attributes
| Name | Description | Default value |
| ---------- | ----------------------------------------- | ------------- |
| transistor | "npn" (active-high) or "pnp" (active-low) | "npn" |
## Operation
The relay is an electronic switch.
When the `IN` pin is high / disconnected, `COM` is connected to `NC` (NC means normally closed).
When the `IN` pin is low, `COM` is connected to `NO` (NO means normally open).
Setting the "transistor" attribute to "pnp" inverts the logic: when `IN` is high, `COM` is connected to `NO`, and when `IN` is low / disconnected, `COM` is connected to `NC`.
## Simulator Examples
- [One relay module controlling two LEDs](https://wokwi.com/projects/347308007359513172) |
import { APIResult } from "./api_result";
import { WeeklyExpenses } from "./expense";
export interface Calculations {
/**
* Gibt das restliche "Guthaben" für diesen Monat aus.
* Abzüglich der kommenden und der getätigten Ausgaben.
* @param month
* @param year
*/
calculate_leftover(
month: number,
year: number
): APIResult<number>
/**
* Gibt die mögliche Einsparung an abhängig von der Eingabe des Zeitraums und Modifiers.
* @param id Ausgabe oder Einnahme
* @param timeframe_modifier
* @param timeframe
*/
calculate_savings(
id: string,
timeframe_modifier: number,
timeframe: TimeFrame
): APIResult<number>
/**
* Gibt die Ausgaben für eine bestimmte Kalenderwoche zurück.
* z.B. für die Anzeige in einem Graph Mo-So + Total
* @param week
*/
show_expenses(
week: number
): APIResult<WeeklyExpenses>
}
enum TimeFrame {
DAILY,
WEEKLY,
MONTHLY,
YEARLY
} |
{-# LANGUAGE FlexibleInstances #-}
module Rearrange where
import Test.QuickCheck
data Sum a b
= First a
| Second b
instance Functor (Sum e) where
fmap _ (First a) = First a
fmap f (Second b) = Second $ f b
data Company a b c
= DeepBlue a c
| Something b
instance Functor (Company e e') where
fmap _ (Something b) = Something b
fmap f (DeepBlue a c) = DeepBlue a $ f c
data More a b
= L a b a
| R b a b
deriving (Eq, Show)
instance Functor (More x) where
fmap f (L a b a') = L a (f b) a'
fmap f (R b a b') = R (f b) a (f b')
instance (Arbitrary a, Arbitrary b) => Arbitrary (More a b) where
arbitrary =
oneof
[ L <$> arbitrary <*> arbitrary <*> arbitrary
, R <$> arbitrary <*> arbitrary <*> arbitrary
]
data Quant a b
= Finance
| Desk a
| Bloor b
deriving (Eq, Show)
instance Functor (Quant a) where
fmap _ Finance = Finance
fmap _ (Desk a) = Desk a
fmap f (Bloor b) = Bloor $ f b
instance (Arbitrary a, Arbitrary b) => Arbitrary (Quant a b) where
arbitrary =
oneof
[ return Finance
, Desk <$> arbitrary
, Bloor <$> arbitrary
]
{- hlint ignore "Use newtype instead of data" -}
data K a b = K a
deriving (Eq, Show)
instance Functor (K a) where
fmap _ (K a) = K a
instance (Arbitrary a, Arbitrary b) => Arbitrary (K a b) where
arbitrary = K <$> arbitrary
data EvilGoateeConst a b = GoatyConst b
deriving (Eq, Show)
instance Functor (EvilGoateeConst a) where
fmap f (GoatyConst b) = GoatyConst $ f b
instance (Arbitrary a, Arbitrary b) => Arbitrary (EvilGoateeConst a b) where
arbitrary = GoatyConst <$> arbitrary
data LiftItOut f a = LiftItOut (f a)
deriving (Eq, Show)
instance (Arbitrary (f a)) => Arbitrary (LiftItOut f a) where
arbitrary = LiftItOut <$> arbitrary
instance Functor f => Functor (LiftItOut f) where
fmap f (LiftItOut fa) = LiftItOut $ fmap f fa
data Parappa f g a = DaWrappa (f a) (g a)
deriving (Eq, Show)
instance (Arbitrary (f a), Arbitrary (g a)) => Arbitrary (Parappa f g a) where
arbitrary = DaWrappa <$> arbitrary <*> arbitrary
instance (Functor f, Functor g) => Functor (Parappa f g) where
fmap f (DaWrappa fa ga) = DaWrappa (fmap f fa) $ fmap f ga
data IgnoreOne f g a b = IgnoringSomething (f a) (g b)
deriving (Eq, Show)
instance Functor g => Functor (IgnoreOne f g a) where
fmap f (IgnoringSomething fa ga) = IgnoringSomething fa $ fmap f ga
instance (Arbitrary (f a), Arbitrary (g b)) => Arbitrary (IgnoreOne f g a b) where
arbitrary = IgnoringSomething <$> arbitrary <*> arbitrary
data Notorious g o a t = Notorious (g o) (g a) (g t)
deriving (Eq, Show)
instance Functor g => Functor (Notorious g o a) where
fmap f (Notorious go ga gt) = Notorious go ga $ fmap f gt
instance (Arbitrary (g o), Arbitrary (g a), Arbitrary (g t) ) => Arbitrary (Notorious g o a t) where
arbitrary = Notorious <$> arbitrary <*> arbitrary <*> arbitrary
data List a = Nil | Cons a (List a)
deriving (Eq, Show)
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons x xs) = Cons (f x) (fmap f xs)
instance Arbitrary a => Arbitrary (List a) where
arbitrary =
frequency
[ (20, Cons <$> arbitrary <*> arbitrary)
, (1, return Nil)
]
data GoatLord a
= NoGoat
| OneGoat a
| MoreGoats (GoatLord a) (GoatLord a) (GoatLord a)
deriving (Eq, Show)
instance Functor GoatLord where
fmap _ NoGoat = NoGoat
fmap f (OneGoat a) = OneGoat $ f a
fmap f (MoreGoats a b c) = MoreGoats x y z
where
x = fmap f a
y = fmap f b
z = fmap f c
instance Arbitrary a => Arbitrary (GoatLord a) where
arbitrary =
frequency
[ (1, OneGoat <$> arbitrary)
, (5, return NoGoat)
, (1, MoreGoats <$> arbitrary <*> arbitrary <*> arbitrary)
] |
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Lista-Contatos-JSTL</title>
</head>
<body>
<c:import url="cabecalho.jsp"/>
<!-- cria o DAO -->
<table>
<!-- PERCORRE CONTATOS montando as linhas da tabela -->
<c:forEach var="contato" items="${contatos}">
<tr>
<td>${contato.nome}</td>
<td>
<c:if test="${not empty contato.email}">
<a href="mailto:${contato.email}">${contato.email}</a>
</c:if>
<c:if test="${empty contato.email}">
Email não informado
</c:if>
</td>
<td>${contato.endereco}</td>
<td><fmt:formatDate value="${contato.dataNascimento.time }"
pattern="dd/MM/yyyy"/></td>
<td><a href="mvc?logica=RemoveContatoLogic&id=${contado.id}">Remover</a></td>
</tr>
</c:forEach>
</table>
<a href="bemvindo.jsp">Voltar</a> <br/>
<c:import url="rodape.jsp"/>
</body>
</html> |
/// © Max Shemetov, 2023
// ignore_for_file: unused_local_variable
import 'package:positive_num/positive_num.dart';
void examplePositiveInt(int someNumber) {
final (:error, :instance) = PositiveInt.create(someNumber);
if (instance != null) {
final positiveInt = instance;
print('Created a PositiveInt, value: $positiveInt');
} else {
print('Error. $error');
}
}
void examplePositiveDouble(double someNumber) {
final result = PositiveDouble.create(someNumber);
if (result.instance != null) {
final positiveDouble = result.instance!;
print('Created a PositiveDouble, value: $positiveDouble');
} else {
print('Error. ${result.error}');
}
}
void examplePositiveNum(num someNumber) {
switch (PositiveNum.create(someNumber)) {
case (:String? error, :PositiveNum instance):
final positiveNum = instance;
print('Created a PositiveNum, value: $positiveNum');
break;
case (:String error, :PositiveNum? instance):
print('Error. $error');
break;
}
}
void main() {
examplePositiveInt(1);
examplePositiveDouble(2.2);
examplePositiveNum(3);
//
examplePositiveInt(-1);
examplePositiveDouble(-2.2);
examplePositiveNum(-3);
} |
package game
import (
"context"
"fmt"
"github.com/dark-enstein/crise/internal/tetra"
utils2 "github.com/dark-enstein/crise/internal/utils"
"github.com/hajimehoshi/ebiten/v2"
"log"
"sync"
)
const (
MAX_TETROMINO_ONSCREEN = 300
ACCELERATION_FACTOR = 0.5
)
// TetrominoManager manages the spawn and despqwn of Tetrominoes in game.
type TetrominoManager struct {
// activeMember is the currently active of current onScreen elements.
activeMember *tetra.Tetromino
// creationCounter defines the cycles of updates before a new Tetromino is spawned
creationCounter int
// activeN is the integer location of the currently active Tetromino in onScreen
activeN int
// onScreenBank stores all the currently displayed Tetromino on screen
onScreenBank []*tetra.Tetromino
// settings holds config settings that TetrominoManager uses to manage the tetris animation
settings *TetroSettings
// handling syncronization and change of state
sync.Mutex
}
// TetroSettings defines the settings used by the manager to manage tetris animation
type TetroSettings struct {
// tIncrement holds the increment value valid, given the current input. It can always be mutated
tIncrement float32
// tIncrementSaved holds the increment value as defined in settings. It never changes.
tIncrementSaved float32
}
// Accelerate increases the value of the increment by a factor to simulate acceleration
func (ts *TetroSettings) Accelerate() {
ts.tIncrement += ACCELERATION_FACTOR
}
// Reset resets the currnetly active increment value to original as set within from settings
func (ts *TetroSettings) Reset() {
ts.tIncrement = ts.tIncrementSaved
}
// NewTetrominoMananger creates a new Tetromino manager. inc is the preferred increment or speed of the Tetromino on key direction directive. Right now it is measured in pixels on the screen, but later it would be changed to be a multiple of utils2.SPRITE_HEIGHT
func NewTetrominoMananger(inc int) *TetrominoManager {
return &TetrominoManager{
onScreenBank: make([]*tetra.Tetromino, 0, MAX_TETROMINO_ONSCREEN),
settings: &TetroSettings{tIncrement: float32(inc)},
}
}
// Add adds a new Tetromino to the screen
func (t *TetrominoManager) Add() {
//rand.Intn(len(tetra.TetraCoordinates))
t.onScreenBank = append(t.onScreenBank, tetra.NewTetromino(tetra.TetraCoordinates[tetra.J], utils2.WALL_WIDTH, utils2.WALL_HEIGHT))
t.activeN = len(t.onScreenBank) - 1
t.activeMember = t.onScreenBank[t.activeN]
}
// Active returns the currently active Tetromino. This is what is currently controllable by the player.
func (t *TetrominoManager) Active() *tetra.Tetromino {
return t.activeMember
}
// OnScreenBank returns all the Tetrominoes currently on screen.
func (t *TetrominoManager) OnScreenBank() []*tetra.Tetromino {
return t.onScreenBank
}
// ActiveTArray returns the 2D array of the currently active Tetromino
func (t *TetrominoManager) ActiveTArray() [][]int {
return t.onScreenBank[t.activeN].Arr
}
// MoveDown moves the tetromino downward
func (t *TetrominoManager) MoveDown() {
log.Println("acquiring move down lock")
t.Lock()
for i := 0; i < len(t.ActiveTArray()); i++ {
fX, fY := t.ActiveTArray()[i][0], t.ActiveTArray()[i][1]
//g.sample[i][0] += INCREMENT
t.onScreenBank[t.activeN].Arr[i][1] += t.inc()
fmt.Printf("moved sprites from %v,%v to %v,%v\n", fX, fY, t.onScreenBank[t.activeN].Arr[i][0], t.onScreenBank[t.activeN].Arr[i][1])
}
log.Println("releasing move down lock")
t.Unlock()
}
// MoveUp moves the tetromino upwards
func (t *TetrominoManager) MoveUp() {
log.Println("acquiring move up lock")
t.Lock()
for i := 0; i < len(t.ActiveTArray()); i++ {
fX, fY := t.ActiveTArray()[i][0], t.ActiveTArray()[i][1]
//g.sample[i][0] += INCREMENT
t.onScreenBank[t.activeN].Arr[i][1] -= t.inc()
fmt.Printf("moved sprites from %v,%v to %v,%v\n", fX, fY, t.onScreenBank[t.activeN].Arr[i][0], t.onScreenBank[t.activeN].Arr[i][1])
}
log.Println("releasing move up lock")
t.Unlock()
}
// MoveLeft moves the tetromino leftward
func (t *TetrominoManager) MoveLeft() {
log.Println("acquiring move left lock")
t.Lock()
for i := 0; i < len(t.ActiveTArray()); i++ {
fX, fY := t.ActiveTArray()[i][0], t.ActiveTArray()[i][1]
t.onScreenBank[t.activeN].Arr[i][0] -= t.inc()
//g.sample[i][1] += INCREMENT
fmt.Printf("moved sprites from %v,%v to %v,%v\n", fX, fY, t.onScreenBank[t.activeN].Arr[i][0], t.onScreenBank[t.activeN].Arr[i][1])
}
log.Println("releasing move left lock")
t.Unlock()
}
// MoveRight moves the tetromino rightward
func (t *TetrominoManager) MoveRight() {
log.Println("acquiring move right lock")
t.Lock()
for i := 0; i < len(t.ActiveTArray()); i++ {
fX, fY := t.ActiveTArray()[i][0], t.ActiveTArray()[i][1]
t.onScreenBank[t.activeN].Arr[i][0] += t.inc()
//g.sample[i][1] += INCREMENT
fmt.Printf("moved sprites from %v,%v to %v,%v\n", fX, fY, t.onScreenBank[t.activeN].Arr[i][0], t.onScreenBank[t.activeN].Arr[i][1])
}
log.Println("releasing move right lock")
t.Unlock()
}
// WillCollide implements collission detection for Tetris
func (t *TetrominoManager) WillCollide(t0 *tetra.Tetromino) {}
// toRealIncrement converts an increment (measured in number of sprites) to real increment (based on the dimensions of the screen)
func toRealIncrement(n int) int {
return n * utils2.SPRITE_HEIGHT
}
func (t *TetrominoManager) Display(ctx context.Context, screen *ebiten.Image) {
//log.Printf("calling build on N tetromino: %v\n", len(t.onScreenBank))
for i := 0; i < len(t.onScreenBank); i++ {
//log.Printf("calling build on tetromino: %v\n", t.onScreenBank[i])
t.onScreenBank[i].Build(ctx)(screen)
}
}
// Accelerate accelerates the current tetromino. On key press
func (t *TetrominoManager) Accelerate() {
t.settings.Accelerate()
}
// ResetInc resets the increment of the current tetromino. On key release
func (t *TetrominoManager) ResetInc() {
t.settings.Reset()
}
// inc returns the current increment value cast into int
func (t *TetrominoManager) inc() int {
return int(t.settings.tIncrement)
}
// IsAccelerated checks if the currently active tetromino is accelerated
func (t *TetrominoManager) IsAccelerated() bool {
if t.settings.tIncrement < t.settings.tIncrementSaved || t.settings.tIncrement == t.settings.tIncrementSaved {
return false
}
return true
} |
import { JSBI, Pair, Percent } from '@jediswap/sdk'
import { darken } from 'polished'
import React, { useState } from 'react'
import { ChevronDown, ChevronUp } from 'react-feather'
import { Link } from 'react-router-dom'
import styled from 'styled-components'
import { useTotalSupply } from '../../data/TotalSupply'
import { useTokenBalance } from '../../state/wallet/hooks'
import { DMSansText } from '../../theme'
import { currencyId } from '../../utils/currencyId'
import { unwrappedToken } from '../../utils/wrappedCurrency'
import { ButtonEmpty, ButtonGradient, ButtonPrimary } from '../Button'
import { transparentize } from 'polished'
import noise from '../../assets/images/noise.png'
import { useColor } from '../../hooks/useColor'
import Card, { LightCard, WhiteOutlineCard, JediPositionCard } from '../Card'
import { AutoColumn } from '../Column'
import CurrencyLogo from '../CurrencyLogo'
import DoubleCurrencyLogo from '../DoubleLogo'
import { RowBetween, RowFixed } from '../Row'
import { Dots } from '../swap/styleds'
import { Separator } from '../../pages/Pool/styleds'
import { useAccountDetails } from '../../hooks'
export const FixedHeightRow = styled(RowBetween)`
height: 24px;
`
export const CardNoise = styled.span`
background: url(${noise});
background-size: cover;
mix-blend-mode: overlay;
border-radius: 12px;
width: 100%;
height: 100%;
opacity: 0.15;
position: absolute;
top: 0;
left: 0;
user-select: none;
`
export const HoverCard = styled(Card)`
border: 1px solid transparent;
:hover {
border: 1px solid ${({ theme }) => darken(0.06, theme.bg2)};
}
`
const StyledPositionCard = styled(LightCard)<{ bgColor: any }>`
border: none;
background: ${({ theme, bgColor }) =>
`radial-gradient(91.85% 100% at 1.84% 0%, ${transparentize(0.8, bgColor)} 0%, ${theme.bg3} 100%) `};
position: relative;
overflow: hidden;
`
const CardText = styled.div<{
textAlign?: string
fontWeight?: number
fontSize?: number
lineHeight?: string
fontColor?: string
}>`
font-family: 'DM Sans', sans-serif;
color: ${({ fontColor, theme }) => (fontColor ? fontColor : theme.jediWhite)};
font-weight: ${({ fontWeight }) => (fontWeight ? fontWeight : 'normal')};
font-size: ${({ fontSize }) => (fontSize ? `${fontSize}px` : '14px')};
line-height: ${({ lineHeight }) => (lineHeight ? lineHeight : '140%')};
text-align: ${({ textAlign }) => (textAlign ? textAlign : 'center')};
`
const ManageText = styled.div`
font-weight: 800;
font-size: 16px;
line-height: 20px;
font-feature-settings: 'salt' on, 'liga' off;
text-transform: uppercase;
letter-spacing: 0.5px;
`
const AddRemoveButton = styled(ButtonPrimary)`
font-size: 24px;
line-height: 20px;
font-weight: 800;
border-radius: 8px;
padding: 22px;
`
interface PositionCardProps {
pair: Pair
showUnwrapped?: boolean
border?: string
}
export function MinimalPositionCard({ pair, showUnwrapped = false, border }: PositionCardProps) {
const { address } = useAccountDetails()
const currency0 = showUnwrapped ? pair.token0 : unwrappedToken(pair.token0)
const currency1 = showUnwrapped ? pair.token1 : unwrappedToken(pair.token1)
const [showMore, setShowMore] = useState(false)
const userPoolBalance = useTokenBalance(address ?? undefined, pair.liquidityToken)
const totalPoolTokens = useTotalSupply(pair.liquidityToken)
const poolTokenPercentage =
!!userPoolBalance && !!totalPoolTokens && JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw)
? new Percent(userPoolBalance.raw, totalPoolTokens.raw)
: undefined
const [token0Deposited, token1Deposited] =
!!pair &&
!!totalPoolTokens &&
!!userPoolBalance &&
// this condition is a short-circuit in the case where useTokenBalance updates sooner than useTotalSupply
JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw)
? [
pair.getLiquidityValue(pair.token0, totalPoolTokens, userPoolBalance, false),
pair.getLiquidityValue(pair.token1, totalPoolTokens, userPoolBalance, false)
]
: [undefined, undefined]
return (
<>
{userPoolBalance && JSBI.greaterThan(userPoolBalance.raw, JSBI.BigInt(0)) ? (
<WhiteOutlineCard border={border} borderRadius={'8px'} padding={'12px 32px'}>
<AutoColumn gap="12px">
<FixedHeightRow>
<RowFixed>
<CardText fontWeight={700} fontSize={18} lineHeight={'100%'}>
Your position
</CardText>
</RowFixed>
</FixedHeightRow>
<Separator style={{ margin: '0px -32px' }} />
<FixedHeightRow>
<RowFixed>
<DoubleCurrencyLogo currency0={currency0} currency1={currency1} size={20} margin={true} />
<CardText fontWeight={700} fontSize={18} lineHeight={'100%'}>
{currency0.symbol}/{currency1.symbol}
</CardText>
</RowFixed>
<RowFixed>
<CardText fontWeight={700} fontSize={18} lineHeight={'100%'}>
{userPoolBalance ? userPoolBalance.toSignificant(4) : '-'}
</CardText>
</RowFixed>
</FixedHeightRow>
<AutoColumn gap="4px" style={{ marginTop: '-4px' }}>
<FixedHeightRow>
<CardText fontSize={16} fontWeight={500} lineHeight={'100%'}>
Your pool share:
</CardText>
<CardText fontSize={16} fontWeight={500} lineHeight={'100%'}>
{poolTokenPercentage ? poolTokenPercentage.toFixed(6) + '%' : '-'}
</CardText>
</FixedHeightRow>
<FixedHeightRow>
<CardText fontSize={16} fontWeight={500} lineHeight={'100%'}>
{currency0.symbol}:
</CardText>
{token0Deposited ? (
<RowFixed>
<CardText fontSize={16} fontWeight={500} lineHeight={'100%'} style={{ marginLeft: '6px' }}>
{token0Deposited?.toSignificant(6)}
</CardText>
</RowFixed>
) : (
'-'
)}
</FixedHeightRow>
<FixedHeightRow>
<CardText fontSize={16} fontWeight={500}>
{currency1.symbol}:
</CardText>
{token1Deposited ? (
<RowFixed>
<CardText fontSize={16} fontWeight={500} style={{ marginLeft: '6px' }}>
{token1Deposited?.toSignificant(6)}
</CardText>
</RowFixed>
) : (
'-'
)}
</FixedHeightRow>
</AutoColumn>
</AutoColumn>
</WhiteOutlineCard>
) : (
<WhiteOutlineCard padding={'12px'} borderRadius={'8px'}>
<CardText fontSize={15} textAlign="left">
<span role="img" aria-label="wizard-icon">
⭐️
</span>{' '}
By adding liquidity you'll earn 0.3% of all trades on this pair proportional to your share of the pool.
Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.
</CardText>
</WhiteOutlineCard>
)}
</>
)
}
export default function FullPositionCard({ pair, border }: PositionCardProps) {
const { address } = useAccountDetails()
const currency0 = unwrappedToken(pair.token0)
const currency1 = unwrappedToken(pair.token1)
const [showMore, setShowMore] = useState(false)
const userPoolBalance = useTokenBalance(address ?? undefined, pair.liquidityToken)
const totalPoolTokens = useTotalSupply(pair.liquidityToken)
const poolTokenPercentage =
!!userPoolBalance && !!totalPoolTokens && JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw)
? new Percent(userPoolBalance.raw, totalPoolTokens.raw)
: undefined
const [token0Deposited, token1Deposited] =
!!pair &&
!!totalPoolTokens &&
!!userPoolBalance &&
// this condition is a short-circuit in the case where useTokenBalance updates sooner than useTotalSupply
JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw)
? [
pair.getLiquidityValue(pair.token0, totalPoolTokens, userPoolBalance, false),
pair.getLiquidityValue(pair.token1, totalPoolTokens, userPoolBalance, false)
]
: [undefined, undefined]
const backgroundColor = useColor(pair?.token0)
return (
<JediPositionCard /*style={{ cursor: 'pointer' }}*/ border={border}>
<CardNoise />
<AutoColumn gap="48px">
<ButtonEmpty padding="0" width="100%" onClick={() => setShowMore(!showMore)}>
<FixedHeightRow>
<RowFixed>
<div style={{ color: 'white' }}>
<DoubleCurrencyLogo currency0={currency0} currency1={currency1} margin={true} size={25} />
</div>
<DMSansText.mediumHeader>
{!currency0 || !currency1 ? <Dots>Loading</Dots> : `${currency0.symbol} / ${currency1.symbol}`}
</DMSansText.mediumHeader>
</RowFixed>
<RowFixed gap="4px">
{/* <ButtonEmpty
padding="6px 8px"
borderRadius="12px"
width="fit-content"
onClick={() => setShowMore(!showMore)}
> */}
<>
<ManageText>Manage</ManageText>
{showMore ? <ChevronUp size="25" /> : <ChevronDown size="25" />}
</>
{/* </ButtonEmpty> */}
</RowFixed>
</FixedHeightRow>
</ButtonEmpty>
{showMore && (
<AutoColumn gap="14px">
<RowBetween>
<DMSansText.body fontSize={18}>Your pool tokens:</DMSansText.body>
<DMSansText.body fontSize={18}>
{userPoolBalance ? userPoolBalance.toSignificant(4) : '-'}
</DMSansText.body>
</RowBetween>
<RowBetween>
<RowFixed>
<DMSansText.body fontSize={18}>Pooled {currency0.symbol}:</DMSansText.body>
</RowFixed>
{token0Deposited ? (
<RowFixed>
<DMSansText.body fontSize={18} marginLeft={'6px'}>
{token0Deposited?.toSignificant(6)}
</DMSansText.body>
<CurrencyLogo size={25} style={{ marginLeft: '8px' }} currency={currency0} />
</RowFixed>
) : (
'-'
)}
</RowBetween>
<RowBetween>
<RowFixed>
<DMSansText.body fontSize={18}>Pooled {currency1.symbol}:</DMSansText.body>
</RowFixed>
{token1Deposited ? (
<RowFixed>
<DMSansText.body fontSize={18} marginLeft={'6px'}>
{token1Deposited?.toSignificant(6)}
</DMSansText.body>
<CurrencyLogo size={25} style={{ marginLeft: '8px' }} currency={currency1} />
</RowFixed>
) : (
'-'
)}
</RowBetween>
<RowBetween>
<DMSansText.body fontSize={18}>Your pool share:</DMSansText.body>
<DMSansText.body fontSize={18}>
{poolTokenPercentage ? poolTokenPercentage.toSignificant(6) + '%' : '-'}
</DMSansText.body>
</RowBetween>
<RowBetween marginTop="15px">
<AddRemoveButton as={Link} to={`/add/${currencyId(currency0)}/${currencyId(currency1)}`} width="48%">
Add Liquidity
</AddRemoveButton>
<AddRemoveButton as={Link} width="48%" to={`/remove/${currencyId(currency0)}/${currencyId(currency1)}`}>
Remove Liquidity
</AddRemoveButton>
</RowBetween>
</AutoColumn>
)}
</AutoColumn>
</JediPositionCard>
)
} |
callirhoe - high quality calendar rendering
(c) 2012-2015 George Tzoumas
https://geotz.github.io/callirhoe/
QUICK INSTALLATION GUIDE
CONTENTS
1) FROM COMPRESSED ARCHIVE
2) FROM GITHUB
3) INSTALLING INTO BINARY PATH
4) INSTALLATION FOR ARCH LINUX
(rough installation guide for novice users...)
1) FROM COMPRESSED ARCHIVE
Download the latest version from the project's page.
You end up with a file named callirhoe-vX.Y.Z-gID.tar.gz or .zip where
X.Y.Z the version number (for example 0.4.2) and ID the commit ID
(depending on how you obtained the archive).
Extract the contents of the archive
$ tar zxf callirhoe-vX.Y.Z-gID.tar.gz
Change into program's directory
$ cd geotz-callirhoe-ID
Now you can launch the program, e.g.
$ ./callirhoe.py foo.pdf
See section 3 for how to install callirhoe so that it lies in your
executable path.
2) FROM GITHUB
Checkout the latest version from github. Most probably you want only the
master branch (unless you also want to download the website with over
100MB of pregenerated calendars!):
$ git clone -b master --single-branch https://github.com/geotz/callirhoe.git
Change into directory
$ cd callirhoe
After a few days/weeks/months... you may update to the latest version:
$ git pull
You can launch the program as usual:
$ ./callirhoe.py foo.pdf
3) INSTALLING INTO BINARY PATH
You can add a link to your path, $HOME/bin or /usr/local/bin:
$ ln -s `pwd`/callirhoe.py $HOME/bin/callirhoe
You can do the same with calmagick.py. You may also install it
system-wide, for example in /opt. In this case, keep in mind, that
~/.callirhoe/ is also searched for additional definitions, styles etc.
If you do not plan to mess with the source, you may create a binary
python package. This is not exactly a binary, it is a zip archive
containing compiled python bytecode, which is quite compact. To do so,
simply run:
$ make
This will create two executables, 'callirhoe' and 'calmagick'. Now you
can install them into your binary path as follows:
$ make install
this will typically install to /usr/local/bin (and the holiday files into
/usr/local/share/callirhoe/holidays). You can specify another prefix:
$ make install DESTDIR=/my/other/dir
Now you can remove the source dir, as it is no longer needed.
4) INSTALLATION FOR ARCH LINUX
There is a PKGBUILD file you can use to install. Normally you get just
the PKGBUILD from the webpage from AUR
(https://aur.archlinux.org/packages/callirhoe/). It is also included in
the source distribution, but this is a bit redundant (see below).
Place the PKGBUILD into a directory and run:
$ makepkg -si
( -s will automatically install missing depedencies; also note that this
will redownload the source from the svn )
Arch will do the rest for you.
In the unlikely event that you don't have "makepkg" already installed
you can find information about it's installation here:
https://wiki.archlinux.org/index.php/Arch_User_Repository |
<template >
<h2 style="margin-top: 30px;margin-left: 40px;">การบันทึกเข้า-ออกงาน</h2>
<v-container>
<v-row>
<v-col sm="12" md="4">
<v-card style="margin-top: 100px;padding: 18px; border-radius: 16px;" elevation="3">
<div v-for="item in empolyinformation" :key="item.name">
<h3 style="padding: 10px;font-weight: bold;">
<v-icon size="large">mdi-account-circle-outline</v-icon>{{item.name}}</h3>
<h3 style="padding:10px;font-weight:bold;">
<v-icon size="large">mdi-account</v-icon>{{ item.position }}</h3>
<h3 style="padding:10px;">
<v-icon size="large">mdi-calendar</v-icon>{{ formattedDate }}</h3>
</div>
<div>
<v-row justify="center">
<v-col cols="auto" style="display: flex; padding-top:70px">
<v-dialog activator="parent" width="auto">
<template v-slot:activator="{ props }">
<v-btn color="success" size="x-large" v-bind="props">บันทึกเข้า</v-btn>
</template>
<template v-slot:default="{ isActive }">
<v-card>
<v-toolbar color="success" title="บันทึกการออกงาน"></v-toolbar>
<v-card-text>
<div class="text-h5 pa-12">
ต้องการบันทึกเวลาเข้างานของคุณใช่หรือไม่ ?
</div>
</v-card-text>
<v-card-actions class="justify-end">
<v-btn style="font-size:large;font-weight: bold;" color="success" variant="text" @click="isActive.value = false" >
ตกลง
</v-btn>
<v-btn style="font-size: large;font-weight: bold;" color="error" variant="text" @click="isActive.value = false" >
ยกเลิก
</v-btn>
</v-card-actions>
</v-card>
</template>
</v-dialog>
<v-dialog activator="parent" width="auto">
<template v-slot:activator="{ props }">
<v-btn color="error" size="x-large" v-bind="props" style="margin-left: 50px">บันทึกออก</v-btn>
</template>
<template v-slot:default="{ isActive }">
<v-card>
<v-toolbar color="error" title="บันทึกการออกงาน"></v-toolbar>
<v-card-text>
<div class="text-h5 pa-12">
ต้องการบันทึกเวลาออกงานของคุณใช่หรือไม่ ?
</div>
</v-card-text>
<v-card-actions class="justify-end">
<v-btn style="font-size:large;font-weight: bold;" color="success" variant="text" @click="isActive.value = false" >
ตกลง
</v-btn>
<v-btn style="font-size: large;font-weight: bold;" color="error" variant="text" @click="isActive.value = false" >
ยกเลิก
</v-btn>
</v-card-actions>
</v-card>
</template>
</v-dialog>
</v-col>
</v-row>
</div>
</v-card>
</v-col>
<v-col sm="12" md="8">
<div >
<h3 class="text-high-emphasis font-weight-medium">ประวัติการเข้า-ออกงาน</h3>
<br/>
<v-card elevation="3">
<v-table>
<thead style="background-color: #e0e0e0">
<tr>
<th class="text-center ">วันที่</th>
<th class="text-center">เวลาเข้า</th>
<th class="text-center">เวลาออก</th>
</tr>
</thead>
<tbody >
<tr v-for="item in historys" :key="item.date">
<td class="text-center">{{ item.date }}</td>
<td class="text-center">{{ item.timein }}</td>
<td class="text-center">{{ item.timeout }}</td>
</tr>
</tbody>
</v-table>
</v-card>
</div>
</v-col>
</v-row>
</v-container>
</template>
<script>
import moment from 'moment';
export default {
name: "checkin",
data() {
return {
date: new Date(),
historys: [
{
date: "22 มกราคม 2566",
timein: "08.55 น.",
timeout:"18.00 น."
},
{
date: "23 มกราคม 2566",
timein: "08.55 น.",
timeout:"18.00 น."
},
{
date: "24 มกราคม 2566",
timein: "08.55 น.",
timeout:"18.00 น."
},
{
date: "25 มกราคม 2566",
timein: "08.55 น.",
timeout:"18.00 น."
},
{
date: "26 มกราคม 2566",
timein: "08.55 น.",
timeout:"18.00 น."
},
{
date: "27 มกราคม 2566",
timein: "08.55 น.",
timeout:"18.00 น."
},
{
date: "25 มกราคม 2566",
timein: "08.55 น.",
timeout:"18.00 น."
},
{
date: "26 มกราคม 2566",
timein: "08.55 น.",
timeout:"18.00 น."
},
{
date: "27 มกราคม 2566",
timein: "08.55 น.",
timeout:"18.00 น."
},
],
empolyinformation: [
{
name: 'สุชาดา ศิริโกศล',
position: 'Humance Resource',
}
],
};
},
computed: {
formattedDate() {
return moment(this.date).format('dddd D MMMM YYYY, h:mm a');
},
},
};
</script> |
/*********************************************************
* UNION TYPE IN TYPESCRIPT
* All the possible type which a variable can store.
*/
let user: { name: string, age: number } | null = null;
function getUser(): { name: string, age: number | null } {
const uname = 'Shani';
const uage = 34;
user = { name: uname, age: uage };
return user ?? null;
}
console.log(getUser());
function printStatus(message: string, statusCode: string | number) {
console.log(`${message}. Status Code: ${statusCode}`);
}
printStatus('Request was successful', 200);
printStatus('Bad Request', '400'); |
import { useState } from "react";
import { FormItem, FormContainer } from "@/components/ui/Form";
import Button from "@/components/ui/Button";
import Alert from "@/components/ui/Alert";
import PasswordInput from "@/components/shared/PasswordInput";
import ActionLink from "@/components/shared/ActionLink";
import { apiResetPassword } from "@/services/AuthService";
import useTimeOutMessage from "@/utils/hooks/useTimeOutMessage";
import { useLocation, useNavigate } from "react-router-dom";
import { Field, Form, Formik } from "formik";
import * as Yup from "yup";
import type { CommonProps } from "@/@types/common";
import type { AxiosError } from "axios";
import { useTranslation } from "react-i18next";
import { Input } from "@/components/ui";
interface ResetPasswordFormProps extends CommonProps {
disableSubmit?: boolean;
signInUrl?: string;
}
type ResetPasswordFormSchema = {
email: string;
code: string;
password: string;
confirm_password: string;
};
const validationSchema = Yup.object().shape({
email: Yup.string().required("validations.required"),
code: Yup.string().required("validations.required").length(6),
password: Yup.string().required("validations.required"),
confirm_password: Yup.string()
.required("validations.required")
.oneOf([Yup.ref("password")], "validations.passwords_mismatch"),
});
const ResetPasswordForm = (props: ResetPasswordFormProps) => {
const { t } = useTranslation();
const { disableSubmit = false, className, signInUrl = "/sign-in" } = props;
const [resetComplete, setResetComplete] = useState(false);
const [message, setMessage] = useTimeOutMessage();
const navigate = useNavigate();
const location = useLocation();
const onSubmit = async (
values: ResetPasswordFormSchema,
setSubmitting: (isSubmitting: boolean) => void
) => {
const { email, code, password, confirm_password } = values;
setSubmitting(true);
try {
const resp = await apiResetPassword({ email, code, password, confirm_password });
if (resp.data) {
setSubmitting(false);
setResetComplete(true);
}
} catch (errors) {
setMessage(
(errors as AxiosError<{ message: string }>)?.response?.data?.message ||
(errors as Error).toString()
);
setSubmitting(false);
}
};
const onContinue = () => {
navigate("/sign-in");
};
return (
<div className={className}>
<div className="mb-6">
{resetComplete ? (
<>
<h3 className="mb-1">{t("reset_password_page.success.title")}</h3>
<p>{t("reset_password_page.success.description")}</p>
</>
) : (
<>
<h3 className="mb-1">{t("reset_password_page.title")}</h3>
<p>{t("reset_password_page.description")}</p>
</>
)}
</div>
{message && (
<Alert showIcon className="mb-4" type="danger">
{message}
</Alert>
)}
<Formik
initialValues={{
email: (location.state?.email as string) ?? "",
code: "",
password: "",
confirm_password: "",
}}
validationSchema={validationSchema}
onSubmit={(values, { setSubmitting }) => {
if (!disableSubmit) {
onSubmit(values, setSubmitting);
} else {
setSubmitting(false);
}
}}
>
{({ touched, errors, isSubmitting }) => (
<Form>
<FormContainer>
{!resetComplete ? (
<>
<FormItem
label={t("email_address")}
invalid={errors.email && touched.email}
errorMessage={errors.email}
>
<Field
type="email"
autoComplete="off"
name="email"
placeholder={t("email_address")}
component={Input}
/>
</FormItem>
<FormItem
label={t("email_code")}
invalid={errors.code && touched.code}
errorMessage={errors.code}
>
<Field
autoComplete="off"
name="code"
placeholder={t("email_code")}
component={Input}
/>
</FormItem>
<FormItem
label={t("password")}
invalid={errors.password && touched.password}
errorMessage={errors.password}
>
<Field
autoComplete="off"
name="password"
placeholder={t("password")}
component={PasswordInput}
/>
</FormItem>
<FormItem
label={t("confirm_password")}
invalid={errors.confirm_password && touched.confirm_password}
errorMessage={errors.confirm_password}
>
<Field
autoComplete="off"
name="confirm_password"
placeholder={t("confirm_password")}
component={PasswordInput}
/>
</FormItem>
<Button block loading={isSubmitting} variant="solid" type="submit">
{isSubmitting ? t("submitting") : t("submit")}
</Button>
</>
) : (
<Button block variant="solid" type="button" onClick={onContinue}>
{t("continue")}
</Button>
)}
<div className="mt-4 text-center">
<span>{t("back_to")} </span>
<ActionLink to={signInUrl}>{t("login")}</ActionLink>
</div>
</FormContainer>
</Form>
)}
</Formik>
</div>
);
};
export default ResetPasswordForm; |
package logic.card;
import logic.game.CardColor;
import logic.game.CardSymbol;
import logic.game.GameLogic;
public class DrawFourCard extends EffectCard {
// Constructors
public DrawFourCard() {
super(null, CardSymbol.DRAW_FOUR);
}
// Methods
@Override
public String toString() {
if (this.getColor() == null) {
return "DRAW FOUR";
}
return String.format("DRAW FOUR (%s color selected)", this.getColor());
}
@Override
public boolean canPlay() {
return true;
}
@Override
public String performEffect() {
var game = GameLogic.getInstance();
var playerHand = game.getCurrentPlayerHand();
var newColor = playerHand.stream()
.filter(card -> !card.equals(this))
.findFirst()
.map(card -> card.getColor())
.orElse(CardColor.RED);
this.setColor(newColor);
var message = String.format("Set color to %s\n", newColor);
game.incrementDrawAmount(4);
int currentPlayer;
do {
game.goToNextPlayer();
currentPlayer = game.getCurrentPlayer();
} while (game.getPlayerHand(currentPlayer).isEmpty());
var drawCard = game.getCurrentPlayerHand().stream()
.filter(card -> card.getSymbol().equals(CardSymbol.DRAW_FOUR))
.findFirst()
.orElse(null);
if (drawCard != null) {
message += String.format(
"Player %d played %s. %d cards remaining.",
currentPlayer, drawCard,
game.getCurrentPlayerHand().size() - 1);
return message + "\n" + drawCard.play();
} else {
game.draw(game.getDrawAmount());
message += String.format("Player %d drew %d cards. %d cards remaining.",
currentPlayer, game.getDrawAmount(), game.getCurrentPlayerHand().size());
game.setDrawAmount(0);
return message;
}
}
} |
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import "../PledgeForm/PledgeForm.css";
function ProjectForm(props) {
const { project } = props;
//State
const [projectDetails, setprojectDetails] = useState({
title: "",
description:"",
goal: "",
image: "",
date_created: null,
is_open: true,
});
//Hooks
const navigate = useNavigate();
//Actions
const handleChange = (event) => {
const {id, value} = event.target;
// we are taking the id and value out of the input.
setprojectDetails((projectDetails) =>({
...projectDetails, ///... doesn't give nested objects
[id]: value,
}));
};
const authToken = window.localStorage.getItem("token");
const postData = async () => { //we are using async as we are doing await first
const response = await fetch(
`${import.meta.env.VITE_API_URL}projects/`,
{
method: "post",
headers: {
"Content-Type": "application/json",
"Authorization": `Token ${authToken}`,
},
body: JSON.stringify(projectDetails),
}
);
return response.json();
};
const handleSubmit = async (event) => {
event.preventDefault();
if (window.localStorage.getItem("token")) {
console.log("token exists");
await postData();
navigate("/");
}
};
return (
<>
<h2>Get help from the paw community <br/> by submitting a project below!</h2>
<form onSubmit={handleSubmit}>
<div className="form-item">
<label htmlFor="title">Title:</label>
<input
type="text"
id="title"
onChange={handleChange}
placeholder="Enter title"
/>
</div>
<div className="form-item" id="description">
<label htmlFor="description">Description:</label>
<textarea
type="text"
rows="5"
cols="80"
id="description"
onChange={handleChange}
placeholder="Add a description here"
/>
</div>
<div className="form-item">
<label htmlFor="goal">Enter the $ goal:</label>
<input
type="text"
id="goal"
onChange={handleChange}
placeholder="Add your goal here"
/>
</div>
<div className="form-item">
<label htmlFor="image">Link an image for your project:</label>
<input
type="text"
id="image"
onChange={handleChange}
placeholder="Add your image URL here"
/>
</div>
<div className="form-item" id="activate-project">
<label htmlFor="is_open">Activate Project:</label>
<input type="checkbox" id="is_open" onChange={handleChange} />
</div>
<div className="form-item">
<label htmlFor="date_created">Date Created:</label>
<input type="date" id="date_created" onChange={handleChange} />
</div>
<button type="submit" className="blue-btn" id="project-btn">
Submit your Project
</button>
</form>
</>
);
};
export default ProjectForm; |
from project.formula_teams.formula_team import FormulaTeam
from project.formula_teams.mercedes_team import MercedesTeam
from project.formula_teams.red_bull_team import RedBullTeam
class F1SeasonApp:
valid_team_names = ["Mercedes", "Red Bull"]
def __init__(self):
self.red_bull_team: RedBullTeam or None = None
self.mercedes_team: MercedesTeam or None = None
def register_team_for_season(self, team_name: str, budget: int):
if team_name not in self.valid_team_names:
raise ValueError("Invalid team name!")
if team_name == self.valid_team_names[0]:
self.mercedes_team = MercedesTeam(budget)
else:
self.red_bull_team = RedBullTeam(budget)
return f"{team_name} has joined the new F1 season."
def new_race_results(self, race_name: str, red_bull_pos: int, mercedes_pos: int):
if not self.red_bull_team or not self.mercedes_team:
raise Exception("Not all teams have registered for the season.")
return self.get_race_results(race_name, red_bull_pos, mercedes_pos)
def get_race_results(self, race_name: str, red_bull_pos: int, mercedes_pos: int):
ahead_team = "Red Bul" if red_bull_pos < mercedes_pos else "Mercedes"
red_bul_revenue = self.red_bull_team.calculate_revenue_after_race(red_bull_pos)
mercedes = self.mercedes_team.calculate_revenue_after_race(mercedes_pos)
return f"Red Bull: {red_bul_revenue}. Mercedes: {mercedes}." \
f" {ahead_team} is ahead at the {race_name} race." |
import argparse
import numpy as np
import os
import time
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score, auc
from tqdm import tqdm
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from mvtec import *
from fag import *
from networks import *
from tools import *
torch.cuda.empty_cache()
class FractalAD():
def __init__(self):
self.findobj_cfg = {'bottle':0,'cable':0,'capsule':1,'carpet':0,'grid':0,
'hazelnut':0,'leather':0,'metal_nut':0,'pill':1,'screw':1,'tile':0,
'toothbrush':1,'transistor':0,'wood':0,'zipper':1}
self.kd_cfg = {'bottle':1,'cable':1,'capsule':1,'carpet':0,'grid':0,
'hazelnut':1,'leather':0,'metal_nut':1,'pill':1,'screw':1,'tile':0,
'toothbrush':1,'transistor':1,'wood':0,'zipper':1}
self.load_model()
def load_dataset(self, load_size, batch_size, num_workers=0, drop_last=False, is_train=True):
if is_train:
transform_train = FAG(load_size=load_size, is_findobj=self.findobj_cfg[category])
else:
transform_train = None
dataset = MVTec(dataset_path, category, is_train, load_size, transform_train)
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=is_train,
num_workers=num_workers, drop_last=drop_last, pin_memory=True)
phase = 'train' if is_train else 'test'
self.dataset_length = len(dataset)
print('Dataset size : {} set - {}'.format(phase, self.dataset_length))
return dataloader
def load_model(self):
self.teacher = BackBone(backbone=backbone, pretrained=True).to(device)
self.student = BackBone(backbone=backbone, pretrained=False).to(device)
self.sfnet = SFNet(backbone=backbone).to(device)
self.csam = CSAM()
if self.kd_cfg[category]:
self.optimizer = torch.optim.AdamW([{'params':self.student.parameters()},
{'params':self.sfnet.parameters()}], lr=lr, weight_decay=0.001)
else:
self.optimizer = torch.optim.AdamW(self.sfnet.parameters(), lr=lr)
self.db_loss = DiceBCELoss()
self.kd_loss = CosSimLoss()
def train_step(self, img, aug, msk):
self.optimizer.zero_grad()
if self.kd_cfg[category]:
img_t = self.teacher(img)
aug_t = self.teacher(aug)
img_s = self.student(img)
aug_s = self.student(aug)
prd = self.sfnet(self.csam(aug_t, aug_s))
loss_kd = self.kd_loss(img_t, img_s)
loss_db = self.db_loss(prd, msk)
loss = loss_kd + loss_db
loss.backward()
self.optimizer.step()
return torch.sigmoid(prd), [loss_kd, loss_db, loss]
else:
prd = self.sfnet(self.teacher(aug))
loss = self.db_loss(prd, msk)
loss.backward()
self.optimizer.step()
return torch.sigmoid(prd), loss
def train(self):
print('Training category: ', category)
print('Training num_epoch: ', num_epoch)
train_loader = self.load_dataset(load_size = load_size, batch_size=batch_size,
num_workers=8, drop_last=True, is_train=True)
self.teacher.eval()
self.student.train()
self.sfnet.train()
start_epoch = 0
global_step = 0
# load weights
path_checkpoint = os.path.join(weight_save_path, "model.pth")
if os.path.exists(path_checkpoint):
checkpoint = torch.load(path_checkpoint)
if self.kd_cfg[category]:
self.student.load_state_dict(checkpoint['student'])
self.sfnet.load_state_dict(checkpoint['sfnet'])
self.optimizer.load_state_dict(checkpoint['optimizer'])
start_epoch = checkpoint['epoch'] + 1
global_step = checkpoint['global_step']
print('-'*50)
print("Model restored")
print('-'*50)
for epoch in range(start_epoch, num_epoch):
start_time = time.time()
for idx, (img, aug, msk, _) in enumerate(train_loader):
global_step += 1
img = img.to(device)
aug = aug.to(device)
msk = msk.to(device)
prd, loss = self.train_step(img, aug, msk)
# tensorboard
if self.kd_cfg[category]:
loss_kd, loss_db, loss = loss
# save images
img = np.uint8(255*img[0,:,:,:].permute(1,2,0).to('cpu').detach().numpy())
aug = np.uint8(255*aug[0,:,:,:].permute(1,2,0).to('cpu').detach().numpy())
msk = np.uint8(255*msk[0,:,:,:].permute(1,2,0).to('cpu').detach().numpy())
prd = np.uint8(255*prd[0,:,:,:].permute(1,2,0).to('cpu').detach().numpy())
msks = cv2.cvtColor(np.concatenate([msk, prd], axis=1), cv2.COLOR_GRAY2RGB)
imgs = cv2.cvtColor(np.concatenate([img, aug, msks], axis=1), cv2.COLOR_BGR2RGB)
cv2.imwrite(os.path.join(train_path, 'epoch_{:04d}.jpg'.format(epoch)), imgs)
# save weights
checkpoint = {
"sfnet": self.sfnet.state_dict(),
'optimizer':self.optimizer.state_dict(),
"epoch": epoch,
"global_step": global_step
}
if self.kd_cfg[category]:
checkpoint.update({"student": self.student.state_dict()})
torch.save(checkpoint, os.path.join(weight_save_path, 'model.pth'))
if self.kd_cfg[category]:
print('Epoch: {}/{} | loss_kd: {:.4f} | loss_db: {:.4f} | loss: {:.4f} | Time consumed: {:.4f}'.\
format(epoch, num_epoch, float(loss_kd.data), float(loss_db.data), float(loss.data), time.time() - start_time))
else:
print('Epoch: {}/{} | loss: {:.4f} | Time consumed: {:.4f}'.\
format(epoch, num_epoch, float(loss.data), time.time() - start_time))
print('Train end.')
def test(self):
print('Testing category: ', category)
try:
if self.kd_cfg[category]:
self.student.load_state_dict(torch.load(weight_save_path+'/model.pth')['student'])
self.sfnet.load_state_dict(torch.load(weight_save_path+'/model.pth')['sfnet'])
except:
raise Exception('Check saved model path.')
self.teacher.eval()
self.student.eval()
self.sfnet.eval()
test_loader = self.load_dataset(load_size = load_size, batch_size=1, is_train=False)
# prepare for calculating auc-pro
gt_masks = []
pd_masks = []
gt_list_img = []
pd_list_img = []
gt_list_pix = []
pd_list_pix = []
start_time = time.time()
for test_img, test_msk, label, img_name in tqdm(test_loader):
# test image shape = [1,3,H,W]
test_img = test_img.to(device)
with torch.set_grad_enabled(False):
if self.kd_cfg[category]:
pred_msk = torch.sigmoid(self.sfnet(self.csam(self.teacher(test_img), self.student(test_img)))).to('cpu')
else:
pred_msk = torch.sigmoid(self.sfnet(self.teacher(test_img))).to('cpu')
gt_masks.append(test_msk.squeeze().numpy())
pd_masks.append(pred_msk.squeeze().numpy())
# test image label 0 is normal, 1 is anomaly
gt_score = 0. if MVTec_DEFECT_TYPE[label] == 'good' else 1.
pd_score = torch.mean(pred_msk).item()
gt_list_img.append(gt_score)
pd_list_img.append(pd_score)
gt_list_pix.extend(test_msk.numpy().ravel())
pd_list_pix.extend(pred_msk.numpy().ravel())
# save images
test_img = np.uint8(255 * test_img[0, :, :, :].permute(1, 2, 0).to('cpu').numpy())
test_msk = np.uint8(255 * test_msk[0, :, :, :].permute(1, 2, 0).numpy())
pred_msk = np.uint8(255 * pred_msk[0, :, :, :].permute(1, 2, 0).numpy())
msks = cv2.cvtColor(np.concatenate([test_msk, pred_msk], axis=1), cv2.COLOR_GRAY2RGB)
imgs = cv2.cvtColor(np.concatenate([test_img, msks], axis=1), cv2.COLOR_BGR2RGB)
cv2.imwrite(os.path.join(sample_path, f'{img_name[0]}.jpg'), imgs)
print('Total test time consumed : {}'.format(time.time() - start_time))
# calculate auc-roc
p_auc = round(roc_auc_score(gt_list_pix, pd_list_pix), 4)
i_auc = round(roc_auc_score(gt_list_img, pd_list_img), 4)
print("Total pixel-level auc-roc score:", p_auc)
print("Total image-level auc-roc score:", i_auc)
with open(os.path.join(project_path, backbone, 'results.txt'), 'a', encoding='utf-8') as f:
f.write(category + ' pixel-auc:' + str(p_auc) + ' image-auc:' + str(i_auc) + '\n')
print('Test end.')
def get_args():
parser = argparse.ArgumentParser(description='FractalAD')
parser.add_argument('--phase', default='train')
parser.add_argument('--dataset_path', default=r'./MVTec_AD/')
parser.add_argument('--backbone', default='resnet18')
parser.add_argument('--category', default='capsule')
parser.add_argument('--num_epoch', default=100)
parser.add_argument('--lr', default=0.001)
parser.add_argument('--batch_size', default=32)
parser.add_argument('--load_size', default=256)
parser.add_argument('--gpu', default=0)
parser.add_argument('--project_path', default='./results')
args = parser.parse_args()
return args
if __name__ == '__main__':
seed_everything(111111)
args = get_args()
torch.cuda.set_device(int(args.gpu))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# device = 'cpu'
print ('Available devices ', torch.cuda.device_count())
print ('Current cuda device ', torch.cuda.current_device())
# print(torch.cuda.get_device_name(device))
phase = args.phase
dataset_path = args.dataset_path
backbone = args.backbone
category = args.category
num_epoch = int(args.num_epoch)
lr = args.lr
batch_size = args.batch_size
load_size = args.load_size
project_path = args.project_path
train_path = os.path.join(project_path, backbone, 'train', category + '_bs'+ str(batch_size))
os.makedirs(train_path, exist_ok=True)
sample_path = os.path.join(project_path, backbone, 'sample', category + '_bs'+ str(batch_size))
os.makedirs(sample_path, exist_ok=True)
weight_save_path = os.path.join(project_path, backbone, 'checkpoint', category + '_bs'+ str(batch_size))
os.makedirs(weight_save_path, exist_ok=True)
fractalad = FractalAD()
if phase == 'train':
fractalad.train()
# fractalad.test()
elif phase == 'test':
fractalad.test()
else:
print('Phase argument must be train or test.') |
import { inject, injectable } from "tsyringe";
import { hash } from 'bcryptjs';
import User from "../../infra/typeorm/entities/User";
import IUsersRepository from "../../repositories/IUsersRepository";
import { HttpException, HttpStatusCode } from "../../../../shared/exceptions/HttpException";
import { IRequest } from "../../dtos/users/IRequestDTO";
@injectable()
export class CreateUserService {
constructor(
@inject('UsersRepository')
private usersRepository: IUsersRepository,
) { }
async execute({ name, email, password }: IRequest): Promise<User> {
const userExists = await this.usersRepository.findByEmail(email);
if (userExists) {
throw new HttpException(HttpStatusCode.CONFLICT, 'Email address already used.');
}
const hashedPassword = await hash(password, 8);
const user = await this.usersRepository.create({
name,
email,
password: hashedPassword,
});
return user;
}
} |
red(s) = { return(concat("\e[31m", concat(s, "\e[0m"))); }
green(s) = { return(concat("\e[32m", concat(s, "\e[0m"))); }
blue(s) = { return(concat("\e[34m", concat(s, "\e[0m"))); }
print("Tonelli x^2 = a mod (p): Usage Tonelli(a,p)");
print("Bestimmung einer Wurzel");
Tonelli(a,p) = {
if (p <=2,
printf(red("p has to be bigger than 2\n"));
return;
);
my(case, root, root2 , h, low_p, i, res, euler_crit, euler_crit_h);
\\ check euler criterium first!
euler_crit = (a^((p-1)/2)) % p;
if (euler_crit == p-1,
printf(red("euler criterium not fullfilled! (a^((p-1)/2)) %% p = -1;\n"));
printf(red("a = %d doesnt have a root in Z%d*\n"), a, p);
return;
);
if (euler_crit == 1,
printf(green("euler criterium fullfilled! (a^((p-1)/2)) %% p;\n"));
printf(green("(%d^((%d-1)/2)) %% %d = %d\n"),a,p,p, euler_crit);
);
case = p % 4;
\\ check if the case is
\\p = 3 %4 or
\\p = 1 %4
root = 1;
printf("Case p %% 4 = %d\n",case);
if (case == 3,
\\ true
printf(green("a ^ ((p +1)/4)\n"));
root = a ^((p+1)/4) %p;
root2 = lift(Mod(-root,p));
printf(green("%d ^ ((%d +1)/4) \= %d is 1. root of %d in Z%d*\n"), a,p,root, a,p);
printf(green("%d ^ ((%d +1)/4) \= %d is 2. root (=> -%d) of %d in Z%d*\n"), a,p,root2,root, a,p);
\\false => means it has to be the case 1
,
\\ case == 1
\\ find a suiting h (which is not a square remainder)
h = 2;
while (true,
euler_crit_h = (h^((p-1)/2)) % p;
if (euler_crit_h == p -1,
printf("found h = %d\n", h);
printf("%d ^((%d-1/2)) \= -1\n", h,p);
break;
);
h++;
);
exp_a = (p-1) / 2;
exp_h = p-1;
printf(red("exp_a = %d\n"), exp_a);
printf(blue("exp_h = %d\n"), exp_h);
i = 1;
while(exp_a % 2 == 0,
printf("%d. bisect\n", i);
i++;
exp_a /= 2;
exp_h /= 2;
printf(red("exp_a = %d\n"), exp_a);
printf(blue("exp_h = %d\n"), exp_h);
\\ check if there the product is -1 if yes we have to add to the exponent of h
res = (a^(exp_a) * h^exp_h)%p;
printf("Result of a^(exp_a) * h^exp_h = %d\n", res);
if (res == p-1,
exp_h += (p-1)/2; \\ corresponds to a multiplication by -1
printf(green("%d is equivalent to -1 %% %d-> need adjustment of exponent of h\n"), res,p);
printf(green("Adjusted exp_h = %d \t(h_old += (p-1)/2)\n"), exp_h);
);
);
printf(green("Found u = %d (exponent of a) and g = %d (exponent of h)\n"), exp_a, exp_h);
root = (a^((exp_a +1)/2) * h^(exp_h /2)) %p;
root2 = lift(Mod(-root,p));
printf(green("%d ^((%d +1) / 2) * %d^(%d / 2) %% p\n"), a,exp_a, h, exp_h,p);
printf(green("Found 1. root = %d\n"), root);
printf(green("Found 2. root (=> -%d) \= %d\n"),root, root2);
);
printf("Check 1. root: %d^2 %% %d = %d\n", root, p, (root^2) % p);
printf("Check 2. root: %d^2 %% %d = %d\n", root2, p, (root^2) % p);
} |
#' Try to intelligently reduce a large palette down to a reasonable smaller
#' set of colors
#'
#' Given a palette and a desired number of colors to use, this function will
#' compute CIEDE2000 and attempt to reduce the input set to a disctinct
#' smaller set of colors based on color distances.
#'
#' @param pal input palette to reduct
#' @param n number of desired colors
#' @return vector of \code{n} colors from \code{pal}
#' @note internal CIEDE2000 color distance implementation by Gaurav Sharma & Maynard P Baalthazar
#' @export
trim_palette <- function(pal, n=5) {
tmp <- as(colorspace::hex2RGB(pal, gamma=TRUE), "LAB")
ncols <- nrow(tmp@coords)
mm <- matrix(nrow=ncols, ncol=ncols)
outer(1:ncols, 1:ncols, FUN = function(i, j) {
deltaE2000(tmp[i], tmp[j], 1, 2, 1)
}) -> mm
mmd <- as.dist(mm)
hc <- hclust(mmd, method="ward.D2")
ct <- cutree(hc, n)
gsub(" ", "0", pal[!duplicated(ct)])
} |
import React, {useState, useEffect } from 'react';
import styled from 'styled-components';
import { Link, useNavigate } from 'react-router-dom';
import Logo from '../assets/logo.png';
import {ToastContainer, toast} from 'react-toastify';
import axios from 'axios';
import "react-toastify/dist/ReactToastify.css"
import { registerRoute } from '../utils/APIRoutes';
function Register() {
const navigate = useNavigate();
const [values, setValues] = useState({
username: "",
email: "",
password: "",
confirmPassword: ""
});
const toastOptions = {
position: "bottom-right",
autoClose: 8000,
pauseOnHover: true,
draggable: true,
theme: "dark"
}
useEffect(() => {
if(localStorage.getItem("chat-app-user")){
navigate('/')
}
},[])
const handleSubmit = async (event) => {
event.preventDefault();
if(handleValidation()){
console.log("inside validaiton", registerRoute)
const {password, username, email } = values;
const {data} = await axios.post(registerRoute, {
username,
email,
password,
});
if(data.status === false){
toast.error(data.msg, toastOptions);
}
if(data.status == true){
localStorage.setItem('chat-app-user', JSON.stringify(data.user))
navigate("/");
}
}
};
const handleValidation =()=>{
const {password, confirmPassword, username, email } = values
if(password!==confirmPassword){
toast.error("password and confirm password should be same!", toastOptions);
return false;
} else if(username.length < 3){
toast.error("Username should be greater than 3 characters!", toastOptions);
return false;
} else if(password.length <= 8){
toast.error("Passowrd should be greater or equal to 8 characters!", toastOptions);
return false;
} else if(email===""){
toast.error("Email is required!", toastOptions);
return false;
}
return true;
};
const handleChange = (event) => {
setValues({...values, [event.target.name]:event.target.value})
console.log({[event.target.name]:event.target.value});
}
return (
<>
<FormContainer>
<form onSubmit={(event) => handleSubmit(event)}>
<div className='brand'>
<img src={Logo} alt="logo" />
<h1>snappy</h1>
</div>
<input type="text" placeholder='Username' name="username" onChange={e=>handleChange(e)} />
<input type="email" placeholder='Email' name="email" onChange={e=>handleChange(e)} />
<input type="password" placeholder='Password' name="password" onChange={e=>handleChange(e)} />
<input type="password" placeholder='Confirm Password' name="confirmPassword" onChange={e=>handleChange(e)} />
<button type="submit">Create User</button>
<span>Already have an account? <Link to="/login">Login</Link></span>
</form>
</FormContainer>
<ToastContainer />
</>
)
}
const FormContainer = styled.div`
height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
justify-content: center;
gap: 1rem;
align-items: center;
background-color: #131324;
.brand {
display: flex;
align-items: center;
gap: 1rem;
justify-content: center;
img{
height: 5rem;
}
h1{
color: white;
text-transform: uppercase;
}
}
form {
display: flex;
flex-direction: column;
gap: 2rem;
background-color: #00000076;
border-radius: 2rem;
padding: 3rem 5rem;
input{
background-color: transparent;
padding: 1rem;
border: 0.1rem solid #4e0eff;
border-radius: 0.4rem;
color: white;
width: 100%
font-size: 1rem;
&:focus{
border: 0.1rem solid #997af0;
outline: none;
}
}
button{
background-color: #997af0;
color: white;
padding: 1rem 2rem;
border-radius: 0.4rem;
cursor: pointer;
font-weight: bold;
border: none;
font-size: 1rem;
text-transform: uppercase;
transition: 0.5s ease-in-out;
&:hover {
background-color: #4e0eff;
}
}
span {
color: white;
text-transform: uppercase;
a {
color: #4e0eff;
text-decoration: none;
font-weight: bold;
}
}
}
`;
export default Register |
package com.sw.设计模式.行为型模式.memento.blackBox;
import com.sw.设计模式.行为型模式.memento.whiteBox.RoleStateMemento;
/**
* @author Wang Hao
* @date 2022/9/22 22:31
* @description 游戏角色类(发起人)
*/
public class GameRole {
/**
* 生命值
*/
private int vit;
/**
* 攻击值
*/
private int atk;
/**
* 防御值
*/
private int def;
public int getVit() {
return vit;
}
public void setVit(int vit) {
this.vit = vit;
}
public int getAtk() {
return atk;
}
public void setAtk(int atk) {
this.atk = atk;
}
public int getDef() {
return def;
}
public void setDef(int def) {
this.def = def;
}
/**
* 初始化内部状态
*/
public void initState() {
this.vit = 100;
this.atk = 100;
this.def = 100;
}
/**
* 战斗
*/
public void fight() {
this.vit = 0;
this.atk = 0;
this.def = 0;
}
/**
* 保存游戏角色状态
*
* @return
*/
public Memento saveState() {
return new RoleStateMemento(vit, atk, def);
}
/**
* 恢复角色状态
*
* @param memento
*/
public void recoverState(Memento memento) {
RoleStateMemento roleStateMemento = (RoleStateMemento) memento;
this.vit = roleStateMemento.getVit();
this.atk = roleStateMemento.getAtk();
this.def = roleStateMemento.getDef();
}
/**
* 展示角色状态
*/
public void displayState() {
System.out.println("生命值:" + vit);
System.out.println("攻击值:" + vit);
System.out.println("防御值:" + vit);
}
private class RoleStateMemento implements Memento {
/**
* 生命值
*/
private int vit;
/**
* 攻击值
*/
private int atk;
/**
* 防御值
*/
private int def;
public RoleStateMemento() {
}
public RoleStateMemento(int vit, int atk, int def) {
this.vit = vit;
this.atk = atk;
this.def = def;
}
public int getVit() {
return vit;
}
public void setVit(int vit) {
this.vit = vit;
}
public int getAtk() {
return atk;
}
public void setAtk(int atk) {
this.atk = atk;
}
public int getDef() {
return def;
}
public void setDef(int def) {
this.def = def;
}
}
} |
const Sequelize = require('sequelize');
module.exports = (sequelize) => {
const Usuario = sequelize.define('Usuario', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true,
},
},
password: {
type: Sequelize.STRING,
allowNull: false,
validate: {
len: [8, 255],
},
},
name: {
type: Sequelize.STRING,
allowNull: false,
validate: {
len: [2, 255],
},
},
});
Usuario.associate = (models) => {
Usuario.hasMany(models.Despesa, {
foreignKey: 'userId',
as: 'despesas',
});
};
return Usuario;
}; |
package com.charlye934.shoppinliverpool.home.presenter.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.core.view.MenuProvider
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.charlye934.shoppinliverpool.R
import com.charlye934.shoppinliverpool.databinding.FragmentListProductsBinding
import com.charlye934.shoppinliverpool.home.domain.model.ProductCardUI
import com.charlye934.shoppinliverpool.home.presenter.adapter.ProductsListAdapter
import com.charlye934.shoppinliverpool.home.presenter.viewmodel.HomeViewModel
import com.charlye934.shoppinliverpool.util.ConstantsServices.VISIBLE_THRESHOLD
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ListProductsFragment : Fragment() {
private lateinit var _binding: FragmentListProductsBinding
private val binding: FragmentListProductsBinding get() = _binding
private val viewModel: HomeViewModel by activityViewModels()
private lateinit var productsListAdapter: ProductsListAdapter
private var searchWord = ""
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentListProductsBinding.inflate(layoutInflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpToolbar()
setUpRecyclerView()
configSearchEvent()
setOnRefreshListener()
viewModel.numPage.value?.let { viewModel.getDataProducts(page = it) }
viewModel.listDataProducts.observe(viewLifecycleOwner){
_binding.refresh.isRefreshing = false
configuratinoListAdapter(it)
}
}
private fun setUpToolbar(){
_binding.toolbarView.toolbar.apply {
title = getString(R.string.title_liverpool)
addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.menu_sort, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
when(menuItem.itemId){
R.id.action_sort_more_new -> {
_binding.rvProducts.scrollToPosition(0)
}
R.id.action_sort_relevancia -> {
_binding.rvProducts.scrollToPosition(0)
}
R.id.action_sort_less_price -> {
_binding.rvProducts.scrollToPosition(0)
}
R.id.action_more_price -> {
_binding.rvProducts.scrollToPosition(0)
}
R.id.action_calification -> {
_binding.rvProducts.scrollToPosition(0)
}
}
return true
}
})
}
}
private fun setUpRecyclerView(){
_binding.rvProducts.apply {
productsListAdapter = ProductsListAdapter()
layoutManager = LinearLayoutManager(requireContext())
adapter = productsListAdapter
addOnScrollListener(object : RecyclerView.OnScrollListener(){
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val totalItemCount = (layoutManager as LinearLayoutManager).itemCount
val lastVisibleItem = (layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
if (totalItemCount <= (lastVisibleItem + VISIBLE_THRESHOLD)) {
viewModel.updatePage(true)
viewModel.numPage.value?.let { viewModel.getDataProducts(page = it, search = searchWord) }
}
}
})
}
}
private fun configuratinoListAdapter(listProducts: List<ProductCardUI>){
productsListAdapter.apply {
submitList(listProducts)
notifyItemRangeChanged(0, listProducts.size)
}
}
private fun configSearchEvent(){
_binding.searchView.apply {
txtSearch.addTextChangedListener { eventFilter ->
searchWord = eventFilter.toString()
}
searchIconImageView.setOnClickListener {
viewModel.updatePage(false)
viewModel.getDataProducts(page = viewModel.numPage.value, search = searchWord, clearData = true)
}
icClear.setOnClickListener {
searchWord = ""
txtSearch.setText("")
viewModel.updatePage(false)
viewModel.getDataProducts(page = viewModel.numPage.value, search = searchWord, clearData = true)
}
}
}
private fun setOnRefreshListener(){
_binding.refresh.apply {
setOnRefreshListener {
viewModel.updatePage(false)
viewModel.getDataProducts(page = viewModel.numPage.value, search = searchWord, clearData = true)
}
}
}
} |
#include "ops.h"
EncoderOp::EncoderOp(vector<TensorObj> inputs_, vector<TensorObj> outputs_) : Ops(inputs_, outputs_) {}
void EncoderOp::forward()
{
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int C = inputs[1].shape[1];
for (int b = 0; b < B; b++)
{
for (int t = 0; t < T; t++)
{
// seek to the output position in out[b,t,:]
float *out_bt = reinterpret_cast<float *>(outputs[0].ptr) + b * T * C + t * C;
// get the index of the token at inp[b, t]
int *ix = reinterpret_cast<int *>(inputs[0].ptr) + b * T + t;
// seek to the position in wte corresponding to the token
float *wte_ix = reinterpret_cast<float *>(inputs[1].ptr) + (*ix) * C;
// seek to the position in wpe corresponding to the position
float *wpe_t = reinterpret_cast<float *>(inputs[2].ptr) + t * C;
// add the two vectors and store the result in out[b,t,:]
for (int c = 0; c < C; c++)
{
out_bt[c] = wte_ix[c] + wpe_t[c];
}
}
}
}
void EncoderOp::backward()
{
// inputs[0] is dout (B,T,C)
// inputs[1] is model inputs
// outputs[0] is grad_wte
// outputs[1] is grad_wpe
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int C = inputs[0].shape[2];
for (int b = 0; b < B; b++)
{
int *ix = reinterpret_cast<int *>(inputs[1].ptr) + b * T;
for (int t = 0; t < T; t++)
{
float *dout_bt = reinterpret_cast<float *>(inputs[0].ptr) + b * T * C + t * C;
int ix_val = ix[t];
float *dwte_ix = reinterpret_cast<float *>(outputs[0].ptr) + ix_val * C;
float *dwpe_t = reinterpret_cast<float *>(outputs[1].ptr) + t * C;
for (int c = 0; c < C; c++)
{
float d = dout_bt[c];
dwte_ix[c] += d;
dwpe_t[c] += d;
}
}
}
}
LayerNormOp::LayerNormOp(vector<TensorObj> inputs_, vector<TensorObj> outputs_) : Ops(inputs_, outputs_) {}
void LayerNormOp::forward()
{
// inputs[0] is inp (B,T,C)
// inputs[1] is weight (C,)
// inputs[2] is bias (C,)
// outputs[0] is out (B,T,C)
// outputs[1] is mean (B,T)
// outputs[2] is rstd (B,T)
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int C = inputs[0].shape[2];
float eps = 1e-5f;
for (int b = 0; b < B; b++)
{
float *mean = reinterpret_cast<float *>(outputs[1].ptr) + b * T;
float *rstd = reinterpret_cast<float *>(outputs[2].ptr) + b * T;
for (int t = 0; t < T; t++)
{
// seek to the input position inp[b,t,:]
float *x = reinterpret_cast<float *>(inputs[0].ptr) + b * T * C + t * C;
// calculate the mean
float m = 0.0f;
for (int c = 0; c < C; c++)
{
m += x[c];
}
m /= C;
// calculate the variance
float v = 0.0f;
for (int c = 0; c < C; c++)
{
v += (x[c] - m) * (x[c] - m);
}
v /= C;
// calculate the standard deviation
float s = 1.0f / sqrt(v + eps);
// seek to the output position out[b,t,:]
float *out_bt = reinterpret_cast<float *>(outputs[0].ptr) + b * T * C + t * C;
// normalize the input and store the result in out[b,t,:]
for (int c = 0; c < C; c++)
{
out_bt[c] = (x[c] - m) * s;
// out * weight + bias
out_bt[c] = out_bt[c] * reinterpret_cast<float *>(inputs[1].ptr)[c] + reinterpret_cast<float *>(inputs[2].ptr)[c];
}
mean[t] = m;
rstd[t] = s;
}
}
}
void LayerNormOp::backward()
{
// inputs[0] is dout (B,T,C)
// inputs[1] is inp (B,T,C)
// inputs[2] is weight
// inputs[3] is mean
// inputs[4] is rstd
// outputs[0] is grad_inp
// outputs[1] is grad_weight
// outputs[2] is grad_bias
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int C = inputs[0].shape[2];
for (int b = 0; b < B; b++)
{
float *mean = reinterpret_cast<float *>(inputs[3].ptr) + b * T;
float *rstd = reinterpret_cast<float *>(inputs[4].ptr) + b * T;
for (int t = 0; t < T; t++)
{
float *dout_bt = reinterpret_cast<float *>(inputs[0].ptr) + b * T * C + t * C;
float *inp_bt = reinterpret_cast<float *>(inputs[1].ptr) + b * T * C + t * C;
float *dinp_bt = reinterpret_cast<float *>(outputs[0].ptr) + b * T * C + t * C;
float mean_t = mean[t];
float rstd_t = rstd[t];
// first: two reduce operations
float dnorm_mean = 0.0f;
float dnorm_norm_mean = 0.0f;
for (int c = 0; c < C; c++)
{
float norm_bti = (inp_bt[c] - mean_t) * rstd_t;
float dnorm_i = reinterpret_cast<float *>(inputs[2].ptr)[c] * dout_bt[c];
dnorm_mean += dnorm_i;
dnorm_norm_mean += norm_bti * dnorm_i;
}
dnorm_mean /= C;
dnorm_norm_mean /= C;
// now iterate again and accumulate all the gradients
for (int c = 0; c < C; c++)
{
float norm_bti = (inp_bt[c] - mean_t) * rstd_t;
float dnorm_i = reinterpret_cast<float *>(inputs[2].ptr)[c] * dout_bt[c];
// gradient contribution to bias
reinterpret_cast<float *>(outputs[2].ptr)[c] += dnorm_i;
// gradient contribution to weights
reinterpret_cast<float *>(outputs[1].ptr)[c] += norm_bti * dout_bt[c];
// gradient contribution to input
float dval = 0.0f;
dval += dnorm_i;
dval -= dnorm_mean;
dval -= dnorm_norm_mean * norm_bti;
dval *= rstd_t;
dinp_bt[c] += dval;
}
}
}
}
MatMulOp::MatMulOp(vector<TensorObj> inputs_, vector<TensorObj> outputs_) : Ops(inputs_, outputs_) {}
void MatMulOp::forward()
{
// inputs[0] is inp
// inputs[1] is weight
// inputs[2] is bias
// outputs[0] is out
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int C = inputs[0].shape[2];
int OC = inputs[1].shape[0];
#pragma omp parallel for collapse(2)
for (int b = 0; b < B; b++)
{
for (int t = 0; t < T; t++)
{
// seek to the output position in out[b,t,:]
float *out_bt = reinterpret_cast<float *>(outputs[0].ptr) + b * T * OC + t * OC;
// seek to the input position in inp[b,t,:]
float *inp_bt = reinterpret_cast<float *>(inputs[0].ptr) + b * T * C + t * C;
for (int o = 0; o < OC; o++)
{
float val = inputs.size() == 2 ? 0.0f : reinterpret_cast<float *>(inputs[2].ptr)[o];
float *wrow = reinterpret_cast<float *>(inputs[1].ptr) + o * C;
for (int c = 0; c < C; c++)
{
val += inp_bt[c] * wrow[c];
}
out_bt[o] = val;
}
}
}
}
void MatMulOp::backward()
{
// inputs[0] is dout (B,T,OC)
// inputs[1] is inp (B,T,C)
// inputs[2] is weight
// outputs[0] is grad_inp
// outputs[1] is grad_weight
// outputs[2] is grad_bias
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int OC = inputs[0].shape[2];
int C = inputs[1].shape[2];
// backward into inp first
#pragma omp parallel for collapse(2)
for (int b = 0; b < B; b++)
{
for (int t = 0; t < T; t++)
{
float *dout_bt = reinterpret_cast<float *>(inputs[0].ptr) + b * T * OC + t * OC;
float *dinp_bt = reinterpret_cast<float *>(outputs[0].ptr) + b * T * C + t * C;
for (int o = 0; o < OC; o++)
{
float *wrow = reinterpret_cast<float *>(inputs[2].ptr) + o * C;
float d = dout_bt[o];
for (int c = 0; c < C; c++)
{
dinp_bt[c] += d * wrow[c];
}
}
}
}
// backward into weight/bias
#pragma omp parallel for
for (int o = 0; o < OC; o++)
{
for (int b = 0; b < B; b++)
{
for (int t = 0; t < T; t++)
{
float *dout_bt = reinterpret_cast<float *>(inputs[0].ptr) + b * T * OC + t * OC;
float *inp_bt = reinterpret_cast<float *>(inputs[1].ptr) + b * T * C + t * C;
float *dwrow = reinterpret_cast<float *>(outputs[1].ptr) + o * C;
float d = dout_bt[o];
// have bias
if (outputs.size() == 3)
{
float *dbias = reinterpret_cast<float *>(outputs[2].ptr);
dbias[o] += d;
}
for (int i = 0; i < C; i++)
{
dwrow[i] += d * inp_bt[i];
}
}
}
}
}
AttentionOp::AttentionOp(vector<TensorObj> inputs_, vector<TensorObj> outputs_) : Ops(inputs_, outputs_) {}
void AttentionOp::forward()
{
// inputs[0] is qkv (B,T,3C)
// outputs[0] is atty (B,T,C)
// outputs[1] is preatt (B,NH,T,T)
// outputs[2] is att (B,NH,T,T)
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int C3 = inputs[0].shape[2];
int C = outputs[0].shape[2];
int NH = outputs[1].shape[1];
int hs = C / NH;
float scale = 1.0f / sqrt(hs);
#pragma omp parallel for collapse(3)
for (int b = 0; b < B; b++)
{
for (int t = 0; t < T; t++)
{
for (int h = 0; h < NH; h++)
{
float *query_t = reinterpret_cast<float *>(inputs[0].ptr) + b * T * C3 + t * C3 + h * hs;
float *preatt_bth = reinterpret_cast<float *>(outputs[1].ptr) + b * NH * T * T + h * T * T + t * T;
float *att_bth = reinterpret_cast<float *>(outputs[2].ptr) + b * NH * T * T + h * T * T + t * T;
// 1. calculate the attention scores (QKT)
float maxval = -10000.0f;
for (int t2 = 0; t2 <= t; t2++)
{
float *key_t2 = reinterpret_cast<float *>(inputs[0].ptr) + b * T * C3 + t2 * C3 + h * hs + C;
// query_t * key_t2
float val = 0.0f;
for (int c = 0; c < hs; c++)
{
val += query_t[c] * key_t2[c];
}
val *= scale;
maxval = max(maxval, val);
preatt_bth[t2] = val;
}
// 2. calculate the exp and sum
float expsum = 0.0f;
for (int t2 = 0; t2 <= t; t2++)
{
float expv = exp(preatt_bth[t2] - maxval);
expsum += expv;
att_bth[t2] = expv;
}
float expsum_inv = expsum == 0.0f ? 0.0f : 1.0f / expsum;
// 3. normalize to get the softmax
for (int t2 = 0; t2 < T; t2++)
{
if (t2 <= t)
{
att_bth[t2] *= expsum_inv;
}
else
{
// causal attention mask. not strictly necessary to set to zero here
// only doing this explicitly for debugging and checking to PyTorch
att_bth[t2] = 0.0f;
}
}
// 4. calculate the weighted values into the output of attention
float *out_bth = reinterpret_cast<float *>(outputs[0].ptr) + b * T * C + t * C + h * hs;
for (int i = 0; i < hs; i++)
{
out_bth[i] = 0.0f;
}
for (int t2 = 0; t2 <= t; t2++)
{
float *value_t2 = reinterpret_cast<float *>(inputs[0].ptr) + b * T * C3 + t2 * C3 + h * hs + 2 * C;
float att_btht2 = att_bth[t2];
for (int i = 0; i < hs; i++)
{
out_bth[i] += att_btht2 * value_t2[i];
}
}
}
}
}
}
void AttentionOp::backward()
{
// inputs[0] is dout (B,T,C)
// inputs[1] is qkv (B,T,3C)
// inputs[2] is att (B,NH,T,T)
// outputs[0] is grad_qkv
// outputs[1] is grad_preatt
// outputs[2] is grad_att
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int C = inputs[0].shape[2];
int NH = inputs[2].shape[1];
int C3 = inputs[1].shape[2];
int hs = C / NH;
float scale = 1.0f / sqrt(hs);
for (int b = 0; b < B; b++)
{
for (int t = 0; t < T; t++)
{
for (int h = 0; h < NH; h++)
{
float *att_bth = reinterpret_cast<float *>(inputs[2].ptr) + b * NH * T * T + h * T * T + t * T;
float *datt_bth = reinterpret_cast<float *>(outputs[2].ptr) + b * NH * T * T + h * T * T + t * T;
float *dpreatt_bth = reinterpret_cast<float *>(outputs[1].ptr) + b * NH * T * T + h * T * T + t * T;
float *dquery_t = reinterpret_cast<float *>(outputs[0].ptr) + b * T * C3 + t * C3 + h * hs;
float *query_t = reinterpret_cast<float *>(inputs[1].ptr) + b * T * C3 + t * C3 + h * hs;
// backward pass 4, through the value accumulation
float *dout_bth = reinterpret_cast<float *>(inputs[0].ptr) + b * T * C + t * C + h * hs;
for (int t2 = 0; t2 <= t; t2++)
{
float *value_t2 = reinterpret_cast<float *>(inputs[1].ptr) + b * T * C3 + t2 * C3 + h * hs + 2 * C;
float *dvalue_t2 = reinterpret_cast<float *>(outputs[0].ptr) + b * T * C3 + t2 * C3 + h * hs + 2 * C;
for (int i = 0; i < hs; i++)
{
// in the forward pass this was:
// out_bth[i] += att_bth[t2] * value_t2[i];
// so now we have:
datt_bth[t2] += value_t2[i] * dout_bth[i];
dvalue_t2[i] += att_bth[t2] * dout_bth[i];
}
}
// backward pass 2&3, the softmax
for (int t2 = 0; t2 <= t; t2++)
{
for (int t3 = 0; t3 <= t; t3++)
{
float indicator = t2 == t3 ? 1.0f : 0.0f;
float local_derivative = att_bth[t2] * (indicator - att_bth[t3]);
dpreatt_bth[t3] += local_derivative * datt_bth[t2];
}
}
// backward pass 1, the query @ key matmul
for (int t2 = 0; t2 <= t; t2++)
{
float *key_t2 = reinterpret_cast<float *>(inputs[1].ptr) + b * T * C3 + t2 * C3 + h * hs + C;
float *dkey_t2 = reinterpret_cast<float *>(outputs[0].ptr) + b * T * C3 + t2 * C3 + h * hs + C;
for (int i = 0; i < hs; i++)
{
// in the forward pass this was:
// preatt_bth[t2] += (query_t[i] * key_t2[i]) * scale;
// so now we have:
dquery_t[i] += key_t2[i] * dpreatt_bth[t2] * scale;
dkey_t2[i] += query_t[i] * dpreatt_bth[t2] * scale;
}
}
}
}
}
}
ResidualOp::ResidualOp(vector<TensorObj> inputs_, vector<TensorObj> outputs_) : Ops(inputs_, outputs_) {}
void ResidualOp::forward()
{
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int C = inputs[0].shape[2];
int N = B * T * C;
float *inp = reinterpret_cast<float *>(inputs[0].ptr);
float *inp2 = reinterpret_cast<float *>(inputs[1].ptr);
float *out = reinterpret_cast<float *>(outputs[0].ptr);
for (int i = 0; i < N; i++)
{
out[i] = inp[i] + inp2[i];
}
}
void ResidualOp::backward()
{
// inputs[0] shape is (B,T,C)
// outputs[0] shape is (B,T,C)
// outputs[1] shape is (B,T,C)
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int C = inputs[0].shape[2];
int N = B * T * C;
float *grad_inp = reinterpret_cast<float *>(inputs[0].ptr);
float *grad_out = reinterpret_cast<float *>(outputs[0].ptr);
float *grad_out2 = reinterpret_cast<float *>(outputs[1].ptr);
for (int i = 0; i < N; i++)
{
grad_out[i] += grad_inp[i];
grad_out2[i] += grad_inp[i];
}
}
GeluOp::GeluOp(vector<TensorObj> inputs_, vector<TensorObj> outputs_) : Ops(inputs_, outputs_) {}
void GeluOp::forward()
{
// inputs[0] shape is (B,T,4*C)
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int C = inputs[0].shape[2];
int N = B * T * C;
float *inp = reinterpret_cast<float *>(inputs[0].ptr);
float *out = reinterpret_cast<float *>(outputs[0].ptr);
float s = sqrt(2.0f / 3.14159265358979323846f);
for (int i = 0; i < N; i++)
{
float x = inp[i];
out[i] = 0.5f * x * (1.0f + tanh(s * (x + 0.044715f * x * x * x)));
}
}
void GeluOp::backward()
{
// inputs[0] is grad_act[fch_gelu],shape is (B,T,4*C)
// inputs[1] is act[fch],shape is (B,T,4*C)
// output[0] is grad_act[fch],shape is (B,T,4*C)
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int C = inputs[0].shape[2];
int N = B * T * C;
float s = sqrt(2.0f / 3.14159265358979323846f);
float *inp_grad = reinterpret_cast<float *>(inputs[0].ptr);
float *inp_act = reinterpret_cast<float *>(inputs[1].ptr);
float *out_grad = reinterpret_cast<float *>(outputs[0].ptr);
for (int i = 0; i < N; i++)
{
float x = inp_act[i];
float cube = 0.044715f * x * x * x;
float tanh_arg = s * (x + cube);
float tanh_out = tanh(tanh_arg);
float coshf_out = cosh(tanh_arg);
float sech_out = 1.0f / (coshf_out * coshf_out);
float local_grad = 0.5f * (1.0f + tanh_out) + x * 0.5f * sech_out * s * (1.0f + 3.0f * 0.044715f * x * x);
out_grad[i] += local_grad * inp_grad[i];
}
}
SoftmaxOp::SoftmaxOp(vector<TensorObj> inputs_, vector<TensorObj> outputs_) : Ops(inputs_, outputs_) {}
void SoftmaxOp::forward()
{
// inputs[0] is logits is (B,T,V)
// outputs[0] is probs is (B,T,V)
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int V = inputs[0].shape[2];
#pragma omp parallel for collapse(2)
for (int b = 0; b < B; b++)
{
for (int t = 0; t < T; t++)
{
float *logits_bt = reinterpret_cast<float *>(inputs[0].ptr) + b * T * V + t * V;
float *probs_bt = reinterpret_cast<float *>(outputs[0].ptr) + b * T * V + t * V;
float maxval = -10000.0f;
for (int v = 0; v < V; v++)
{
maxval = max(maxval, logits_bt[v]);
}
float sum = 0.0f;
for (int v = 0; v < V; v++)
{
float val = exp(logits_bt[v] - maxval);
probs_bt[v] = val;
sum += val;
}
for (int v = 0; v < V; v++)
{
probs_bt[v] /= sum;
}
}
}
}
void SoftmaxOp::backward()
{
// wait to implement
}
CrossEntropyOp::CrossEntropyOp(vector<TensorObj> inputs_, vector<TensorObj> outputs_) : Ops(inputs_, outputs_) {}
void CrossEntropyOp::forward()
{
// inputs[0] is probs (B,T,V)
// inputs[1] is target (B,T)
// outputs[0] is loss (B,T)
int B = inputs[0].shape[0];
int T = inputs[0].shape[1];
int V = inputs[0].shape[2];
for (int b = 0; b < B; b++)
{
for (int t = 0; t < T; t++)
{
float *probs_bt = reinterpret_cast<float *>(inputs[0].ptr) + b * T * V + t * V;
int *target_bt = reinterpret_cast<int *>(inputs[1].ptr) + b * T + t;
float *loss_bt = reinterpret_cast<float *>(outputs[0].ptr) + b * T + t;
*loss_bt = -log(probs_bt[*target_bt]);
}
}
}
void CrossEntropyOp::backward()
{
// input[0] is grad_act[losses], shape is (B,T)
// input[1] is act[probs], shape is (B,T,V)
// input[2] is model targets, shape is (B,T)
// output[0] is grad_act[logits], shape is (B,T,V)
int B = inputs[1].shape[0];
int T = inputs[1].shape[1];
int V = inputs[1].shape[2];
for (int b = 0; b < B; b++)
{
float *dloss_bt = reinterpret_cast<float *>(inputs[0].ptr) + b * T;
int *ix = reinterpret_cast<int *>(inputs[2].ptr) + b * T;
for (int t = 0; t < T; t++)
{
float *dlogits_bt = reinterpret_cast<float *>(outputs[0].ptr) + b * T * V + t * V;
float *probs_bt = reinterpret_cast<float *>(inputs[1].ptr) + b * T * V + t * V;
float dloss = dloss_bt[t];
int target = ix[t];
for (int v = 0; v < V; v++)
{
float indicator = v == target ? 1.0f : 0.0f;
dlogits_bt[v] += (probs_bt[v] - indicator) * dloss;
}
}
}
} |
<?php
/**
* "Loop After Content" Functions
*
* @package Saved
* @subpackage Functions
* @copyright Copyright (c) 2017, ChurchThemes.com
* @link https://churchthemes.com/themes/saved
* @license GPLv2 or later
* @since 1.0
*/
// No direct access
if ( ! defined( 'ABSPATH' ) ) exit;
/*********************************
* LOOP AFTER CONTENT
*********************************/
/**
* Get "loop after content" query
*
* @since 1.0
* @return object WP_Query object
*/
function saved_loop_after_content_query() {
$query = apply_filters( 'saved_loop_after_content_query', false );
// Post type must be supported.
if ( isset( $query->query['post_type'] ) && ! post_type_exists( $query->query['post_type'] ) ) {
$query = false;
}
return $query;
}
/**
* Check if "loop after content" is being used
*
* @since 1.0
* @return bool Whether or not "loop after content" is used
*/
function saved_loop_after_content_used() {
$used = false;
if ( saved_loop_after_content_query() ) {
$used = true;
}
return apply_filters( 'saved_loop_after_content_used', $used );
}
/**
* Output the loop by loading template
*
* @since 1.0
* @global object $wp_query
*/
function saved_loop_after_content_output() {
global $wp_query;
// Loop posts based on query from filter
$query = saved_loop_after_content_query();
if ( $query ) {
// Preserve original query for after loop
$original_query = $wp_query;
$wp_query = $query;
// Loop posts with loop.php
echo '<div id="saved-loop-after-content" class="saved-loop-after-content">';
get_template_part( 'loop' );
echo '</div>';
// Restore original query
$wp_query = $original_query;
wp_reset_postdata(); // restore $post global in main query
}
}
/**
* Make loop content show after content
*
* @since 1.0
*/
function saved_loop_after_content() {
// Front-end only
if ( ! is_admin() ) {
// Make content available via action placed after content (see content.php)
add_action( 'saved_after_content', 'saved_loop_after_content_output' );
}
}
add_action( 'init', 'saved_loop_after_content' ); |
import React, { useEffect, useState } from "react";
import "./App.scss";
import Home from "./containers/home";
import {
createBrowserRouter,
Navigate,
BrowserRouter as Router,
RouterProvider,
} from "react-router-dom";
import Login from "./containers/login";
import { ChakraProvider } from "@chakra-ui/react";
import SignUp from "./containers/signup";
import { PATH } from "./constants/path";
import { QueryClient, QueryClientProvider } from "react-query";
import NavBar from "./components/NavBar";
import Observations from "./containers/observations";
import Allergies from "./containers/allergies";
import Conditions from "./containers/conditions";
import Whitelist from "./containers/whitelist";
import AddObservation from "./containers/add-observation";
import { UserProvider, useUserContext } from "./model/user/userContext";
import { CookiesProvider, useCookies } from "react-cookie";
import Medications from "./containers/medications";
import AddCondition from "./containers/add-condition";
import Profile from "./containers/profile";
import AddAllergy from "./containers/add-allergy";
import AddMedication from "./containers/add-medication";
import { customizedTheme } from "./theme";
import Patients from "./containers/patients";
import AllRecords from "./containers/all-records";
import Doctors from "./containers/doctors";
import Intro from "./containers/intro";
function App() {
const queryClient = new QueryClient();
const [cookies, setCookie] = useCookies(["Authorization"]);
const [authenticated, setAuthenticated] = useState(
cookies.Authorization ? true : false
);
useEffect(() => {
if (cookies.Authorization) {
setAuthenticated(true);
} else {
setAuthenticated(false);
}
}, [cookies]);
const ProtectedRoute = ({ children }: any) => {
const { user, setUser } = useUserContext();
useEffect(() => {
if (authenticated) {
console.log("Authhh");
setUser({
...user,
isLoggedIn: true,
});
}
}, [authenticated]);
if (!authenticated) {
return <Navigate to={PATH.Login} replace />;
}
return (
<div className="flex bg-primaryBlue-500 h-screen">
<NavBar />
<div className="overflow-y-scroll w-full">{children}</div>
</div>
);
};
const router = createBrowserRouter([
{
path: PATH.Login,
element: <Login />,
},
{
path: PATH.SignUp,
element: <SignUp />,
},
{
path: PATH.Intro,
element: <Intro />,
},
{
path: PATH.Home,
element: (
<ProtectedRoute>
<Home />
</ProtectedRoute>
),
},
{
path: PATH.Observations,
element: (
<ProtectedRoute>
<Observations />
</ProtectedRoute>
),
},
{
path: PATH.Allergies,
element: (
<ProtectedRoute>
<Allergies />
</ProtectedRoute>
),
},
{
path: PATH.Conditions,
element: (
<ProtectedRoute>
<Conditions />
</ProtectedRoute>
),
},
{
path: PATH.Medications,
element: (
<ProtectedRoute>
<Medications />
</ProtectedRoute>
),
},
{
path: PATH.Whitelist,
element: (
<ProtectedRoute>
<Whitelist />
</ProtectedRoute>
),
},
{
path: PATH.AddObservation,
element: (
<ProtectedRoute>
<AddObservation />
</ProtectedRoute>
),
},
{
path: PATH.AddCondition,
element: (
<ProtectedRoute>
<AddCondition />
</ProtectedRoute>
),
},
{
path: PATH.AddAllergy,
element: (
<ProtectedRoute>
<AddAllergy />
</ProtectedRoute>
),
},
{
path: PATH.AddMedication,
element: (
<ProtectedRoute>
<AddMedication />
</ProtectedRoute>
),
},
{
path: PATH.Patient,
element: (
<ProtectedRoute>
<Patients />
</ProtectedRoute>
),
},
{
path: PATH.Profile,
element: (
<ProtectedRoute>
<Profile />
</ProtectedRoute>
),
},
{
path: PATH.AllRecords,
element: (
<ProtectedRoute>
<AllRecords />
</ProtectedRoute>
),
},
{
path: PATH.Doctors,
element: (
<ProtectedRoute>
<Doctors />
</ProtectedRoute>
),
},
]);
return (
<UserProvider>
<CookiesProvider>
<QueryClientProvider client={queryClient}>
<ChakraProvider theme={customizedTheme}>
<RouterProvider router={router} />
</ChakraProvider>
</QueryClientProvider>
</CookiesProvider>
</UserProvider>
);
}
export default App; |
use std::iter::Iterator;
pub fn array_demo() {
let arr = [1, 3, 66];
for (i, &n) in arr.iter().enumerate() {
println!("arr[{}] = {}", i, n);
}
println!("The usual array = {:?}", arr);
let numbers = [1; 5];
println!("Array with default args = {:?}", numbers);
let fruits: [&str; 3] = ["appl", "orang", "bana"];
for i in 0..arr.len() {
println!("fruit {} = {}", i, fruits[i]);
}
println!("all fruits = {:?}", fruits);
}
pub fn slices_demo() {
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let id1 = 2;
let id2 = 5;
let slice = &arr[id1..id2];
println!("slice from {} to {} = {:?}", id1, id2, slice);
let a: [i32; 6] = [10, 20, 30, 40, 50, 60];
println!("a: {:?}", a);
let s: &[i32] = &a[2..4];
println!("s: {:?}", s);
}
pub fn structs_demo() {
#[allow(dead_code)]
#[derive(Debug)]
struct Person {
name: String,
age: u8,
height: u8
}
let p1 = Person {
name: String::from("John"),
age: 32,
height: 180
};
println!("Person = {}", p1.name);
println!("Person = {:?}", p1);
println!("Person = {:#?}", p1);
} |
import com.application.weather.data.WeatherData
import com.application.weather.database.WeatherDatabase
import com.application.weather.database.WeatherEntity
import com.application.weather.network.WeatherService
import com.application.weather.repository.WeatherRepository
import io.kotest.core.spec.style.FunSpec
import io.mockk.*
import io.reactivex.subjects.BehaviorSubject
class WeatherRepositoryTest : FunSpec({
val database = mockk<WeatherDatabase>()
val weatherService = mockk<WeatherService>()
val repository: WeatherRepository by lazy {
WeatherRepository(database, weatherService)
}
beforeTest {
MockKAnnotations.init(this)
}
test("get weather from weather service") {
val weather = BehaviorSubject.create<WeatherData>()
every { weatherService.getWeather("")} returns weather
repository.getWeather("")
verify { weatherService.getWeather("") }
}
test("get weather from database") {
val weather = BehaviorSubject.create<List<WeatherEntity>>()
every { database.getWeather()} returns weather
repository.getWeather()
verify { database.getWeather() }
}
}) |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.mytracks.R;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
/**
* Manage the application menus.
*
* @author Sandor Dornbush
*/
class MenuManager {
private MyTracks activity;
public MenuManager(MyTracks activity) {
this.activity = activity;
}
public boolean onCreateOptionsMenu(Menu menu) {
activity.getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onPrepareOptionsMenu(Menu menu, boolean hasRecorded,
boolean isRecording, boolean hasSelectedTrack) {
menu.findItem(R.id.menu_list_tracks).setEnabled(hasRecorded);
menu.findItem(R.id.menu_list_markers)
.setEnabled(hasRecorded && hasSelectedTrack);
MenuItem startRecording = menu.findItem(R.id.menu_start_recording);
startRecording.setEnabled(!isRecording);
startRecording.setVisible(!isRecording);
MenuItem stopRecording = menu.findItem(R.id.menu_stop_recording);
stopRecording.setEnabled(isRecording);
stopRecording.setVisible(isRecording);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_start_recording: {
activity.startRecording();
return true;
}
case R.id.menu_stop_recording: {
activity.stopRecording();
return true;
}
case R.id.menu_list_tracks: {
Intent startIntent = new Intent(activity, MyTracksList.class);
activity.startActivityForResult(startIntent, MyTracksConstants.SHOW_TRACK);
return true;
}
case R.id.menu_list_markers: {
Intent startIntent = new Intent(activity, MyTracksWaypointsList.class);
startIntent.putExtra("trackid", activity.getSelectedTrack());
activity.startActivityForResult(startIntent, MyTracksConstants.SHOW_WAYPOINT);
return true;
}
case R.id.menu_settings: {
Intent startIntent = new Intent(activity, MyTracksSettings.class);
activity.startActivity(startIntent);
return true;
}
case R.id.menu_help: {
Intent startIntent = new Intent(activity, WelcomeActivity.class);
activity.startActivity(startIntent);
return true;
}
case MyTracksConstants.MENU_CLEAR_MAP: {
activity.setSelectedTrack(-1);
return true;
}
}
return false;
}
} |
/* Copyright Contributors to the Open Cluster Management project */
import { Namespace, NamespaceDefinition } from '../resources'
import { nockIgnoreApiPaths, nockRBAC } from './nock-util'
import { getAuthorizedNamespaces, isAnyNamespaceAuthorized } from './rbac-util'
import { waitForNocks } from './test-util'
const adminAccess = { name: '*', namespace: '*', resource: '*', verb: '*' }
const createDeployment = {
name: 'new-cluster-deployment',
resource: 'clusterdeployments',
verb: 'create',
group: 'hive.openshift.io',
}
describe('getAuthorizedNamespaces', () => {
it('checks each namespace individually for non-admin users', async () => {
nockIgnoreApiPaths()
const nocks = [
nockRBAC(adminAccess, false),
nockRBAC({ ...createDeployment, namespace: 'test-namespace-1' }, false),
nockRBAC({ ...createDeployment, namespace: 'test-namespace-2' }, true),
]
expect(
await getAuthorizedNamespaces(
[createDeployment],
[
{
...(NamespaceDefinition as Pick<Namespace, 'apiVersion' | 'kind'>),
metadata: { name: 'test-namespace-1' },
},
{
...(NamespaceDefinition as Pick<Namespace, 'apiVersion' | 'kind'>),
metadata: { name: 'test-namespace-2' },
},
]
)
).toEqual(['test-namespace-2'])
await waitForNocks(nocks)
})
})
describe('isAnyNamespaceAuthorized', () => {
it('checks each namespace individually for non-admin users', async () => {
nockIgnoreApiPaths()
const nocks = [
nockRBAC(adminAccess, false),
nockRBAC({ ...createDeployment, namespace: 'test-namespace-1' }, false),
nockRBAC({ ...createDeployment, namespace: 'test-namespace-2' }, true),
]
expect(
await isAnyNamespaceAuthorized(
[createDeployment],
[
{
...(NamespaceDefinition as Pick<Namespace, 'apiVersion' | 'kind'>),
metadata: { name: 'test-namespace-1' },
},
{
...(NamespaceDefinition as Pick<Namespace, 'apiVersion' | 'kind'>),
metadata: { name: 'test-namespace-2' },
},
]
)
).toEqual(true)
await waitForNocks(nocks)
})
it('returns false for an empty namespace list', async () => {
expect(await isAnyNamespaceAuthorized([createDeployment], [])).toEqual(false)
})
it('returns true without checking namespaces for an admin user', async () => {
nockIgnoreApiPaths()
const nocks = [nockRBAC(adminAccess, true)]
expect(
await isAnyNamespaceAuthorized(
[createDeployment],
[
{
...(NamespaceDefinition as Pick<Namespace, 'apiVersion' | 'kind'>),
metadata: { name: 'test-namespace-1' },
},
{
...(NamespaceDefinition as Pick<Namespace, 'apiVersion' | 'kind'>),
metadata: { name: 'test-namespace-2' },
},
]
)
).toEqual(true)
await waitForNocks(nocks)
})
}) |
define(['jquery', 'mustache', 'crossroads', 'hasher'], function(jq, Mustache, crossroads, hasher) {
function JsAutoP(s) {
if (!s || s.search(/\n|\r/) == -1) {
return s;
}
var X = function(x, a, b) {return x.replace(new RegExp(a, 'g'), b)};
var R = function(a, b) {return s = X(s, a, b)};
var blocks = '(table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select'
blocks += '|form|blockquote|address|math|style|script|object|input|param|p|h[1-6])';
s += '\n';
R('<br />\\s*<br />', '\n\n');
R('(<' + blocks + '[^>]*>)', '\n$1');
R('(</' + blocks + '>)', '$1\n\n');
R('\r\n|\r', '\n'); // cross-platform newlines
R('\n\n+', '\n\n');// take care of duplicates
R('\n?((.|\n)+?)\n\\s*\n', '<p>$1</p>\n');// make paragraphs
R('\n?((.|\n)+?)$', '<p>$1</p>\n');//including one at the end
R('<p>\\s*?</p>', '');// under certain strange conditions it could create a P of entirely whitespace
R('<p>(<div[^>]*>\\s*)', '$1<p>');
R('<p>([^<]+)\\s*?(</(div|address|form)[^>]*>)', '<p>$1</p>$2');
R('<p>\\s*(</?' + blocks + '[^>]*>)\\s*</p>', '$1');
R('<p>(<li.+?)</p>', '$1');// problem with nested lists
R('<p><blockquote([^>]*)>', '<blockquote$1><p>');
R('</blockquote></p>', '</p></blockquote>');
R('<p>\\s*(</?' + blocks + '[^>]*>)', '$1');
R('(</?' + blocks + '[^>]*>)\\s*</p>', '$1');
R('<(script|style)(.|\n)*?</\\1>', function(m0) {return X(m0, '\n', '<PNL>')});
R('(<br />)?\\s*\n', '<br />\n');
R('<PNL>', '\n');
R('(</?' + blocks + '[^>]*>)\\s*<br />', '$1');
R('<br />(\\s*</?(p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)', '$1');
if (s.indexOf('<pre') != -1) {
R('(<pre(.|\n)*?>)((.|\n)*?)</pre>', function(m0, m1, m2, m3) {
return X(m1, '\\\\([\'\"\\\\])', '$1') + X(X(X(m3, '<p>', '\n'), '</p>|<br />', ''), '\\\\([\'\"\\\\])', '$1') + '</pre>';
});
}
return R('\n</p>$', '</p>');
}
current_page = 1;
function get_recent(page) {
var url = 'http://localhost:3000/library/?page=' + page;
clearPanels();
jq.getJSON(url, function(data, status, jqXHR) {
var templateData = {'books': data['books']};
var template = jq('#book-list-template').html();
Mustache.parse(template);
var rendered = Mustache.render(template, templateData);
jq("#book-list").html(rendered);
jq('#book-list .book').on('click', function() {
var id = jq(this).data('id');
jq("#book-list").fadeOut('fast', function() {
hasher.setHash('book/' + id);
});
});
var next_page = data['next-page'];
var prev_page = data['prev-page'];
if (!next_page) {
jq("#book-list-pager button.next").attr('disabled', 'disabled');
} else {
jq("#book-list-pager button.next").removeAttr('disabled');
}
if (!prev_page) {
jq("#book-list-pager button.prev").attr('disabled', 'disabled');
} else {
jq("#book-list-pager button.prev").removeAttr('disabled');
}
jq("#book-list-pager button.next").on('click', function() {
hasher.setHash('page/' + ++current_page);
});
jq("#book-list-pager button.prev").on('click', function() {
hasher.setHash('page/' + --current_page);
});
jq("#book-list").fadeIn();
});
}
var route_home = crossroads.addRoute('/', function() {
get_recent(1);
});
var route_home_paged = crossroads.addRoute('/page/{page}', function(page) {
get_recent(page);
});
var route_book = crossroads.addRoute('/book/{slug}', function(slug) {
clearPanels();
jq.getJSON('http://localhost:3000/book/' + slug, function(data, status, jqXHR) {
data['description'] = JsAutoP(data['description']);
var templateData = {'book': data};
var template = jq('#book-detail-template').html();
Mustache.parse(template);
var rendered = Mustache.render(template, templateData);
jq("#book-detail").html(rendered);
jq("#book-detail").fadeIn();
});
});
function clearPanels() {
jq('.content-panel').html('').hide();
}
//setup hasher
function parseHash(newHash, oldHash){
crossroads.parse(newHash);
}
hasher.initialized.add(parseHash); //parse initial hash
hasher.changed.add(parseHash); //parse hash changes
hasher.init(); //start listening for history change
}); |
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::HashMap;
use std::path::Path;
use crate::error::{Er, E};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Metadata {
pub name: String,
pub url: String,
pub license: String,
pub audio: String,
pub native: String,
pub transcript: Option<String>,
pub translations: HashMap<String, String>,
#[serde(skip_serializing)]
#[serde(skip_deserializing)]
pub enclosing_directory: String,
}
impl Metadata {
pub fn from_filename(filename: String) -> E<Self> {
let mut f = std::fs::File::open(&filename)?;
let reader = std::io::BufReader::new(f);
let mut metadata: Self = serde_json::from_reader(reader)?;
metadata.enclosing_directory = Path::parent(&Path::new(&filename))
.unwrap()
.to_str()
.unwrap()
.to_string();
Ok(metadata)
}
pub fn from_resource_path(resource_path: &String) -> E<Self> {
let full_path = if resource_path.starts_with("/") {
resource_path.clone()
} else {
format!(
"{}/{}",
std::env::var("ASSETS_DIR").unwrap_or("../assets".to_string()),
resource_path
)
};
let metadata_path = format!("{}/metadata.json", full_path);
log::debug!("Path is {}", metadata_path);
let mut metadata = Metadata::from_filename(metadata_path)?;
metadata.enclosing_directory = full_path;
Ok(metadata)
}
} |
# Neon Velocity Game Documentation
## Table of Contents
1. [Introduction](#introduction)
2. [Game Overview](#game-overview)
3. [Gameplay Mechanics](#gameplay-mechanics)
4. [Game World Narrative](#game-world-narrative)
5. [Core Loops](#core-loops)
6. [Objectives and Progression](#objectives-and-progression)
7. [Game Systems](#game-systems)
8. [Interactivity](#interactivity)
9. [References](#references)
## 1. Introduction <a name="introduction"></a>
Neon Velocity is an adrenaline-fueled arcade racing game set in a futuristic world where AI drones find themselves trapped in time. Players embark on a thrilling journey to navigate through dynamic circuits, engage in combat with rival drones, and survive in both futuristic and retro environments.
## 2. Game Overview <a name="game-overview"></a>
- *Title:* Neon Velocity
- *Team Name:* Game Titans
- *Team Members:* Muhammad Tayyab, Mustaqim Afzal
- *Genre:* Arcade Racing, Shooting, Survival
- *Visual Style:* Cyberpunk with neon lights and sleek metallic surfaces, with occasional retro scenes inspired by ancient times
- *Audio Style:* Futuristic soundscapes with electronic beats in the future, retro-inspired melodies in the past
- *Assets:* Assets are used from Unity Asset Store
## 3. Gameplay Mechanics <a name="gameplay-mechanics"></a>
Neon Velocity combines arcade racing with shooting and survival elements. Players control AI drones navigating through neon-lit circuits suspended above futuristic cityscapes. Key gameplay mechanics include:
- Racing through procedurally generated tracks
- Dodging obstacles and engaging in combat with rival drones
- Collecting power-ups for tactical advantage
- Surviving in both futuristic and retro environments
- Balancing speed and survival to emerge victorious
- Control Inputs: Players use up, down, back, right keys for movement, "Q" key for firing.
## 4. Game World Narrative <a name="game-world-narrative"></a>
In the year 2087, futuristic AI drones dominate the skies of sprawling metropolises, engaging in adrenaline-fueled racing battles. However, a temporal anomaly disrupts the races, sending the drones hurtling through time to ancient eras. Players must navigate through both futuristic and retro environments, collecting ancient potions to restore health and time orbs to prolong survival. The journey to reclaim the future world becomes an unforgettable adventure filled with challenges and excitement.
## 5. Core Loops <a name="core-loops"></a>
### Race Loop:
- Navigate through procedurally generated tracks
- Dodge obstacles and engage in combat with rival drones
- Collect energy orbs and power-ups
- Pass through teleport doors to transition between past and future environments
### Power-Up Loop:
- Collect power-ups such as Turbo Boost, Hologram Decoy, EMP Pulse, and Quantum Warp
- Use power-ups strategically to gain an advantage in races
## 6. Objectives and Progression <a name="objectives-and-progression"></a>
### Short-Term Goals:
- Win races and achieve high scores
- Master power-ups for tactical advantage
- Survive in the past while time is running out
### Long-Term Goals:
- Uncover the mystery behind rogue AI drones disrupting the races
- Maintain drone health and achieve higher scores with each playthrough
## 7. Game Systems <a name="game-systems"></a>
### Physics System:
- Handles drone movement and collisions
### Combat System:
- Manages light disc combat and power-up interactions
### Progression System:
- Tracks player achievements, unlocks, and circuit progression
## 8. Interactivity <a name="interactivity"></a>
### Player Actions Moment-by-Moment:
- Steer the drone and perform acrobatics
- Engage in combat with light discs
- Activate power-ups strategically
### Player Movement:
- Race through neon-lit circuits and navigate tight turns
### Physics/Combat:
- Physics governs drone handling and collision responses
- Combat involves aiming and timing light disc throws
## 9. References <a name="references"></a>
- Tron Racing game for lightning effects
- Blur racing game for visual representation of power-ups
- Unity Asset Store for futuristic drone models
- UltraKill for retro environment aesthetics
- Surreal Skybox
- Emace Art
- TrollNest Free
- AS-Retro Adventure Theme
- Magic Sound Effects
- Laser Weapons Sound Pack
This comprehensive documentation provides an overview of Neon Velocity, detailing its concept, gameplay mechanics, narrative, objectives, game systems, and interactivity. Get ready to immerse yourself in the thrilling world of Neon Velocity and embark on an unforgettable racing adventure through time! |
/*
* (C) Copyright 2001, 2002, 2003
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
* Keith Outwater, keith_outwater@mvis.com`
* Steven Scholz, steven.scholz@imc-berlin.de
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* Date & Time support (no alarms) for Dallas Semiconductor (now Maxim)
* DS1307 and DS1338 Real Time Clock (RTC).
*
* based on ds1337.c
*/
#include <common.h>
#include <command.h>
#include <rtc.h>
#include <i2c.h>
#if (defined(CONFIG_RTC_DS1307) || defined(CONFIG_RTC_DS1338) ) && \
(CONFIG_COMMANDS & CFG_CMD_DATE)
/*---------------------------------------------------------------------*/
#undef DEBUG_RTC
#ifdef DEBUG_RTC
#define DEBUGR(fmt,args...) printf(fmt ,##args)
#else
#define DEBUGR(fmt,args...)
#endif
/*---------------------------------------------------------------------*/
#ifndef CFG_I2C_RTC_ADDR
# define CFG_I2C_RTC_ADDR 0x68
#endif
#if defined(CONFIG_RTC_DS1307) && (CFG_I2C_SPEED > 100000)
# error The DS1307 is specified only up to 100kHz!
#endif
/*
* RTC register addresses
*/
#define RTC_SEC_REG_ADDR 0x00
#define RTC_MIN_REG_ADDR 0x01
#define RTC_HR_REG_ADDR 0x02
#define RTC_DAY_REG_ADDR 0x03
#define RTC_DATE_REG_ADDR 0x04
#define RTC_MON_REG_ADDR 0x05
#define RTC_YR_REG_ADDR 0x06
#define RTC_CTL_REG_ADDR 0x07
#define RTC_SEC_BIT_CH 0x80 /* Clock Halt (in Register 0) */
#define RTC_CTL_BIT_RS0 0x01 /* Rate select 0 */
#define RTC_CTL_BIT_RS1 0x02 /* Rate select 1 */
#define RTC_CTL_BIT_SQWE 0x10 /* Square Wave Enable */
#define RTC_CTL_BIT_OUT 0x80 /* Output Control */
static uchar rtc_read (uchar reg);
static void rtc_write (uchar reg, uchar val);
static uchar bin2bcd (unsigned int n);
static unsigned bcd2bin (uchar c);
/*
* Get the current time from the RTC
*/
void rtc_get (struct rtc_time *tmp)
{
uchar sec, min, hour, mday, wday, mon, year;
sec = rtc_read (RTC_SEC_REG_ADDR);
min = rtc_read (RTC_MIN_REG_ADDR);
hour = rtc_read (RTC_HR_REG_ADDR);
wday = rtc_read (RTC_DAY_REG_ADDR);
mday = rtc_read (RTC_DATE_REG_ADDR);
mon = rtc_read (RTC_MON_REG_ADDR);
year = rtc_read (RTC_YR_REG_ADDR);
DEBUGR ("Get RTC year: %02x mon: %02x mday: %02x wday: %02x "
"hr: %02x min: %02x sec: %02x\n",
year, mon, mday, wday, hour, min, sec);
if (sec & RTC_SEC_BIT_CH) {
printf ("### Warning: RTC oscillator has stopped\n");
/* clear the CH flag */
rtc_write (RTC_SEC_REG_ADDR,
rtc_read (RTC_SEC_REG_ADDR) & ~RTC_SEC_BIT_CH);
}
tmp->tm_sec = bcd2bin (sec & 0x7F);
tmp->tm_min = bcd2bin (min & 0x7F);
tmp->tm_hour = bcd2bin (hour & 0x3F);
tmp->tm_mday = bcd2bin (mday & 0x3F);
tmp->tm_mon = bcd2bin (mon & 0x1F);
tmp->tm_year = bcd2bin (year) + ( bcd2bin (year) >= 70 ? 1900 : 2000);
tmp->tm_wday = bcd2bin ((wday - 1) & 0x07);
tmp->tm_yday = 0;
tmp->tm_isdst= 0;
DEBUGR ("Get DATE: %4d-%02d-%02d (wday=%d) TIME: %2d:%02d:%02d\n",
tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_wday,
tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
}
/*
* Set the RTC
*/
void rtc_set (struct rtc_time *tmp)
{
DEBUGR ("Set DATE: %4d-%02d-%02d (wday=%d) TIME: %2d:%02d:%02d\n",
tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_wday,
tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
if (tmp->tm_year < 1970 || tmp->tm_year > 2069)
printf("WARNING: year should be between 1970 and 2069!\n");
rtc_write (RTC_YR_REG_ADDR, bin2bcd (tmp->tm_year % 100));
rtc_write (RTC_MON_REG_ADDR, bin2bcd (tmp->tm_mon));
rtc_write (RTC_DAY_REG_ADDR, bin2bcd (tmp->tm_wday + 1));
rtc_write (RTC_DATE_REG_ADDR, bin2bcd (tmp->tm_mday));
rtc_write (RTC_HR_REG_ADDR, bin2bcd (tmp->tm_hour));
rtc_write (RTC_MIN_REG_ADDR, bin2bcd (tmp->tm_min));
rtc_write (RTC_SEC_REG_ADDR, bin2bcd (tmp->tm_sec));
}
/*
* Reset the RTC. We setting the date back to 1970-01-01.
* We also enable the oscillator output on the SQW/OUT pin and program
* it for 32,768 Hz output. Note that according to the datasheet, turning
* on the square wave output increases the current drain on the backup
* battery to something between 480nA and 800nA.
*/
void rtc_reset (void)
{
struct rtc_time tmp;
rtc_write (RTC_SEC_REG_ADDR, 0x00); /* clearing Clock Halt */
rtc_write (RTC_CTL_REG_ADDR, RTC_CTL_BIT_SQWE | RTC_CTL_BIT_RS1 | RTC_CTL_BIT_RS0);
tmp.tm_year = 1970;
tmp.tm_mon = 1;
tmp.tm_mday= 1;
tmp.tm_hour = 0;
tmp.tm_min = 0;
tmp.tm_sec = 0;
rtc_set(&tmp);
printf ( "RTC: %4d-%02d-%02d %2d:%02d:%02d UTC\n",
tmp.tm_year, tmp.tm_mon, tmp.tm_mday,
tmp.tm_hour, tmp.tm_min, tmp.tm_sec);
return;
}
/*
* Helper functions
*/
static
uchar rtc_read (uchar reg)
{
return (i2c_reg_read (CFG_I2C_RTC_ADDR, reg));
}
static void rtc_write (uchar reg, uchar val)
{
i2c_reg_write (CFG_I2C_RTC_ADDR, reg, val);
}
static unsigned bcd2bin (uchar n)
{
return ((((n >> 4) & 0x0F) * 10) + (n & 0x0F));
}
static unsigned char bin2bcd (unsigned int n)
{
return (((n / 10) << 4) | (n % 10));
}
#endif /* (CONFIG_RTC_DS1307 || CONFIG_RTC_DS1338) && (CFG_COMMANDS & CFG_CMD_DATE) */ |
import { Button, Container, Grid, Heading, Image, Input, Select, VStack } from '@chakra-ui/react'
import React, { useState } from 'react'
import Sidebar from '../Sidebar'
import cursor from '../../../assets/images/cursor2.png'
import { fileUploadCss } from '../../Auth/Register'
const CreateCourse = () => {
const [title,setTitle] = useState('');
const [description,setDescription] = useState('');
const [createdBy,setCreatedBy] = useState('');
const [category,setCategory] = useState('');
const [image,setImage] = useState('');
const [imagePrev,setImagePrev] = useState('');
const changeImageHandler = (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
setImagePrev(reader.result);
setImage(file);
}
}
const categories = [
"Web Development","Artificial Intelligence","Data Science",
"BlockChain Development","Flutter Development",
"React Native","Game Development"
]
return (
<Grid css={{cursor:`url(${cursor}), default`}} minH={'100vh'} templateColumns={['1fr','5fr 1fr']}>
<Container py='16'>
<form>
<Heading textTransform={'uppercase'} children='Create Course' my='16' textAlign={['center','left']} />
<VStack m='auto' spacing={'8'} >
<Input value={title} onChange={(e)=>setTitle(e.target.value)} placeholder='Title' type={'text'} focusBorderColor='purple.300' />
<Input value={description} onChange={(e)=>setDescription(e.target.value)} placeholder='Description' type={'text'} focusBorderColor='purple.300' />
<Input value={createdBy} onChange={(e)=>setCreatedBy(e.target.value)} placeholder='Creator Name' type={'text'} focusBorderColor='purple.300' />
<Select focusBorderColor='purple.300' value={category} onChange={(e)=>setCategory(e.target.value)} >
<option value=''>
Category
</option>
{categories.map((item)=>(
<option key={item} value={item}>{item}</option>
))}
</Select>
<Input accept='image/*' required type={'file'} focusBorderColor='purple.300' css={{'&::file-selector-button':{...fileUploadCss,color:"purple"}}} onChange={changeImageHandler} />
{imagePrev && (
<Image src={imagePrev} boxSize='64' objectFit={'contain'} />
)}
<Button width={'full'} colorScheme={'purple'}>
Create
</Button>
</VStack>
</form>
</Container>
<Sidebar />
</Grid>
)
}
export default CreateCourse |
import type { Collection, Document as MongoDBDocument } from "mongodb";
import { VectorStore } from "./base.js";
import { Embeddings } from "../embeddings/base.js";
import { Document } from "../document.js";
export type MongoDBAtlasVectorSearchLibArgs = {
collection: Collection<MongoDBDocument>;
indexName?: string;
textKey?: string;
embeddingKey?: string;
};
export class MongoDBAtlasVectorSearch extends VectorStore {
declare FilterType: MongoDBDocument;
collection: Collection<MongoDBDocument>;
indexName: string;
textKey: string;
embeddingKey: string;
constructor(embeddings: Embeddings, args: MongoDBAtlasVectorSearchLibArgs) {
super(embeddings, args);
this.collection = args.collection;
this.indexName = args.indexName || "default";
this.textKey = args.textKey || "text";
this.embeddingKey = args.embeddingKey || "embedding";
}
async addVectors(vectors: number[][], documents: Document[]): Promise<void> {
const docs = vectors.map((embedding, idx) => ({
[this.textKey]: documents[idx].pageContent,
[this.embeddingKey]: embedding,
...documents[idx].metadata,
}));
await this.collection.insertMany(docs);
}
async addDocuments(documents: Document[]): Promise<void> {
const texts = documents.map(({ pageContent }) => pageContent);
return this.addVectors(
await this.embeddings.embedDocuments(texts),
documents
);
}
async similaritySearchVectorWithScore(
query: number[],
k: number,
preFilter?: MongoDBDocument,
postFilterPipeline?: MongoDBDocument[]
): Promise<[Document, number][]> {
const knnBeta: MongoDBDocument = {
vector: query,
path: this.embeddingKey,
k,
};
if (preFilter) {
knnBeta.filter = preFilter;
}
const pipeline: MongoDBDocument[] = [
{
$search: {
index: this.indexName,
knnBeta,
},
},
{
$project: {
[this.embeddingKey]: 0,
score: { $meta: "searchScore" },
},
},
];
if (postFilterPipeline) {
pipeline.push(...postFilterPipeline);
}
const results = this.collection.aggregate(pipeline);
const ret: [Document, number][] = [];
for await (const result of results) {
const text = result[this.textKey];
delete result[this.textKey];
const { score, ...metadata } = result;
ret.push([new Document({ pageContent: text, metadata }), score]);
}
return ret;
}
async similaritySearch(
query: string,
k: number,
preFilter?: MongoDBDocument,
postFilterPipeline?: MongoDBDocument[]
): Promise<Document[]> {
const results = await this.similaritySearchVectorWithScore(
await this.embeddings.embedQuery(query),
k,
preFilter,
postFilterPipeline
);
return results.map((result) => result[0]);
}
static async fromTexts(
texts: string[],
metadatas: object[] | object,
embeddings: Embeddings,
dbConfig: MongoDBAtlasVectorSearchLibArgs
): Promise<MongoDBAtlasVectorSearch> {
const docs: Document[] = [];
for (let i = 0; i < texts.length; i += 1) {
const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;
const newDoc = new Document({
pageContent: texts[i],
metadata,
});
docs.push(newDoc);
}
return MongoDBAtlasVectorSearch.fromDocuments(docs, embeddings, dbConfig);
}
static async fromDocuments(
docs: Document[],
embeddings: Embeddings,
dbConfig: MongoDBAtlasVectorSearchLibArgs
): Promise<MongoDBAtlasVectorSearch> {
const instance = new this(embeddings, dbConfig);
await instance.addDocuments(docs);
return instance;
}
} |
#' Numeric app inputs
#'
#' @param df a `data.frame` or `tibble`
#'
#' @return a named character vector of integer and double column names
#' @export pull_numeric_cols
#'
#' @importFrom purrr compact list_c set_names
#'
#' @examples
#' require(palmerpenguins)
#' require(dplyr)
#' pull_numeric_cols(palmerpenguins::penguins)
#' pull_numeric_cols(dplyr::starwars)
pull_numeric_cols <- function(df) {
bins <- pull_binary_cols(df = df)
facets <- pull_facet_cols(df = df)
# assemble
all_bins_facets_list <- list(bins, facets)
# reduce
bins_facets_list <- purrr::compact(all_bins_facets_list)
# vector
bins_facets <- purrr::list_c(bins_facets_list)
# vector of doubles
dbls <- get_column_class(df = df, class = "dbl", return_tbl = FALSE)
# vector of integers
ints <- get_column_class(df = df, class = "int", return_tbl = FALSE)
# assemble
all_dbls_ints_list <- list(dbls, ints)
# # reduce
dbls_ints_list <- purrr::compact(all_dbls_ints_list)
# # vector
dbls_ints <- purrr::list_c(dbls_ints_list)
# reduce
nums_nms <- dbls_ints[dbls_ints %nin% bins_facets]
if (is.null(nums_nms)) {
return(nums_nms)
} else {
# name
nums <- purrr::set_names(nums_nms)
return(nums)
}
} |
class Annotator.Plugin.Document extends Annotator.Plugin
$ = Annotator.$
events:
'beforeAnnotationCreated': 'beforeAnnotationCreated'
pluginInit: ->
this.getDocumentMetadata()
# returns the primary URI for the document being annotated
uri: =>
uri = decodeURIComponent document.location.href
for link in @metadata
if link.rel == "canonical"
uri = link.href
return uri
# returns all uris for the document being annotated
uris: =>
uniqueUrls = {}
for link in @metadata.link
uniqueUrls[link.href] = true if link.href
return (href for href of uniqueUrls)
beforeAnnotationCreated: (annotation) =>
annotation.document = @metadata
getDocumentMetadata: =>
@metadata = {}
# first look for some common metadata types
# TODO: look for microdata/rdfa?
this._getScholar()
this._getDublinCore()
this._getOpenGraph()
this._getFavicon()
# extract out/normalize some things
this._getTitle()
this._getLinks()
return @metadata
_getScholar: =>
@metadata.scholar = {}
for meta in $("meta")
name = $(meta).prop("name")
content = $(meta).prop("content")
if name.match(/^citation_/)
if @metadata.scholar[name]
@metadata.scholar[name].push(content)
else
@metadata.scholar[name] = [content]
_getDublinCore: =>
@metadata.dc = {}
for meta in $("meta")
name = $(meta).prop("name")
content = $(meta).prop("content")
nameParts = name.split(".")
if nameParts.length == 2 and nameParts[0].toLowerCase() == "dc"
n = nameParts[1]
if @metadata.dc[n]
@metadata.dc[n].push(content)
else
@metadata.dc[n] = [content]
_getOpenGraph: =>
@metadata.og = {}
for meta in $("meta")
property = $(meta).attr("property")
content = $(meta).prop("content")
if property
match = property.match(/^og:(.+)$/)
if match
n = match[1]
if @metadata.og[n]
@metadata.og[n].push(content)
else
@metadata.og[n] = [content]
_getTitle: =>
if @metadata.scholar.citation_title
@metadata.title = @metadata.scholar.citation_title[0]
else if @metadata.dc.title
@metadata.title = @metadata.dc.title
else
@metadata.title = $("head title").text()
_getLinks: =>
# we know our current location is a link for the document
@metadata.link = [href: document.location.href]
# look for some relevant link relations
for link in $("link")
l = $(link)
href = this._absoluteUrl(l.prop('href')) # get absolute url
rel = l.prop('rel')
type = l.prop('type')
if rel in ["alternate", "canonical", "bookmark"] and type not in ["application/rss+xml", "application/atom+xml"]
@metadata.link.push(href: href, rel: rel, type: type)
# look for links in scholar metadata
for name, values of @metadata.scholar
if name == "citation_pdf_url"
for url in values
@metadata.link.push
href: this._absoluteUrl(url)
type: "application/pdf"
# kind of a hack to express DOI identifiers as links but it's a
# convenient place to look them up later, and somewhat sane since
# they don't have a type
if name == "citation_doi"
for doi in values
if doi[0..3] != "doi:"
doi = "doi:" + doi
@metadata.link.push(href: doi)
# look for links in dublincore data
for name, values of @metadata.dc
if name == "identifier"
for id in values
if id[0..3] == "doi:"
@metadata.link.push(href: id)
_getFavicon: =>
for link in $("link")
if $(link).prop("rel") in ["shortcut icon", "icon"]
@metadata["favicon"] = this._absoluteUrl(link.href)
# hack to get a absolute url from a possibly relative one
_absoluteUrl: (url) ->
img = $("<img src='#{ url }'>")
url = img.prop('src')
img.prop('src', null)
return url |
import os
import cv2
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
from utilities import get_root_path
import numpy as np
# templ: bool showing if it is template
def get_file_data_cleaned(fp, templ, only_angles=True):
MLid = int(os.path.basename(fp)[2:6])
FPS = 30
if MLid > 272:
FPS = 60
if templ:
df = pd.read_csv(fp).iloc[:, 8:]
x = df.to_numpy()
if not templ and only_angles:
x = np.loadtxt(fp)
x = x[:, 0:3]
cos_x = np.cos(x)
# down-sample to 30 fps if necessary
# if FPS == 60:
# downsample_ratio = 2
# x = temporal_rescale(x, downsample_ratio)
return x
class HeadPoseParser:
def __init__(self, vid_folder, pose_folder, templ=False, pose_ext=".angles"):
self.pose_ext = pose_ext
self.pose_dir = os.path.join(get_root_path("data"), pose_folder)
for fname in os.listdir(self.pose_dir):
if '.avi.' in fname:
fpath_old = os.path.join(self.pose_dir, fname)
fpath_new = os.path.join(self.pose_dir, fname.replace(".avi", ""))
os.rename(fpath_old, fpath_new)
self.video_dir = os.path.join(get_root_path("data"), vid_folder)
self.head_pose_plot_dir = os.path.join(get_root_path("outputs"), "head_pose_plots")
if not os.path.exists(self.head_pose_plot_dir):
os.mkdir(self.head_pose_plot_dir)
self.__signal_ls, self.__vid_ids = self.get_signals(templ)
@property
def signal_ls(self):
return self.__signal_ls
@property
def vid_ids(self):
return self.__vid_ids
def get_signals(self, templ, only_angles=True):
signal_ls = []
vid_ids = []
for hp_fname in os.listdir(self.pose_dir):
hp_fpath = os.path.join(self.pose_dir, hp_fname)
basename = os.path.basename(hp_fpath)
vid_id = os.path.splitext(basename)[0] # get basename without extension
for vid_name in os.listdir(self.video_dir):
if vid_id in vid_name:
v_fpath = os.path.join(self.video_dir, vid_name)
video_cap = cv2.VideoCapture(v_fpath)
# video_fps = int(video_cap.get(cv2.CAP_PROP_FPS))
vid_length = int(video_cap.get(cv2.CAP_PROP_FRAME_COUNT))
break
assert os.path.isfile(hp_fpath) and hp_fpath.endswith(self.pose_ext), f"{hp_fpath} is not a file or not " \
f"the correct format {self.pose_ext}."
print(f"Head Pose File: {hp_fpath}")
# get the angle data and frame differential
signals = get_file_data_cleaned(hp_fpath, templ, only_angles=only_angles)
assert vid_length == signals.shape[0], "The video frame number does not match the head signal data length."
signal_ls.append(signals)
vid_ids.append(vid_id)
return signal_ls, vid_ids
def plot_signals(self, signal_ls, vid_ids):
for i, signals_ind in enumerate(signal_ls):
# color theme
sns.set_theme(style="whitegrid")
color_palette = sns.color_palette('hls', 3)
# define subplot grid
fig, axs = plt.subplots(nrows=3, ncols=1, figsize=(25, 12))
plt.subplots_adjust(hspace=0.5)
fig.suptitle("Head Angle Poses", fontsize=18, y=0.95)
x = np.arange(0, signals_ind.shape[0], dtype=int)
j = 0
for column, ax in zip(signals_ind.T, axs.ravel()):
sns.lineplot(x=x, y=column, ax=ax, color=color_palette[j % 3])
j += 1
fig.show()
full_path = os.path.join(self.head_pose_plot_dir, f'{vid_ids[i]}.png')
fig.savefig(full_path, format='png')
print(f"Saved plot of most important features to '{full_path}'.")
print("") |
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable, ModelConfig;
/**
* Increment OFF
* @var bool
*/
public $incrementing = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'id', 'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* ユーザーのメモ
* 1対多
* @return HasMany
*/
public function memos()
{
return $this->hasMany(Memo::class, 'user_id', 'id');
}
} |
---
id: 61fd719788899952e67692b9
title: Schritt 9
challengeType: 0
dashedName: step-9
---
# --description--
Das `thead`- und `tbody`-Element werden verwendet, um anzugeben, welcher Teil deiner Tabelle der Header ist und welcher Teil die Primärdaten oder den Inhalt enthält.
Füge ein `thead` und `tbody` zu deinem ersten `table` unter dem `caption`-Element hinzu.
# --hints--
Dein erstes `table`-Element sollte ein `thead`-Element enthalten.
```js
assert(document.querySelectorAll('table')?.[0]?.querySelector('thead'));
```
Dein erstes `table`-Element sollte ein `tbody`-Element enthalten.
```js
assert(document.querySelectorAll('table')?.[0]?.querySelector('tbody'));
```
Dein `thead`-Element sollte sich direkt unter deinem `caption`-Element befinden.
```js
assert(document.querySelector('caption')?.nextElementSibling?.localName === 'thead');
```
Dein `tbody`-Element sollte sich direkt unter deinem `thead`-Element befinden.
```js
assert(document.querySelector('thead')?.nextElementSibling?.localName === 'tbody');
```
# --seed--
## --seed-contents--
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Balance Sheet</title>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<main>
<section>
<h1>
<span class="flex">
<span>AcmeWidgetCorp</span>
<span>Balance Sheet</span>
</span>
</h1>
<div id="years" aria-hidden="true">
<span class="year">2019</span>
<span class="year">2020</span>
<span class="year">2021</span>
</div>
<div class="table-wrap">
--fcc-editable-region--
<table>
<caption>Assets</caption>
</table>
--fcc-editable-region--
<table>
</table>
<table>
</table>
</div>
</section>
</main>
</body>
</html>
```
```css
``` |
// SPDX-License-Identifier: LGPL-3.0-only
/* solhint-disable one-contract-per-file */
pragma solidity >=0.7.0 <0.9.0;
import {SafeStorage} from "../libraries/SafeStorage.sol";
import {Guard} from "../base/GuardManager.sol";
import {ISafe} from "../interfaces/ISafe.sol";
/**
* @title Migration Contract for Safe Upgrade
* @notice This contract facilitates the migration of a Safe contract from version 1.3.0/1.4.1 to 1.5.0.
* @dev IMPORTANT: The library is intended to be used with the Safe standard proxy that stores the singleton address
* at the storage slot 0. Use at your own risk with custom proxy implementations. The library will block calls
* if the address stored at the storage slot 0 is not a contract.
*/
contract Safe150Migration is SafeStorage {
// Address of Safe contract version 1.5.0 Singleton (L1)
// TODO: Update this address when the Safe 1.5.0 Singleton is deployed
address public constant SAFE_150_SINGLETON = address(0x88627c8904eCd9DF96A572Ef32A7ff13b199Ed8D);
// Address of Safe contract version 1.5.0 Singleton (L2)
// TODO: Update this address when the Safe 1.5.0 Singleton (L2) is deployed
address public constant SAFE_150_SINGLETON_L2 = address(0x0Ee37514644683f7EB9745a5726C722DeBa77e52);
// Address of Safe contract version 1.5.0 Compatibility Fallback Handler
// TODO: Update this address when the Safe 1.5.0 Compatibility Fallback Handler is deployed
address public constant SAFE_150_FALLBACK_HANDLER = address(0x8aa755cB169991fEDC3E306751dCb71964A041c7);
// the slot is defined as "keccak256("guard_manager.guard.address")" in the GuardManager contract
// reference: https://github.com/safe-global/safe-smart-account/blob/8ffae95faa815acf86ec8b50021ebe9f96abde10/contracts/base/GuardManager.sol#L76-L77
bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
/**
* @notice Constructor
* @dev Initializes the migrationSingleton with the contract's own address.
*/
constructor() {
require(isContract(SAFE_150_SINGLETON), "Safe 1.4.1 Singleton is not deployed");
require(isContract(SAFE_150_SINGLETON_L2), "Safe 1.4.1 Singleton (L2) is not deployed");
require(isContract(SAFE_150_FALLBACK_HANDLER), "Safe 1.4.1 Fallback Handler is not deployed");
}
/**
* @notice Event indicating a change of master copy address.
* @param singleton New master copy address
*/
event ChangedMasterCopy(address singleton);
/**
* @dev Private function to check if a guard is supported.
*/
function checkGuard() private view {
address guard = getGuard();
if (guard != address(0)) {
require(Guard(guard).supportsInterface(type(Guard).interfaceId), "GS300");
}
}
function checkCurrentSingleton() internal view {
require(isContract(singleton), "Trying to migrate an invalid Safe");
}
modifier validSingletonOnly() {
checkCurrentSingleton();
_;
}
/**
* @notice Migrate to Safe 1.5.0 Singleton (L1) at `SAFE_150_SINGLETON`
* @dev This function should only be called via a delegatecall to perform the upgrade.
*/
function migrateSingleton() public validSingletonOnly {
checkGuard();
singleton = SAFE_150_SINGLETON;
emit ChangedMasterCopy(singleton);
}
/**
* @notice Migrate and set the fallback handler to Safe 1.5.0 Compatibility Fallback Handler.
*/
function migrateWithFallbackHandler() public validSingletonOnly {
migrateSingleton();
ISafe(address(this)).setFallbackHandler(SAFE_150_FALLBACK_HANDLER);
}
/**
* @notice Migrate and set the guard to the specified address.
* @param guard The address of the new guard contract.
*/
function migrateWithSetGuard(address guard) public validSingletonOnly {
singleton = SAFE_150_SINGLETON;
emit ChangedMasterCopy(singleton);
ISafe(address(this)).setGuard(guard);
}
/**
* @notice Migrate, set the guard to the specified address, and set the fallback handler to Safe 1.5.0 Compatibility Fallback Handler.
* @param guard The address of the new guard contract.
*/
function migrateWithSetGuardAndFallbackHandler(address guard) public validSingletonOnly {
migrateWithSetGuard(guard);
ISafe(address(this)).setFallbackHandler(SAFE_150_FALLBACK_HANDLER);
}
/**
* @notice Migrate to Safe 1.5.0 Singleton (L2) at `SAFE_150_SINGLETON_L2`
* @dev This function should only be called via a delegatecall to perform the upgrade.
*/
function migrateL2Singleton() public validSingletonOnly {
checkGuard();
singleton = SAFE_150_SINGLETON_L2;
emit ChangedMasterCopy(singleton);
}
/**
* @notice Migrate to Safe 1.5.0 Singleton (L2) and set the fallback handler to Safe 1.5.0 Compatibility Fallback Handler.
*/
function migrateL2WithFallbackHandler() public validSingletonOnly {
migrateL2Singleton();
ISafe(address(this)).setFallbackHandler(SAFE_150_FALLBACK_HANDLER);
}
/**
* @notice Migrate to Safe 1.5.0 Singleton (L2) and set the guard to the specified address.
* @param guard The address of the new guard contract.
*/
function migrateL2WithSetGuard(address guard) public validSingletonOnly {
singleton = SAFE_150_SINGLETON_L2;
emit ChangedMasterCopy(singleton);
ISafe(address(this)).setGuard(guard);
}
/**
* @notice Migrate to Safe 1.5.0 Singleton (L2), set the guard to the specified address, and set the fallback handler to Safe 1.5.0 Compatibility Fallback Handler.
* @param guard The address of the new guard contract.
*/
function migrateL2WithSetGuardAndFallbackHandler(address guard) public validSingletonOnly {
migrateL2WithSetGuard(guard);
ISafe(address(this)).setFallbackHandler(SAFE_150_FALLBACK_HANDLER);
}
/**
* @notice Get the address of the current guard.
* @return guard The address of the current guard contract.
*/
function getGuard() internal view returns (address guard) {
bytes32 slot = GUARD_STORAGE_SLOT;
/* solhint-disable no-inline-assembly */
/// @solidity memory-safe-assembly
assembly {
guard := sload(slot)
}
/* solhint-enable no-inline-assembly */
}
/**
* @notice Checks whether an Ethereum address corresponds to a contract or an externally owned account (EOA).
* @param account The Ethereum address to be checked.
* @return A boolean value indicating whether the address is associated with a contract (true) or an EOA (false).
* @dev This function relies on the `extcodesize` assembly opcode to determine whether an address is a contract.
* It may return incorrect results in some edge cases (see documentation for details).
* Developers should use caution when relying on the results of this function for critical decision-making.
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
/* solhint-disable no-inline-assembly */
/// @solidity memory-safe-assembly
assembly {
size := extcodesize(account)
}
/* solhint-enable no-inline-assembly */
// If the code size is greater than 0, it is a contract; otherwise, it is an EOA.
return size > 0;
}
} |
###########################################################################
#
# Implements the Matrix class.
#
# @@@ Still needs lots of work @@@
=head1 Value::Matrix class
References:
MathObject Matrix methods: L<http://webwork.maa.org/wiki/Matrix_(MathObject_Class)>
MathObject Contexts: L<http://webwork.maa.org/wiki/Common_Contexts>
CPAN RealMatrix docs: L<http://search.cpan.org/~leto/Math-MatrixReal-2.09/lib/Math/MatrixReal.pm>
Allowing Matrices in Fractions:
L<http://webwork.maa.org/moodle/mod/forum/discuss.php?d=2978>
Context()->parens->set("[" => {formMatrix => 1});
Files interacting with Matrices:
L<lib/MatrixReal1.pm>
L<macros/MatrixReduce.pl>
L<lib/Matrix.pm>
L<macros/MatrixCheckers.pl> -- checking whether vectors form a basis
L<macros/MatrixReduce.pl> -- tools for row reduction via elementary matrices
L<macros/MatrixUnits.pl> -- Generates unimodular matrices with real entries
L<macros/PGmatrixmacros.pl>
L<macros/PGmorematrixmacros.pl>
L<macros/PGnumericalmacros.pl>
L<macros/tableau.pl>
L<macros/quickMatrixEntry.pl>
L<macros/LinearProgramming.pl>
Contexts
Matrix -- allows students to enter [[3,4],[3,6]]
-- formMatrix =>1 also allows this?
Complex-Matrix -- allows complex entries
Creation methods
$M1 = Matrix([1,2],[3,4]);
$M2 = Matrix([5,6],[7,8]);
$v = Vector(9,10);
$w = ColumnVector(9,10); # differs in how it is printed
Commands added in Value::matrix
Conversion
$matrix->values produces [[3,4,5],[1,3,4]] recursive array references of numbers (not MathObjects)
$matrix->wwMatrix produces CPAN MatrixReal1 matrix, used for computation subroutines
Information
$matrix->dimension: ARRAY
Access values
row : MathObjectMatrix
column : MathObjectMatrix
element : Real or Complex value
Assign values
these need to be added:
see C<change_matrix_entry()> in MatrixReduce and L<http://webwork.maa.org/moodle/mod/forum/discuss.php?d=2970>
Advanced
$matrix->data: ARRAY reference (internal data) of MathObjects (Real,Complex, Fractions)
stored at each location.
Passthrough methods covering subroutines in Matrix.pm which overrides or
augment CPAN's MatrixReal1.pm. Matrix is a specialized subclass of MatrixReal1.pm
The actual calculations for these methods are done in C<pg/lib/Matrix.pm>
trace
proj
proj_coeff
L
R
PL
PR
Passthrough methods covering subroutines in C<pg/lib/MatrixReal1.pm>
(this has been modified to handle complex numbers)
The actual calculations are done in C<MatrixReal1.pm> subroutines
The commands below are Value::Matrix B<methods> unless otherwise noted.
condition
det
inverse
is_symmetric
decompose_LR
dim
norm_one
norm_max
kleene
normalize
solve_LR($v) - LR decomposition
solve($M,$v) - function version of solve_LR
order_LR - order of LR decomposition matrix (number of non-zero equations)(also order() )
order($M) - function version of order_LR
solve_GSM
solve_SSM
solve_RM
=cut
#
package Value::Matrix;
my $pkg = 'Value::Matrix';
use strict; no strict "refs";
use Matrix; use Complex1;
our @ISA = qw(Value);
#
# Convert a value to a matrix. The value can be:
# a list of numbers or list of (nested) references to arrays of numbers,
# a point, vector or matrix object, a matrix-valued formula, or a string
# that evaluates to a matrix
#
sub new { #internal
my $self = shift; my $class = ref($self) || $self;
my $context = (Value::isContext($_[0]) ? shift : $self->context);
my $M = shift; $M = [] unless defined $M; $M = [$M,@_] if scalar(@_) > 0;
$M = @{$M}[0] if ref($M) =~ m/^Matrix(Real1)?/;
$M = Value::makeValue($M,context=>$context) if ref($M) ne 'ARRAY';
return bless {data => $M->data, context=>$context}, $class
if (Value::classMatch($M,'Point','Vector','Matrix') && scalar(@_) == 0);
return $M if Value::isFormula($M) && Value::classMatch($self,$M->type);
my @M = (ref($M) eq 'ARRAY' ? @{$M} : $M);
Value::Error("Matrices must have at least one entry") unless scalar(@M) > 0;
return $self->matrixMatrix($context,@M) if ref($M[0]) eq 'ARRAY' ||
Value::classMatch($M[0],'Matrix','Vector','Point') ||
(Value::isFormula($M[0]) && $M[0]->type =~ m/Matrix|Vector|Point/);
return $self->numberMatrix($context,@M);
}
#
# (Recursively) make a matrix from a list of array refs
# and report errors about the entry types
#
sub matrixMatrix { #internal
my $self = shift; my $class = ref($self) || $self;
my $context = shift;
my ($x,$m); my @M = (); my $isFormula = 0;
foreach $x (@_) {
if (Value::isFormula($x)) {push(@M,$x); $isFormula = 1} else {
$m = $self->new($context,$x); push(@M,$m);
$isFormula = 1 if Value::isFormula($m);
}
}
my ($type,$len) = ($M[0]->entryType->{name},$M[0]->length);
foreach $x (@M) {
Value::Error("Matrix rows must all be the same type")
unless (defined($x->entryType) && $type eq $x->entryType->{name});
Value::Error("Matrix rows must all be the same length") unless ($len eq $x->length);
}
return $self->formula([@M]) if $isFormula;
bless {data => [@M], context=>$context}, $class;
}
#
# Form a 1 x n matrix from a list of numbers
# (could become a row of an m x n matrix)
#
sub numberMatrix { #internal
my $self = shift; my $class = ref($self) || $self;
my $context = shift;
my @M = (); my $isFormula = 0;
foreach my $x (@_) {
$x = Value::makeValue($x,context=>$context);
Value::Error("Matrix row entries must be numbers: $x ") unless _isNumber($x);
push(@M,$x); $isFormula = 1 if Value::isFormula($x);
}
return $self->formula([@M]) if $isFormula;
bless {data => [@M], context=>$context}, $class;
}
#
# Recursively get the entries in the matrix and return
# an array of (references to arrays of ... ) numbers
#
sub value {
my $self = shift;
my $M = $self->data;
return @{$M} unless Value::classMatch($M->[0],'Matrix');
my @M = ();
foreach my $x (@{$M}) {push(@M,[$x->value])}
return @M;
}
#
# Recursively get the dimensions of the matrix.
# Returns (n) for a 1 x n, or (n,m) for an n x m, etc.
#
sub dimensions {
my $self = shift;
my $r = $self->length;
my $v = $self->data;
return ($r,) unless Value::classMatch($v->[0],'Matrix');
return ($r,$v->[0]->dimensions);
}
#
# Return the proper type for the matrix
#
sub typeRef {
my $self = shift;
return Value::Type($self->class, $self->length, $Value::Type{number})
unless Value::classMatch($self->data->[0],'Matrix');
return Value::Type($self->class, $self->length, $self->data->[0]->typeRef);
}
#
# True if the matrix is a square matrix
#
sub isSquare {
my $self = shift;
my @d = $self->dimensions;
return 0 if scalar(@d) > 2;
return 1 if scalar(@d) == 1 && $d[0] == 1;
return $d[0] == $d[1];
}
#
# True if the matrix is 1-dimensional (i.e., is a matrix row)
#
sub isRow {
my $self = shift;
my @d = $self->dimensions;
return scalar(@d) == 1;
}
#
# See if the matrix is an Identity matrix
#
sub isOne {
my $self = shift;
return 0 unless $self->isSquare;
my $i = 0;
foreach my $row (@{$self->{data}}) {
my $j = 0;
foreach my $k (@{$row->{data}}) {
return 0 unless $k eq (($i == $j)? "1": "0");
$j++;
}
$i++;
}
return 1;
}
#
# See if the matrix is all zeros
#
sub isZero {
my $self = shift;
foreach my $x (@{$self->{data}}) {return 0 unless $x->isZero}
return 1;
}
sub _isNumber {
my $n = shift;
return Value::isNumber($n) || Value::classMatch($n, 'Fraction');
}
#
# Make arbitrary data into a matrix, if possible
#
sub promote {
my $self = shift; my $class = ref($self) || $self;
my $context = (Value::isContext($_[0]) ? shift : $self->context);
my $x = (scalar(@_) ? shift : $self);
return $self->new($context,$x,@_) if scalar(@_) > 0 || ref($x) eq 'ARRAY';
$x = Value::makeValue($x,context=>$context);
return $x->inContext($context) if ref($x) eq $class;
return $self->make($context,@{$x->data}) if Value::classMatch($x,'Point','Vector');
Value::Error("Can't convert %s to %s",Value::showClass($x),Value::showClass($self));
}
#
# Don't inherit ColumnVector flag
#
sub noinherit {
my $self = shift;
return ("ColumnVector","wwM","lrM",$self->SUPER::noinherit);
}
############################################
#
# Operations on matrices
#
sub add {
my ($self,$l,$r,$other) = Value::checkOpOrderWithPromote(@_);
my @l = @{$l->data}; my @r = @{$r->data};
Value::Error("Can't add Matrices with different dimensions")
unless scalar(@l) == scalar(@r);
my @s = ();
foreach my $i (0..scalar(@l)-1) {push(@s,$l[$i] + $r[$i])}
return $self->inherit($other)->make(@s);
}
sub sub {
my ($self,$l,$r,$other) = Value::checkOpOrderWithPromote(@_);
my @l = @{$l->data}; my @r = @{$r->data};
Value::Error("Can't subtract Matrices with different dimensions")
unless scalar(@l) == scalar(@r);
my @s = ();
foreach my $i (0..scalar(@l)-1) {push(@s,$l[$i] - $r[$i])}
return $self->inherit($other)->make(@s);
}
sub mult {
my ($l,$r,$flag) = @_; my $self = $l; my $other = $r;
#
# Constant multiplication
#
if (_isNumber($r)) {
my @coords = ();
foreach my $x (@{$l->data}) {push(@coords,$x*$r)}
return $self->make(@coords);
}
#
# Make points and vectors into columns if they are on the right
#
if (!$flag && Value::classMatch($r,'Point','Vector'))
{$r = ($self->promote($r))->transpose} else {$r = $self->promote($r)}
#
if ($flag) {my $tmp = $l; $l = $r; $r = $tmp}
my @dl = $l->dimensions; my @dr = $r->dimensions;
if (scalar(@dl) == 1) {@dl = (1,@dl); $l = $self->make($l)}
if (scalar(@dr) == 1) {@dr = (@dr,1); $r = $self->make($r)->transpose}
Value::Error("Can only multiply 2-dimensional matrices") if scalar(@dl) > 2 || scalar(@dr) > 2;
Value::Error("Matrices of dimensions %dx%d and %dx%d can't be multiplied",@dl,@dr)
unless ($dl[1] == $dr[0]);
#
# Do matrix multiplication
#
my @l = $l->value; my @r = $r->value; my @M = ();
foreach my $i (0..$dl[0]-1) {
my @row = ();
foreach my $j (0..$dr[1]-1) {
my $s = 0;
foreach my $k (0..$dl[1]-1) {$s += $l[$i]->[$k] * $r[$k]->[$j]}
push(@row,$s);
}
push(@M,$self->make(@row));
}
$self = $self->inherit($other) if Value::isValue($other);
return $self->make(@M);
}
sub div {
my ($l,$r,$flag) = @_; my $self = $l;
Value::Error("Can't divide by a Matrix") if $flag;
Value::Error("Matrices can only be divided by Numbers") unless _isNumber($r);
Value::Error("Division by zero") if $r == 0;
my @coords = ();
foreach my $x (@{$l->data}) {push(@coords,$x/$r)}
return $self->make(@coords);
}
sub power {
my ($l,$r,$flag) = @_; my $self = shift; my $context = $self->context;
Value::Error("Can't use Matrices in exponents") if $flag;
Value::Error("Only square matrices can be raised to a power") unless $l->isSquare;
$r = Value::makeValue($r,context=>$context);
if (_isNumber($r) && $r =~ m/^-\d+$/) {
$l = $l->inverse; $r = -$r;
$self->Error("Matrix is not invertible") unless defined($l);
}
Value::Error("Matrix powers must be non-negative integers") unless _isNumber($r) && $r =~ m/^\d+$/;
return $context->Package("Matrix")->I($l->length,$context) if $r == 0;
my $M = $l; foreach my $i (2..$r) {$M = $M*$l}
return $M;
}
#
# Do lexicographic comparison (row by row)
#
sub compare {
my ($self,$l,$r) = Value::checkOpOrderWithPromote(@_);
Value::Error("Can't compare Matrices with different dimensions")
unless join(',',$l->dimensions) eq join(',',$r->dimensions);
my @l = @{$l->data}; my @r = @{$r->data};
foreach my $i (0..scalar(@l)-1) {
my $cmp = $l[$i] <=> $r[$i];
return $cmp if $cmp;
}
return 0;
}
sub neg {
my $self = promote(@_); my @coords = ();
foreach my $x (@{$self->data}) {push(@coords,-$x)}
return $self->make(@coords);
}
sub conj {shift->twiddle(@_)}
sub twiddle {
my $self = promote(@_); my @coords = ();
foreach my $x (@{$self->data}) {push(@coords,($x->can("conj") ? $x->conj : $x))}
return $self->make(@coords);
}
#
# Transpose an n x m matrix
#
sub transpose {
my $self = promote(@_);
my @d = $self->dimensions;
if (scalar(@d) == 1) {@d = (1,@d); $self = $self->make($self)}
Value::Error("Can't transpose %d-dimensional matrices",scalar(@d)) unless scalar(@d) == 2;
my @M = (); my $M = $self->data;
foreach my $j (0..$d[1]-1) {
my @row = ();
foreach my $i (0..$d[0]-1) {push(@row,$M->[$i]->data->[$j])}
push(@M,$self->make(@row));
}
return $self->make(@M);
}
#
# Get an identity matrix of the requested size
#
sub I {
my $self = shift; my $d = shift; my $context = shift || $self->context;
$d = ($self->dimensions)[0] if !defined $d && ref($self) && $self->isSquare;
Value::Error("You must provide a dimension for the Identity matrix") unless defined $d;
Value::Error("Dimension must be a positive integer") unless $d =~ m/^[1-9]\d*$/;
my @M = (); my @Z = split('',0 x $d);
my $REAL = $context->Package('Real');
foreach my $i (0..$d-1) {
my @row = @Z; $row[$i] = 1;
push(@M,$self->make($context, map {$REAL->new($_)} @row));
}
return $self->make($context,@M);
}
#
# Extract a given row from the matrix
#
sub row {
my $self = (ref($_[0]) ? $_[0] : shift);
my $M = $self->promote(shift); my $i = shift;
return if $i == 0; $i-- if $i > 0;
if ($M->isRow) {return if $i != 0 && $i != -1; return $M}
return $M->data->[$i];
}
#
# Extract a given column from the matrix
#
sub column {
my $self = (ref($_[0]) ? $_[0] : shift);
my $M = $self->promote(shift); my $j = shift;
return if $j == 0; $j-- if $j > 0;
my @d = $M->dimensions;
if (scalar(@d) == 1) {
return if $j+1 > $d[0] || $j < -$d[0];
return $M->data->[$j];
}
return if $j+1 > $d[1] || $j < -$d[1];
my @col = ();
foreach my $row (@{$M->data}) {push(@col,$self->make($row->data->[$j]))}
return $self->make(@col);
}
#
# Extract a given element from the matrix
#
sub element {
my $self = (ref($_[0]) ? $_[0] : shift);
my $M = $self->promote(shift);
return $M->extract(@_);
}
# @@@ assign @@@
# @@@ removeRow, removeColumn @@@
# @@@ Minor @@@
##################################################
#
# Convert MathObject Matrix to old-style Matrix
#
sub wwMatrix {
my $self = (ref($_[0]) ? $_[0] : shift);
my $M = $self->promote(shift); my $j = shift; my $wwM;
return $self->{wwM} if defined($self->{wwM});
my @d = $M->dimensions;
Value->Error("Matrix must be two-dimensional to convert to MatrixReal1") if scalar(@d) > 2;
if (scalar(@d) == 1) {
$wwM = new Matrix(1,$d[0]);
foreach my $j (0..$d[0]-1) {
$wwM->[0][0][$j] = $self->wwMatrixEntry($M->data->[$j]);
}
} else {
$wwM = new Matrix(@d);
foreach my $i (0..$d[0]-1) {
my $row = $M->data->[$i];
foreach my $j (0..$d[1]-1) {
$wwM->[0][$i][$j] = $self->wwMatrixEntry($row->data->[$j]);
}
}
}
$self->{wwM} = $wwM;
return $wwM;
}
sub wwMatrixEntry {
my $self = shift; my $x = shift;
return $x->value if $x->isReal;
return Complex1::cplx($x->Re->value,$x->Im->value) if $x->isComplex;
return $x;
}
sub wwMatrixLR {
my $self = shift;
return $self->{lrM} if defined($self->{lrM});
$self->wwMatrix;
$self->{lrM} = $self->{wwM}->decompose_LR;
return $self->{lrM};
}
sub wwColumnVector {
my $self = shift;
my $v = shift;
my $V = $self->new($v);
$V = $V->transpose if Value::classMatch($v,'Vector');
return $V->wwMatrix;
}
###################################
#
# From MatrixReal1.pm
#
sub det {
my $self = shift; $self->wwMatrixLR;
Value->Error("Can't take determinant of non-square matrix") unless $self->isSquare;
return Value::makeValue($self->{lrM}->det_LR);
}
sub inverse {
my $self = shift; $self->wwMatrixLR;
Value->Error("Can't take inverse of non-square matrix") unless $self->isSquare;
my $I = $self->{lrM}->invert_LR;
return (defined($I) ? $self->new($I) : $I);
}
sub decompose_LR {
my $self = (shift)->copy;
my $LR = $self->wwMatrixLR;
return $self->new($LR)->with(lrM => $LR);
}
sub dim {
my $self = shift;
return $self->wwMatrix->dim();
}
sub norm_one {
my $self = shift;
return Value::makeValue($self->wwMatrix->norm_one());
}
sub norm_max {
my $self = shift;
return Value::makeValue($self->wwMatrix->norm_max());
}
sub kleene {
my $self = shift;
return $self->new($self->wwMatrix->kleene());
}
sub normalize {
my $self = shift;
my $v = $self->wwColumnVector(shift);
my ($M,$b) = $self->wwMatrix->normalize($v);
return ($self->new($M),$self->new($b));
}
sub solve {shift->solve_LR(@_)}
sub solve_LR {
my $self = shift;
my $v = $self->wwColumnVector(shift);
my ($d,$b,$M) = $self->wwMatrixLR->solve_LR($v);
$b = $self->new($b) if defined($b);
$M = $self->new($M) if defined($M);
return ($d,$b,$M);
}
sub condition {
my $self = shift;
my $I = $self->new(shift)->wwMatrix;
return $self->new($self->wwMatrix->condition($I));
}
sub order {shift->order_LR(@_)}
sub order_LR { # order of LR decomposition matrix (number of non-zero equations)
my $self = shift;
return $self->wwMatrixLR->order_LR;
}
sub solve_GSM {
my $self = shift;
my $x0 = $self->wwColumnVector(shift);
my $b = $self->wwColumnVector(shift);
my $e = shift;
my $v = $self->wwMatrix->solve_GSM($x0,$b,$e);
$v = $self->new($v) if defined($v);
return $v;
}
sub solve_SSM {
my $self = shift;
my $x0 = $self->wwColumnVector(shift);
my $b = $self->wwColumnVector(shift);
my $e = shift;
my $v = $self->wwMatrix->solve_SSM($x0,$b,$e);
$v = $self->new($v) if defined($v);
return $v;
}
sub solve_RM {
my $self = shift;
my $x0 = $self->wwColumnVector(shift);
my $b = $self->wwColumnVector(shift);
my $w = shift; my $e = shift;
my $v = $self->wwMatrix->solve_RM($x0,$b,$w,$e);
$v = $self->new($v) if defined($v);
return $v;
}
sub is_symmetric {
my $self = shift;
return $self->wwMatrix->is_symmetric;
}
###################################
#
# From Matrix.pm
#
sub trace {
my $self = shift;
return Value::makeValue($self->wwMatrix->trace);
}
sub proj {
my $self = shift;
my $v = $self->new(shift)->wwMatrix;
return $self->new($self->wwMatrix->proj($v));
}
sub proj_coeff {
my $self = shift;
my $v = $self->new(shift)->wwMatrix;
return $self->new($self->wwMatrix->proj_coeff($v));
}
sub L {
my $self = shift;
return $self->new($self->wwMatrixLR->L);
}
sub R {
my $self = shift;
return $self->new($self->wwMatrixLR->R);
}
sub PL {
my $self = shift;
return $self->new($self->wwMatrixLR->PL);
}
sub PR {
my $self = shift;
return $self->new($self->wwMatrixLR->PR);
}
############################################
#
# Generate the various output formats
#
#
# Use array environment to lay out matrices
#
sub TeX {
my $self = shift; my $equation = shift;
my $def = ($equation->{context} || $self->context)->lists->get('Matrix');
my $open = shift || $self->{open} || $def->{open};
my $close = shift || $self->{close} || $def->{close};
$open =~ s/([{}])/\\$1/g; $close =~ s/([{}])/\\$1/g;
my $TeX = ''; my @entries = (); my $d;
if ($self->isRow) {
foreach my $x (@{$self->data}) {
if (Value::isValue($x)) {
$x->{format} = $self->{format} if defined $self->{format};
push(@entries,$x->TeX($equation));
} else {push(@entries,$x)}
}
$TeX .= join(' &',@entries) . "\n";
$d = scalar(@entries);
} else {
foreach my $row (@{$self->data}) {
foreach my $x (@{$row->data}) {
if (Value::isValue($x)) {
$x->{format} = $self->{format} if defined $self->{format};
push(@entries,$x->TeX($equation));
} else {push(@entries,$x)}
}
$TeX .= join(' &',@entries) . '\cr'."\n";
$d = scalar(@entries); @entries = ();
}
}
$TeX =~ s/\\cr\n$/\n/;
return '\left'.$open.'\begin{array}{'.('c'x$d).'}'."\n".$TeX.'\end{array}\right'.$close;
}
###########################################################################
1; |
'use client';
import {
Disclosure,
DisclosureButton,
DisclosurePanel,
} from '@headlessui/react';
import { Bars3Icon, CloudIcon, XMarkIcon } from '@heroicons/react/24/outline';
import { Link } from '../ui';
const navigation = [
{
name: 'Dashboard',
href: '/',
},
{
name: 'Acerca de',
href: '/about',
},
];
const Header = () => {
return (
<Disclosure
as='nav'
className='border-b border-gray-200 bg-white dark:bg-gray-800 dark:border-gray-700 dark:text-white fixed w-full z-10 top-0'
>
{({ open, close }) => (
<>
<div className='mx-auto max-w-7xl px-4 sm:px-6 lg:px-8'>
<div className='flex h-16 justify-between'>
<div className='flex'>
<div className='flex flex-shrink-0 items-center'>
<CloudIcon className='block h-9 w-9 text-black dark:text-white' />
</div>
<div className='hidden sm:-my-px sm:ml-6 sm:flex sm:space-x-8'>
{navigation.map((item) => (
<Link
key={item.name}
href={item.href}
className='border-transparent text-gray-500 hover:border-indigo-300 hover:text-gray-700 inline-flex items-center border-b-2 px-1 pt-1 text-sm font-medium dark:text-white dark:hover:text-gray-200 dark:hover:border-indigo-600'
activeClassName='border-indigo-500 text-gray-900 dark:text-white dark:border-indigo-500 dark:hover:text-gray-200 dark:hover:border-gray-200'
>
{item.name}
</Link>
))}
</div>
</div>
<div className='-mr-2 flex items-center sm:hidden'>
{/* Mobile menu button */}
<DisclosureButton
className='relative inline-flex items-center justify-center rounded-md bg-white p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-500 dark:bg-gray-800 dark:hover:bg-gray-700 '
aria-label={open ? 'Close main menu' : 'Open main menu'}
>
<span className='absolute -inset-0.5' />
<span className='sr-only'>Open main menu</span>
{open ? (
<XMarkIcon className='block h-6 w-6' aria-hidden='true' />
) : (
<Bars3Icon className='block h-6 w-6' aria-hidden='true' />
)}
</DisclosureButton>
</div>
</div>
</div>
<DisclosurePanel className='sm:hidden'>
<div className='space-y-1 pb-3 pt-2 flex flex-col'>
{navigation.map((item) => (
<Link
key={item.name}
onClick={() => close()}
href={item.href}
className='text-start border-transparent text-gray-600 hover:border-gray-300 hover:bg-gray-50 hover:text-gray-800 block border-l-4 py-2 pl-3 pr-4 text-base font-medium
dark:text-white dark:hover:text-gray-200 dark:hover:border-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700 dark:pl-4 dark:pr-5 dark:py-3 dark:text-lg'
activeClassName='border-indigo-500 text-gray-900 dark:text-white dark:border-indigo-500 dark:hover:text-gray-200 dark:hover:border-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700 dark:pl-4 dark:pr-5 dark:py-3 dark:text-lg'
>
{item.name}
</Link>
))}
</div>
</DisclosurePanel>
</>
)}
</Disclosure>
);
};
export default Header; |
# @param {Integer} column_number
# @return {String}
CHARS = ("A".."Z").to_a
def convert_to_title(column_number)
result = ""
quotient = column_number
until quotient.zero?
quotient, remainder = (quotient - 1).divmod(26)
result << CHARS[remainder]
end
result.reverse
end |
import random
def jogar_forca():
imprime_mensagem_abertura()
palavra_secreta = carregar_palavras_secretas()
letras_acertadas = inicializa_letras_acertadas(palavra_secreta)
print(letras_acertadas, "\n")
enforcou = False
acertou = False
erros = 0
# Enquanto não enforcou E não acertou
while(not enforcou and not acertou):
chute = pede_o_chute()
if(chute in palavra_secreta):
marca_chute_correto(chute, palavra_secreta, letras_acertadas)
else:
erros += 1 # Seria a mesma coisa que erros = erros + 1
print("Ops, você errou! Faltam {} tentativas.".format(7-erros))
desenhaforca(erros)
enforcou = erros == 7 # Quando o usuário atingir 6 erros, o loop parará já que ele terá enforcado.
acertou = "_" not in letras_acertadas # Acertou vai ser TRUE, quando não tiver mais "_" dentro das letras_acertadas.
print(letras_acertadas)
if(acertou):
imprime_mensagem_vitoria()
else:
imprime_mensagem_derrota(palavra_secreta)
# FUNÇÕES:
def imprime_mensagem_abertura():
print("***********************************************")
print("*** Olá mundo! Bem-vindo ao jogo de Forca!! ***")
print("***********************************************\n")
def carregar_palavras_secretas():
# Dentro do arquivo "palavras.txt" foram criadas todas as palvras e apartir disso, criamos uma lista conterá os elementos de cada linha do arquivo.
arquivo = open("palavras.txt", "r")
palavras = []
for linha in arquivo:
linha = linha.strip() # Tirando o \n
palavras.append(linha) # Cada linha está sendo adicionada dentro da lista como um elemento.
arquivo.close()
# Tornar a palavra aleatória.
numero = random.randrange(0, len(palavras))
palavra_secreta = palavras[numero].upper()
return palavra_secreta # Serve para a função retornar o valor da palavra_secreta
def inicializa_letras_acertadas(palavra_secreta):
return ["_" for letra in palavra_secreta] # Crie um "_" dentro da lista, para cada letra na palavra_secreta.
def pede_o_chute():
chute = input("Qual a letra? ")
chute = chute.strip().upper() # Para os espaçamentos no input não afetarem a entrada do chute & as letras ficarem maiúsculas.
return chute
def marca_chute_correto(chute, palavra_secreta, letras_acertadas):
index = 0 # Para mostrar a posição de cada letra da palavra.
for letra in palavra_secreta: # 'letra' vai destrinchar todas as letras da variável 'palavra_secreta'.
if (chute == letra.upper()): # .upper() é para deixar todas as letras maiúsculas.
letras_acertadas[index] = chute
index = index + 1 # Seria a mesma coisa que index += 1
def imprime_mensagem_vitoria():
print("Parabéns, você ganhou!")
print(" ___________ ")
print(" '._==_==_=_.' ")
print(" .-\: /-. ")
print(" | (|:. |) | ")
print(" '-|:. |-' ")
print(" \::. / ")
print(" '::. .' ")
print(" ) ( ")
print(" .' '._ ")
print(" '-------' ")
def imprime_mensagem_derrota(palavra_secreta):
print("Puxa, você foi enforcado!")
print("A palavra era {}".format(palavra_secreta))
print(" _______________ ")
print(" / \ ")
print(" / \ ")
print("// \/\ ")
print("\| XXXX XXXX | / ")
print(" | XXXX XXXX |/ ")
print(" | XXX XXX | ")
print(" | | ")
print(" \_ XXX __/ ")
print(" |\ XXX /| ")
print(" | | | | ")
print(" | I I I I I I I | ")
print(" | I I I I I I | ")
print(" \_ _/ ")
print(" \_ _/ ")
print(" \_______/ ")
def desenhaforca(erros):
print(" ______ ")
print(" |/ | ")
if(erros == 1):
print(" | (_) ")
print(" | ")
print(" | ")
if(erros == 2):
print(" | (_) ")
print(" | | ")
print(" | ")
if(erros == 3):
print(" | (_) ")
print(" | \| ")
print(" | ")
if(erros == 4):
print(" | (_) ")
print(" | \|/ ")
print(" | ")
if(erros == 5):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
if(erros == 6):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | / ")
if(erros == 7):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | / \ ")
print(" | ")
print("_|___ ")
print()
#Para rodar a forca sem precisar ir pelo arquivo do "jogos.py"
if(__name__ == "__main__"):
jogar_forca() |
import Head from "next/head";
import styles from '../../styles/Premium.module.css'
import {useState} from 'react'
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faTimesCircle, faCheckCircle} from "@fortawesome/free-solid-svg-icons";
import QuestionAnswer from "../../components/QuestionAnswer";
import Markdown from "../../components/Markdown";
import {serverSideTranslations} from "next-i18next/serverSideTranslations";
import {useTranslation} from "next-i18next";
const tierPrices = {
1: '4.99',
2: '9.99',
3: '14.99'
}
const tierUrls = {
1: 'https://www.patreon.com/join/merlinfuchs/checkout?rid=4409325',
2: 'https://www.patreon.com/join/merlinfuchs/checkout?rid=4837411',
3: 'https://www.patreon.com/join/merlinfuchs/checkout?rid=3820460'
}
export async function getStaticProps({locale}) {
return {
props: {
...(await serverSideTranslations(locale, ['common', 'premium'])),
},
};
}
export default function Premium() {
const {t} = useTranslation(['premium', 'common'])
const [selectedTier, setSelectedTier] = useState(2)
const faq = t('faq', {returnObjects: true})
return (
<div>
<Head>
<title>Premium | Xenon Bot</title>
</Head>
<div className={`bg-theme-darker pt-20 pb-72 -mb-48 text-center px-5 ${styles.header}`}>
<h3 className="text-7xl font-bold mb-4">Xenon Premium</h3>
<div className="text-2xl text-gray-300 mb-10">{t('catchLine')}</div>
<a href="/patreon" target="_blank"
className="inline-block bg-yellow-400 text-black transform hover:scale-105 transition-transform transition-300 px-5 py-2 rounded-md text-2xl">
{t('subscribeNow')}
</a>
</div>
<div className="grid justify-items-center mb-20">
<div className="w-full xl:w-304 px-3 md:px-5">
<div className="grid justify-items-center grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-10 xl:gap-16 mb-32 px-2">
<div className="bg-theme-dark rounded-md shadow-xl flex flex-col">
<div className="pt-5 pb-10 px-5 text-center flex-auto items-center">
<div className="text-3xl font-bold text-gray-200">Backup role assignments & nicknames</div>
</div>
<img src="/template-load.jpg" alt=""
className="flex-initial transform scale-105 xl:scale-110 rounded-md shadow-xl"/>
</div>
<div className="bg-theme-dark rounded-md shadow-xl flex flex-col">
<div className="pt-5 pb-10 px-5 text-center flex-auto items-center">
<div className="text-3xl font-bold text-gray-200">Backup messsages</div>
</div>
<img src="/template-load.jpg" alt=""
className="flex-initial transform scale-105 xl:scale-110 rounded-md shadow-xl"/>
</div>
<div className="bg-theme-dark rounded-md shadow-xl flex flex-col">
<div className="pt-5 pb-10 px-5 text-center flex-auto items-center">
<div className="text-3xl font-bold text-gray-200">Synchronize messages, bans and role assignments</div>
</div>
<img src="/template-load.jpg" alt=""
className="flex-initial transform scale-105 xl:scale-110 rounded-md shadow-xl"/>
</div>
</div>
<div className="flex flex-col lg:flex-row mb-36">
<div className="bg-theme-darker rounded-md flex flex-col flex-auto lg:mr-5 mb-5 lg:mb-0">
<div className="flex flex-initial flex-row flex-wrap justify-between">
<div
className={`flex relative items-center justify-center cursor-pointer flex-auto border-r-2 border-theme-lighter rounded-tl-md px-3 py-2 ${selectedTier === 0 ? 'bg-theme-light' : 'bg-theme-dark'}`}
onClick={() => setSelectedTier(0)}>
<div className="text-xl fond-bold">Free Tier</div>
</div>
<div
className={`flex relative items-center justify-center cursor-pointer flex-auto border-r-2 border-theme-lighter px-3 py-2 ${selectedTier === 1 ? 'bg-theme-light' : 'bg-theme-dark'}`}
onClick={() => setSelectedTier(1)}>
<div className="text-xl fond-bold">Premium 1</div>
</div>
<div
className={`flex relative items-center justify-center cursor-pointer flex-auto border-r-2 border-theme-lighter px-3 py-2 ${selectedTier === 2 ? 'bg-theme-light' : 'bg-theme-dark'}`}
onClick={() => setSelectedTier(2)}>
<div className="text-xl fond-bold">Premium 2</div>
</div>
<div
className={`flex relative items-center justify-center cursor-pointer flex-auto rounded-tr-md px-3 py-2 ${selectedTier === 3 ? 'bg-theme-light' : 'bg-theme-dark'}`}
onClick={() => setSelectedTier(3)}>
<div className="text-xl fond-bold">Premium 3</div>
</div>
</div>
<div className="flex-auto justify-evenly flex flex-col py-5 px-10 text-xl">
<div className="flex items-center">
<FontAwesomeIcon icon={faCheckCircle} className="text-green-500 mr-2 text-2xl"/>
<div className="text-gray-300">
<Markdown>{t('perks.backupBase')}</Markdown>
</div>
</div>
<div className="flex items-center">
<FontAwesomeIcon icon={faCheckCircle} className="text-green-500 mr-2 text-2xl"/>
<div className="text-gray-300">
<Markdown>
{t('perks.backupCount', {count: selectedTier === 0 ? '15' : (selectedTier === 1 ? '50' : (selectedTier === 2 ? '100' : '250'))})}
</Markdown>
</div>
</div>
<div className="flex items-center">
<FontAwesomeIcon icon={faCheckCircle} className="text-green-500 mr-2 text-2xl"/>
<div className="text-gray-300">
<Markdown>
{t('perks.backupAutomaticKeep', {count: selectedTier === 0 ? '1' : (selectedTier === 1 ? '2' : (selectedTier === 2 ? '4' : '8'))})}
</Markdown>
</div>
</div>
<div className="flex items-center">
{selectedTier > 0 ? (
<FontAwesomeIcon icon={faCheckCircle} className="text-green-500 mr-2 text-2xl"/>
) : (
<FontAwesomeIcon icon={faTimesCircle} className="text-red-500 mr-2 text-2xl"/>
)}
<div className="text-gray-300">
<Markdown>
{t('perks.backupPremium')}
</Markdown>
</div>
</div>
{selectedTier > 0 ? (
<div className="flex items-center">
< FontAwesomeIcon icon={faCheckCircle}
className="text-green-500 mr-2 text-2xl"/>
<div className="text-gray-300">
<Markdown>
{t('perks.backupMessageCount', {count: selectedTier === 1 ? '50' : (selectedTier === 2 ? '100' : '250')})}
</Markdown>
</div>
</div>
) : (
<div className="flex items-center">
<FontAwesomeIcon icon={faTimesCircle} className="text-red-500 mr-2 text-2xl"/>
<div className="text-gray-300">
<Markdown>{t('perks.backupMessages')}</Markdown>
</div>
</div>
)}
<div className="flex items-center mb-3">
{selectedTier > 0 ? (
<FontAwesomeIcon icon={faCheckCircle} className="text-green-500 mr-2 text-2xl"/>
) : (
<FontAwesomeIcon icon={faTimesCircle} className="text-red-500 mr-2 text-2xl"/>
)}
<div className="text-gray-300">
<Markdown>{t('perks.synchronize')}</Markdown>
</div>
</div>
</div>
</div>
<div className="flex-auto lg:flex-initial">
{selectedTier === 0 ? (
<div className="bg-theme-darker rounded-md px-5 py-10 text-center">
<div className="text-5xl mb-10 font-bold">Free Tier</div>
<div
className="text-8xl text-gray-300 mb-2 font-bold">$0.00
</div>
<div className="text-gray-300 text-xl mb-10">{t('perMonth')}</div>
<a href="/invite" target="_blank"
className="inline-block bg-blue-400 text-black transform hover:scale-105 transition-transform transition-300 px-3 py-2 rounded-md text-2xl">
{t('common:inviteNow')}
</a>
</div>
) : (
<div className="bg-theme-darker rounded-md px-5 py-10 text-center">
<div className="text-5xl mb-10 font-bold">Premium {selectedTier}</div>
<div
className="text-8xl text-blue-400 mb-2 font-bold">${tierPrices[selectedTier]}</div>
<div className="text-gray-300 text-xl mb-10">{t('perMonth')}</div>
<a href={tierUrls[selectedTier]} target="_blank" rel="noreferrer"
className="inline-block bg-yellow-400 text-black transform hover:scale-105 transition-transform transition-300 px-3 py-2 rounded-md text-2xl">
{t('subscribeNow')}
</a>
</div>
)}
</div>
</div>
<div className="mb-10">
<div className="text-4xl text-center mb-10 font-bold">{t('common:faqTitle')}</div>
{faq.map(({question, answer}, i) => (
<QuestionAnswer question={question} answer={answer} key={i}/>
))}
<div className="text-center mt-16">
<div className="text-xl text-gray-300 mb-5">
{t('common:faqFooter')}
</div>
<a href="/discord" target="_blank"
className="inline-block bg-blue-400 px-3 py-2 rounded-md text-lg text-black transform hover:scale-105 transition-transform transition-300">{t('common:joinDiscord')}</a>
</div>
</div>
</div>
</div>
</div>
)
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=0.8, width=device-width">
<!-- http://getbootstrap.com/docs/4.5/ -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link href="/static/styles.css" rel="stylesheet">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon2.ico') }}">
<!-- http://getbootstrap.com/docs/4.5/ -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<title>OffCovid: {% block title %}{% endblock %}</title>
{% block styles %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/16.0.4/css/intlTelInput.css">
{% endblock %}
</head>
<nav class="navbar navbar-expand-md navbar-light bg-light border">
<a class="navbar-brand" style="color:#0f538f;" href="/"><span class="blue"><h2>
<img src="https://icons.iconarchive.com/icons/igh0zt/ios7-style-metro-ui/256/MetroUI-Folder-OS-Security-icon.png" alt="Icon" width="48" height="48">OffCovid</h2></span></a>
<button aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbar" data-toggle="collapse" type="button">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbar">
<ul class="navbar-nav mr-auto mt-2">
<li class="nav-item menu_text"><a class="nav-link" href="/">Main Page</a></li>
<li class="nav-item menu_text"><a class="nav-link" href="/precautions">Precautions</a></li>
<li class="nav-item menu_text"><a class="nav-link" href="/lateral">Lateral Flow Test Information</a></li>
<li class="nav-item menu_text"><a class="nav-link" href="/pcr">PCR Tests</a></li>
<li class="nav-item menu_text"><a class="nav-link" href="/vaccination">Vaccination Clinics</a></li>
<li class="nav-item menu_text"><a class="nav-link" href="/help" style="color:#ac001a">
<img src=" https://cdn4.iconfinder.com/data/icons/Pretty_office_icon_part_2/256/help-desk.png" alt="Icon" width="32" height="32">
Need Help?</a></li>
</ul>
<script>
$(document).ready(function () {
$('ul.navbar-nav > li')
.click(function (e) {
$('ul.navbar-nav > li')
.removeClass('active');
$(this).addClass('active');
});
});
</script>
<ul class="navbar-nav ml-auto mt-2">
<li class="nav-item"><a class="nav-link" href="http://differenttimezone.pythonanywhere.com/">
<img src='https://www.countryflags.com/wp-content/uploads/united-kingdom-flag-png-large.png' width="46" alt="Edinburgh Napier University" border="0">
</a></li>
<li class="nav-item"><a class="nav-link" href="https://translate.google.com/translate?sl=en&tl=de&u=http://differenttimezone.pythonanywhere.com/">
<img src='https://www.countryflags.com/wp-content/uploads/germany-flag-png-large.png' width="46" alt="Edinburgh Napier University" border="0">
</a></li>
<li class="nav-item"><a class="nav-link" href="https://translate.google.com/translate?sl=en&tl=it&u=http://differenttimezone.pythonanywhere.com/">
<img src='https://www.countryflags.com/wp-content/uploads/italy-flag-png-large.png' width="46" alt="Edinburgh Napier University" border="0">
</a></li>
<li class="nav-item"><a class="nav-link" href="https://translate.google.com/translate?sl=en&tl=pt&u=http://differenttimezone.pythonanywhere.com/">
<img src='https://cdn.countryflags.com/thumbs/brazil/flag-400.png' width="46" alt="Edinburgh Napier University" border="0">
</a></li>
</ul>
</div>
</nav>
{% if get_flashed_messages() %}
<header>
<div class="alert alert-primary border text-center" role="alert">
{{ get_flashed_messages() | join(" ") }}
</div>
</header>
{% endif %}
<body>
<main class="container p-4">
{% block main %}{% endblock %}
</main>
</body>
<footer>
<center class="bg-light border">
<center>Powered by <img src='https://edinburgh.org/media/828094/Transparent_two-colour_positive_RGB_72dpi_logo.png' alt="Edinburgh Napier University" style="max-width:25%" border="0"></a>
<img src='https://ih1.redbubble.net/image.1333816393.8681/flat,128x,075,f-pad,128x128,f8f8f8.jpg' alt="NHS LOGO" style="max-width:15%" border="0"></a></center>
</center></footer>
{% block scripts %}
{% endblock %}
</html> |
.-
help for ^omninorm^ (Statalist distribution 26 Mar 2001)
.-
Omnibus Test for Univariate and Multivariate Normality
------------------------------------------------------
^omninorm^ varlist [^if^ exp] [^in^ range]
varlist may contain time-series operators; see help @varlist@.
Description
-----------
^omninorm^ performs an omnibus test for normality on one or several variables
proposed by Doornik and Hansen (1994), based on a test by Shenton and Bowman
(1977). In its small-sample form, the test statistic uses transformed skewness
and kurtosis measures to generate empirical moments that are much closer to
standard normal. The test may be readily applied to a set of variables, such
as the residuals from a multivariate regression. Doornik and Hansen conduct
simulations that illustrate that this test will generally have better size and
power than several proposed in the literature, including the multivariate
Shapiro-Wilk of Royston (1983). They find that their omnibus test "is both
simple, has coorect size and good power properties." (p.6)
Under the null hypothesis of normality of the specified k variables,
the test statistic is distributed Chi-squared with 2 k degrees of
freedom. An asymptotic form of the test is also provided; it is essentially
a multivariate equivalent of the Bowman and Shenton (1975) test, which those
authors consider "unsuitable except in very large samples." (p.2)
Users of Stata 9.0+ should use ^omninorm^.
Examples
--------
. ^use http://fmwww.bc.edu/ec-p/data/micro/iris,clear^
. ^omninorm7 set_sepl set_sepw set_petw ^
. ^omninorm7 set_sepl set_sepw set_petw set_petl ver_sepl ver_sepw^
Acknowledgements
----------------
The code for this routine draws heavily from Jurgen Doornik's implementation
of normtest.ox in the Ox programming language. Nick Cox' matmap is required
for this routine.
References
----------
Bowman, K.O. and Shenton, L.R. 1975. Omnibus test contours for departures from
normality based on root-b1 and b2. Biometrika, 62:243-250.
Doornik, Jurgen A. and Hansen, Henrik. 1994. An Omnibus Test for Univariate
and Multivariate Normality. Unpublished working paper, Nuffield College, Oxford
University. http://ideas.uqam.ca/ideas/data/Papers/wuknucowp9604.html
Royston, J.P. 1983. Some techniques for assessing multivariate normality based
on the Shapiro-Wilk W. Applied Statistics, 32, 121-133.
Shenton, L.R. and Bowman, K.O. 1977. A Bivariate Model for the Distribution
of root-b1 and b2. Journal of the American Statistical Association, 72:206-211.
Author
------
Christopher F Baum, Boston College, USA
baum@@bc.edu
Also see
--------
Manual: ^[R] sktest, swilk^
On-line: help for @sktest@, @swilk@ |
/**
* @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module ui/dropdown/dropdownpanelview
*/
import View from '../view';
import { logWarning } from '@ckeditor/ckeditor5-utils';
/**
* The dropdown panel view class.
*
* See {@link module:ui/dropdown/dropdownview~DropdownView} to learn about the common usage.
*
* @extends module:ui/view~View
*/
export default class DropdownPanelView extends View {
/**
* @inheritDoc
*/
constructor(locale) {
super(locale);
const bind = this.bindTemplate;
/**
* Controls whether the panel is visible.
*
* @observable
* @member {Boolean} #isVisible
*/
this.set('isVisible', false);
/**
* The position of the panel, relative to the parent.
*
* This property is reflected in the CSS class set to {@link #element} that controls
* the position of the panel.
*
* @observable
* @default 'se'
* @member {'s'|'se'|'sw'|'sme'|'smw'|'n'|'ne'|'nw'|'nme'|'nmw'} #position
*/
this.set('position', 'se');
/**
* Collection of the child views in this panel.
*
* A common child type is the {@link module:ui/list/listview~ListView} and {@link module:ui/toolbar/toolbarview~ToolbarView}.
* See {@link module:ui/dropdown/utils~addListToDropdown} and
* {@link module:ui/dropdown/utils~addToolbarToDropdown} to learn more about child views of dropdowns.
*
* @readonly
* @member {module:ui/viewcollection~ViewCollection}
*/
this.children = this.createCollection();
this.setTemplate({
tag: 'div',
attributes: {
class: [
'ck',
'ck-reset',
'ck-dropdown__panel',
bind.to('position', value => `ck-dropdown__panel_${value}`),
bind.if('isVisible', 'ck-dropdown__panel-visible')
]
},
children: this.children,
on: {
// Drag and drop in the panel should not break the selection in the editor.
// https://github.com/ckeditor/ckeditor5-ui/issues/228
selectstart: bind.to(evt => evt.preventDefault())
}
});
}
/**
* Focuses the first view in the {@link #children} collection.
*
* See also {@link module:ui/dropdown/dropdownpanelfocusable~DropdownPanelFocusable}.
*/
focus() {
if (this.children.length) {
const firstChild = this.children.first;
if (typeof firstChild.focus === 'function') {
firstChild.focus();
}
else {
/**
* The child view of a dropdown could not be focused because it is missing the `focus()` method.
*
* This warning appears when a dropdown {@link module:ui/dropdown/dropdownview~DropdownView#isOpen gets open} and it
* attempts to focus the {@link module:ui/dropdown/dropdownpanelview~DropdownPanelView#children first child} of its panel
* but the child does not implement the
* {@link module:ui/dropdown/dropdownpanelfocusable~DropdownPanelFocusable focusable interface}.
*
* Focusing the content of a dropdown on open greatly improves the accessibility. Please make sure the view instance
* provides the `focus()` method for the best user experience.
*
* @error ui-dropdown-panel-focus-child-missing-focus
* @param {module:ui/view~View} childView
* @param {module:ui/dropdown/dropdownpanelview~DropdownPanelView} dropdownPanel
*/
logWarning('ui-dropdown-panel-focus-child-missing-focus', { childView: this.children.first, dropdownPanel: this });
}
}
}
/**
* Focuses the view element or last item in view collection on opening dropdown's panel.
*
* See also {@link module:ui/dropdown/dropdownpanelfocusable~DropdownPanelFocusable}.
*/
focusLast() {
if (this.children.length) {
const lastChild = this.children.last;
if (typeof lastChild.focusLast === 'function') {
lastChild.focusLast();
}
else {
lastChild.focus();
}
}
}
} |
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "arolla/expr/operators/casting_registry.h"
#include <cstdint>
#include <memory>
#include <optional>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "arolla/expr/derived_qtype_cast_operator.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_debug_string.h"
#include "arolla/expr/expr_node.h"
#include "arolla/expr/registered_expr_operator.h"
#include "arolla/qtype/array_like/array_like_qtype.h"
#include "arolla/qtype/base_types.h"
#include "arolla/qtype/optional_qtype.h"
#include "arolla/qtype/qtype.h"
#include "arolla/qtype/qtype_traits.h"
#include "arolla/qtype/standard_type_properties/common_qtype.h"
#include "arolla/qtype/standard_type_properties/properties.h"
#include "arolla/qtype/weak_qtype.h"
#include "arolla/util/indestructible.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::expr_operators {
using ::arolla::expr::CallOp;
using ::arolla::expr::ExprNodePtr;
using ::arolla::expr::RegisteredOperator;
CastingRegistry* CastingRegistry::GetInstance() {
static Indestructible<CastingRegistry> instance(
[](auto* self) { new (self) CastingRegistry; });
return instance.get();
}
// TODO: Add a test making sure that our casting logic is the same
// as numpy "safe" casting.
// We are intentionally prohibiting implicit casting from integer to floating
// point values.
CastingRegistry::CastingRegistry() {
cast_to_ops_ = {
{GetQType<bool>(), std::make_shared<RegisteredOperator>("core.to_bool")},
{GetQType<int32_t>(),
std::make_shared<RegisteredOperator>("core.to_int32")},
{GetQType<int64_t>(),
std::make_shared<RegisteredOperator>("core.to_int64")},
{GetQType<float>(),
std::make_shared<RegisteredOperator>("core.to_float32")},
{GetQType<double>(),
std::make_shared<RegisteredOperator>("core.to_float64")},
{GetWeakFloatQType(),
std::make_shared<RegisteredOperator>("core._to_weak_float")},
{GetQType<uint64_t>(),
std::make_shared<RegisteredOperator>("core.to_uint64")},
};
}
absl::StatusOr<ExprNodePtr> CastingRegistry::GetCast(
ExprNodePtr node, QTypePtr to_qtype, bool implicit_only,
std::optional<ExprNodePtr> shape_for_broadcasting) const {
const QType* from_qtype = node->qtype();
if (from_qtype == nullptr) {
return absl::FailedPreconditionError(absl::StrFormat(
"cannot cast expression %s with unknown QType", GetDebugSnippet(node)));
}
if (from_qtype == to_qtype) {
return node;
}
if (implicit_only &&
!CanCastImplicitly(
from_qtype, to_qtype,
/*enable_broadcasting=*/shape_for_broadcasting.has_value())) {
return absl::InvalidArgumentError(
absl::StrFormat("implicit casting from %s to %s is not allowed",
from_qtype->name(), to_qtype->name()));
}
// Step 1: make scalar types compatible.
ASSIGN_OR_RETURN(auto from_scalar_qtype, GetScalarQType(from_qtype));
ASSIGN_OR_RETURN(auto to_scalar_qtype, GetScalarQType(to_qtype));
if (from_scalar_qtype == GetWeakFloatQType() &&
from_scalar_qtype != to_scalar_qtype) {
const auto upcast_op =
std::make_shared<expr::DerivedQTypeUpcastOperator>(node->qtype());
ASSIGN_OR_RETURN(node, CallOp(upcast_op, {node}));
from_scalar_qtype = GetQType<double>();
}
if (from_scalar_qtype != to_scalar_qtype) {
if (!cast_to_ops_.contains(to_scalar_qtype)) {
return absl::InvalidArgumentError(
absl::StrFormat("unable to find a cast from %s to %s",
from_qtype->name(), to_qtype->name()));
}
ASSIGN_OR_RETURN(node, CallOp(cast_to_ops_.at(to_scalar_qtype), {node}));
if (node->qtype() == to_qtype) {
return node;
}
}
// Step 2: Make array-ness compatible.
if (!IsArrayLikeQType(node->qtype()) && IsArrayLikeQType(to_qtype)) {
if (!shape_for_broadcasting.has_value()) {
return absl::InvalidArgumentError(
absl::StrFormat("unable to cast non-array type %s into an array type "
"%s without shape for broadcasting provided",
from_qtype->name(), to_qtype->name()));
}
ASSIGN_OR_RETURN(
node, CallOp("core.const_with_shape", {*shape_for_broadcasting, node}));
if (node->qtype() == to_qtype) {
return node;
}
}
// Step 3: Make optional-ness compatible.
if (!IsOptionalQType(node->qtype()) && IsOptionalQType(to_qtype)) {
ASSIGN_OR_RETURN(node, CallOp("core.to_optional", {node}));
}
if (node->qtype() == to_qtype) {
return node;
} else {
return absl::InvalidArgumentError(
absl::StrFormat("unable to find a cast from %s to %s",
from_qtype->name(), to_qtype->name()));
}
}
absl::StatusOr<QTypePtr> CastingRegistry::CommonType(
absl::Span<const QTypePtr> arg_types, bool enable_broadcasting) const {
if (arg_types.empty()) {
return absl::InvalidArgumentError(
"empty arg_types list passed to CommonType");
}
const QType* result_qtype = CommonQType(arg_types, enable_broadcasting);
if (result_qtype == nullptr) {
if (enable_broadcasting || !CommonType(arg_types, true).ok()) {
return absl::InvalidArgumentError(
absl::StrCat("no common QType for ", FormatTypeVector(arg_types)));
} else {
return absl::InvalidArgumentError(
absl::StrCat("no common QType without broadcasting for ",
FormatTypeVector(arg_types)));
}
}
return result_qtype;
}
} // namespace arolla::expr_operators |
/************************************************************************
* File name : Tutorial.cpp
* Project name : APEX
* Author Primary author : Wonju cho
* Secondary author : Junseok Yang
* Others : Haewon Shon, Jookyung Lee
*
* Functions for Tutorial Level
* All content © 2019 DigiPen (USA) Corporation, all rights reserved.
*************************************************************************/
#include "Tutorial.h"
#include "CommonLevel.h"
#include "Utils.h"
void TutorialLevel::Initialize()
{
m_backgroundColor.r = 255, m_backgroundColor.g = 255,
m_backgroundColor.b = 255;
camera.position.Set(0.f, 0.f, 150.f);
m_useBuiltInPhysics = false;
mainFont = TTF_OpenFont("font/JaykopDot.ttf", 256);
b2Vec2 gravity(0.f, -40.f);
SetCustomPhysicsWorld(gravity);
Create_UI();
CreateCommonUI();
GeneratePlatform(300.f, 0.f, 2500.f, 30.f, 0);
GeneratePlatform(300.f, -150.f, 2500.f, 30.f, 1);
player1.CreatePlayerObject(&player2, { -100.f, 350.f }, m_game->p1Character, 1);
player2.CreatePlayerObject(&player1, { 100.f, 350.f }, m_game->p2Character, 2);
player1.AllocateBody(GetCustomPhysicsWorld());
AddObject(&player1.GetObject());
AddCustomPhysicsComponent(&player1.GetObject());
player2.AllocateBody(GetCustomPhysicsWorld());
AddObject(&player2.GetObject());
AddCustomPhysicsComponent(&player2.GetObject());
trap.SetName("trap");
trap.sound.LoadSound("sound/put_trap.wav");
tutorialBeeb.SetName("tutorialBeeb");
tutorialBeeb.sound.LoadSound("sound/menu_move.wav");
tutorialSound.SetName("tutorialSound");
tutorialSound.sound.LoadSound("sound/tutorial.wav");
tutorialSound.sound.Play();
hitsound.sound.LoadSound("sound/hit_sound.wav");
playTime = 0.f;
}
void TutorialLevel::Update(float dt)
{
/* pause */
if (m_input->IsTriggered(SDL_SCANCODE_ESCAPE))
{
m_game->Pause();
}
/* CHEAT : SKIP TUTORIAL */
if (m_input->IsTriggered(SDL_SCANCODE_BACKSPACE))
{
m_game->Change(LV_ModeSelect);
}
/* Player move control */
player1.PlayerMovement(dt);
player2.PlayerMovement(dt);
player1.SetPlayerMovingAndStatus(dt);
player2.SetPlayerMovingAndStatus(dt);
player1.SetCollisionMoving();
player2.SetCollisionMoving();
CheckRespawn();
/* Character's animation & effect */
player1.AnimationUpdate(dt);
player2.AnimationUpdate(dt);
AttackEffect(player1, dt);
AttackEffect(player2, dt);
CheckTrapCollision();
CheckSetTrap();
TrapCooldownAnimation(dt);
Print();
playTime += dt;
UpdateCustomPhysics(dt);
Render(dt);
}
void TutorialLevel::Close()
{
/* Reset Infos */
tutorial_p1 = 0, tutorial_p2 = 0;
w_moveCheck = 0, a_moveCheck = 0, s_moveCheck = 0, d_moveCheck = 0,
right_moveCheck = 0, left_moveCheck = 0, up_moveCheck = 0, down_moveCheck = 0,
p1_attackCheck = 0, p2_attackCheck = 0,
p1_trapCheck = 0, p2_trapCheck = 0,
pauseCheck = 0;
RemoveObject(&key_h);
RemoveObject(&key_j);
RemoveObject(&hitsound);
RemoveObject(&numpad2);
RemoveObject(&numpad3);
RemoveObject(&p1_movekey);
RemoveObject(&p2_movekey);
RemoveObject(&move_text);
RemoveObject(&attack_text);
RemoveObject(&trap_text);
RemoveObject(&next_text);
RemoveObject(&shoes_explain);
RemoveObject(&strong_explain);
RemoveObject(&superarmor_explain);
RemoveObject(&shoes);
RemoveObject(&strong);
RemoveObject(&superarmor);
RemoveObject(&p1);
RemoveObject(&p2);
RemoveObject(&p1_trapImage);
RemoveObject(&p2_trapImage);
RemoveObject(&p1_trapcooldown_ui);
RemoveObject(&p2_trapcooldown_ui);
RemoveObject(&p1_respawnText);
RemoveObject(&p2_respawnText);
RemoveObject(&p1_score_1);
RemoveObject(&p1_score_2);
RemoveObject(&p2_score_1);
RemoveObject(&p2_score_2);
tutorialSound.sound.Free();
tutorialBeeb.sound.Free();
trap.sound.Free();
RemoveObject(&tutorialBeeb);
RemoveObject(&tutorialSound);
RemoveObject(&trap);
player1.effect.sprite.Free();
RemoveObject(&player1.effect);
player2.effect.sprite.Free();
RemoveObject(&player2.effect);
/* Remove "custom" objects */
RemoveCustomPhysicsWorld();
// Wrap up state
ClearBaseState();
}
void TutorialLevel::GeneratePlatform(float posX, float posY, float sizeX, float sizeY, int platformNumber)
{
platform[platformNumber].SetName("platform");
platform[platformNumber].transform.position.Set(posX, posY, 0.f);
platform[platformNumber].transform.SetScale(sizeX, sizeY);
// Set the rotation of the object
platform[platformNumber].transform.rotation = 0;
platform[platformNumber].sprite.color = SDL_Color{ 255, 255, 255, 255 };
platform[platformNumber].sprite.LoadImage("texture/platform_image/long_platformer.png", m_renderer);
platform[platformNumber].customPhysics.pOwnerTransform = &platform[platformNumber].transform;
platform[platformNumber].customPhysics.bodyType = CustomPhysics::STATIC;
platform[platformNumber].customPhysics.AllocateBody(GetCustomPhysicsWorld());
AddObject(&platform[platformNumber]);
AddCustomPhysicsComponent(&platform[platformNumber]);
}
/*
* Basic Functions
*/
void TutorialLevel::SelectText(Object *textObject, const char *textContents, const char *id, SDL_Color color)
{
// Set the object's name
textObject->SetName(id);
// Set the scale of the object
textObject->transform.SetScale(550, 50);
// Set the text to render out
textObject->text.SetText(State::m_renderer, textContents, mainFont);
// Set the colors r,g,b,a (0~255)
textObject->text.color = color;
// Set either if the object to be hud or not
textObject->text.isHud = true;
// Register the object to the state
AddObject(textObject);
}
void TutorialLevel::Create_UI()
{
move_text.transform.position.Set(0.f, 300.f, 1.f);
SelectText(&move_text, "Press movement key.", "up_w", { 0,0,0,255 });
if (w_moveCheck + up_moveCheck == 2)
{
RemoveObject(&move_text);
}
p1_movekey.sprite.Free();
p1_movekey.SetName("p1_key_explain");
p1_movekey.transform.position.Set(-600.f, 150.f, 0.f);
p1_movekey.transform.SetScale(210, 140.f);
p1_movekey.transform.rotation = 0;
p1_movekey.sprite.color = SDL_Color{ 255,255,255,255 };
p1_movekey.sprite.LoadImage("texture/UI/keyboard/wasd_keyboard.png", m_renderer);
AddObject(&p1_movekey);
p2_movekey.sprite.Free();
p2_movekey.SetName("p2_key_explain");
p2_movekey.transform.position.Set(150.f, 150.f, 0.f);
p2_movekey.transform.SetScale(210.f, 140.f);
p2_movekey.transform.rotation = 0;
p2_movekey.sprite.color = SDL_Color{ 255,255,255,255 };
p2_movekey.sprite.LoadImage("texture/UI/keyboard/keyboard.png", m_renderer);
AddObject(&p2_movekey);
shoes_explain.transform.position.Set(-450.f, -300.f, 1.f);
SelectText(&shoes_explain, "This item makes player faster", "fast", { 0,0,0,255 });
shoes_explain.transform.SetScale(300.f, 50.f);
shoes.transform.position.Set(-650.f, -270.f, 0.f);
shoes.transform.SetScale(100.f, 150.f);
shoes.sprite.LoadImage("texture/items/Shoes.png", State::m_renderer);
AddObject(&shoes);
strong_explain.transform.position.Set(-100.f, -300.f, 1.f);
SelectText(&strong_explain, "This item makes player more stronger", "fast", { 0,0,0,255 });
strong_explain.transform.SetScale(300.f, 50.f);
strong.transform.position.Set(-150.f, -270.f, 0.f);
strong.transform.SetScale(100.f, 150.f);
strong.sprite.LoadImage("texture/items/strong.png", State::m_renderer);
AddObject(&strong);
superarmor_explain.transform.position.Set(250.f, -300.f, 1.f);
SelectText(&superarmor_explain, "This item makes player faster", "fast", { 0,0,0,255 });
superarmor_explain.transform.SetScale(300.f, 50.f);
superarmor.transform.position.Set(350.f, -270.f, 0.f);
superarmor.transform.SetScale(100.f, 150.f);
superarmor.sprite.LoadImage("texture/items/superarmor.png", State::m_renderer);
AddObject(&superarmor);
}
void TutorialLevel::Print()
{
if(m_input->IsTriggered(SDL_SCANCODE_W))
{
tutorialBeeb.sound.Play();
p1_movekey.sprite.Free();
p1_movekey.sprite.LoadImage("texture/UI/keyboard/w_pressed.png", m_renderer);
}
else if (m_input->IsReleased(SDL_SCANCODE_W))
{
w_moveCheck = 1;
p1_movekey.sprite.Free();
p1_movekey.sprite.LoadImage("texture/UI/keyboard/wasd_keyboard.png", m_renderer);
}
if (m_input->IsTriggered(SDL_SCANCODE_A))
{
tutorialBeeb.sound.Play();
p1_movekey.sprite.Free();
p1_movekey.sprite.LoadImage("texture/UI/keyboard/a_pressed.png", m_renderer);
}
else if (m_input->IsReleased(SDL_SCANCODE_A))
{
a_moveCheck = 1;
p1_movekey.sprite.Free();
p1_movekey.sprite.LoadImage("texture/UI/keyboard/wasd_keyboard.png", m_renderer);
}
if (m_input->IsTriggered(SDL_SCANCODE_S))
{
tutorialBeeb.sound.Play();
p1_movekey.sprite.Free();
p1_movekey.sprite.LoadImage("texture/UI/keyboard/s_pressed.png", m_renderer);
}
else if (m_input->IsReleased(SDL_SCANCODE_S))
{
s_moveCheck = 1;
p1_movekey.sprite.Free();
p1_movekey.sprite.LoadImage("texture/UI/keyboard/wasd_keyboard.png", m_renderer);
}
if (m_input->IsTriggered(SDL_SCANCODE_D))
{
tutorialBeeb.sound.Play();
p1_movekey.sprite.Free();
p1_movekey.sprite.LoadImage("texture/UI/keyboard/d_pressed.png", m_renderer);
}
else if (m_input->IsReleased(SDL_SCANCODE_D))
{
d_moveCheck = 1;
p1_movekey.sprite.Free();
p1_movekey.sprite.LoadImage("texture/UI/keyboard/wasd_keyboard.png", m_renderer);
}
if (m_input->IsTriggered(SDL_SCANCODE_UP))
{
tutorialBeeb.sound.Play();
p2_movekey.sprite.Free();
p2_movekey.sprite.LoadImage("texture/UI/keyboard/up_pressed.png", m_renderer);
}
else if (m_input->IsReleased(SDL_SCANCODE_UP))
{
up_moveCheck = 1;
p2_movekey.sprite.Free();
p2_movekey.sprite.LoadImage("texture/UI/keyboard/keyboard.png", m_renderer);
}
if (m_input->IsTriggered(SDL_SCANCODE_LEFT))
{
tutorialBeeb.sound.Play();
p2_movekey.sprite.Free();
p2_movekey.sprite.LoadImage("texture/UI/keyboard/left_pressed.png", m_renderer);
}
else if (m_input->IsReleased(SDL_SCANCODE_LEFT))
{
left_moveCheck = 1;
p2_movekey.sprite.Free();
p2_movekey.sprite.LoadImage("texture/UI/keyboard/keyboard.png", m_renderer);
}
if (m_input->IsTriggered(SDL_SCANCODE_DOWN))
{
tutorialBeeb.sound.Play();
p2_movekey.sprite.Free();
p2_movekey.sprite.LoadImage("texture/UI/keyboard/down_pressed.png", m_renderer);
}
else if (m_input->IsReleased(SDL_SCANCODE_DOWN))
{
down_moveCheck = 1;
p2_movekey.sprite.Free();
p2_movekey.sprite.LoadImage("texture/UI/keyboard/keyboard.png", m_renderer);
}
if (m_input->IsTriggered(SDL_SCANCODE_RIGHT))
{
tutorialBeeb.sound.Play();
p2_movekey.sprite.Free();
p2_movekey.sprite.LoadImage("texture/UI/keyboard/right_pressed.png", m_renderer);
}
else if (m_input->IsReleased(SDL_SCANCODE_RIGHT))
{
right_moveCheck = 1;
p2_movekey.sprite.Free();
p2_movekey.sprite.LoadImage("texture/UI/keyboard/keyboard.png", m_renderer);
}
if (w_moveCheck + a_moveCheck + s_moveCheck + d_moveCheck == 4
&& up_moveCheck + left_moveCheck + down_moveCheck + right_moveCheck == 4)
{
RemoveObject(&move_text);
if (attack_text.text.GetTexture() == nullptr)
{
attack_text.transform.position.Set(0.f, 300.f, 1.f);
SelectText(&attack_text, "Press attack key.", "h", { 0,0,0,255 });
}
if (key_h.sprite.GetTexture() == nullptr)
{
key_h.transform.position.Set(-390.f, 150.f, 0.f);
key_h.transform.SetScale(70.f, 70.f);
key_h.sprite.LoadImage("texture/UI/keyboard/key_h.png", State::m_renderer);
AddObject(&key_h);
}
if (m_input->IsTriggered(SDL_SCANCODE_H))
{
tutorialBeeb.sound.Play();
key_h.sprite.Free();
key_h.sprite.LoadImage("texture/UI/keyboard/h_pressed.png", m_renderer);
}
else if (m_input->IsReleased(SDL_SCANCODE_H))
{
p1_attackCheck = 1;
key_h.sprite.Free();
key_h.sprite.LoadImage("texture/UI/keyboard/key_h.png", m_renderer);
}
if (numpad2.sprite.GetTexture() == nullptr)
{
numpad2.transform.position.Set(360, 150.f, 0.f);
numpad2.transform.SetScale(70.f, 70.f);
numpad2.sprite.LoadImage("texture/UI/keyboard/numpad2.png", m_renderer);
AddObject(&numpad2);
}
if (m_input->IsTriggered(SDL_SCANCODE_KP_2))
{
tutorialBeeb.sound.Play();
numpad2.sprite.Free();
numpad2.sprite.LoadImage("texture/UI/keyboard/2_pressed.png", m_renderer);
}
else if (m_input->IsReleased(SDL_SCANCODE_KP_2))
{
p2_attackCheck = 1;
numpad2.sprite.Free();
numpad2.sprite.LoadImage("texture/UI/keyboard/numpad2.png", m_renderer);
}
}
if (p1_attackCheck == 1 && p2_attackCheck == 1)
{
RemoveObject(&attack_text);
if (trap_text.text.GetTexture() == nullptr)
{
trap_text.transform.position.Set(0.f, 300.f, 1.f);
SelectText(&trap_text, "Press trap key.", "j", { 0,0,0,255 });
}
if (key_j.sprite.GetTexture() == nullptr)
{
key_j.transform.position.Set(-310, 150.f, 0.f);
key_j.transform.SetScale(70.f, 70.f);
key_j.sprite.LoadImage("texture/UI/keyboard/key_j.png", State::m_renderer);
AddObject(&key_j);
}
if (m_input->IsTriggered(SDL_SCANCODE_J))
{
tutorialBeeb.sound.Play();
key_j.sprite.Free();
key_j.sprite.LoadImage("texture/UI/keyboard/j_pressed.png", m_renderer);
}
else if (m_input->IsReleased(SDL_SCANCODE_J))
{
p1_trapCheck = 1;
key_j.sprite.Free();
key_j.sprite.LoadImage("texture/UI/keyboard/key_j.png", m_renderer);
}
if (numpad3.sprite.GetTexture() == nullptr)
{
numpad3.transform.position.Set(440.f, 150.f, 0.f);
numpad3.transform.SetScale(70.f, 70.f);
numpad3.sprite.LoadImage("texture/UI/keyboard/numpad3.png", State::m_renderer);
AddObject(&numpad3);
}
if (m_input->IsTriggered(SDL_SCANCODE_KP_3))
{
tutorialBeeb.sound.Play();
numpad3.sprite.Free();
numpad3.sprite.LoadImage("texture/UI/keyboard/3_pressed.png", State::m_renderer);
}
else if (m_input->IsReleased(SDL_SCANCODE_KP_3))
{
p2_trapCheck = 1;
numpad3.sprite.Free();
numpad3.sprite.LoadImage("texture/UI/keyboard/numpad3.png", m_renderer);
}
}
if (p1_trapCheck == 1 && p2_trapCheck == 1)
{
RemoveObject(&trap_text);
if (next_text.text.GetTexture() == nullptr)
{
next_text.transform.position.Set(0.f, 300.f, 1.f);
SelectText(&next_text, "Press space to continue", "next", { 0, 0, 0, 255 });
}
if (m_input->IsTriggered(SDL_SCANCODE_SPACE))
{
m_game->Change(LV_ModeSelect);
}
if (m_input->IsTriggered(SDL_SCANCODE_RETURN))
{
m_game->Change(LV_ModeSelect);
}
}
}
/*
* Item Functions
*/
void TutorialLevel::CheckSetTrap()
{
if (State::m_input->IsTriggered(SDL_SCANCODE_J))
{
tutorialBeeb.sound.Play();
if (player1.trapCoolDown < 0.f && player1.GetObject().customPhysics.GetVelocity().y == 0)
{
if (player1.trap.customPhysics.GetBody() != nullptr)
{
player1.trap.RemoveCustomPhysicsComponent();
RemoveObject(&player1.trap);
}
player1.trapCoolDown = 5.f;
player1.trap.SetName("p1 Trap");
player1.trap.transform.position.Set(player1.GetObject().transform.position.x, player1.GetObject().transform.position.y - 40.f, 0.f);
player1.trap.transform.SetScale(50.f, 20.f);
player1.trap.sprite.color = SDL_Color{ 255, 0, 0, 255 };
player1.trap.sprite.LoadImage("texture/items/trap.png", m_renderer);
player1.trap.customPhysics.pOwnerTransform = &player1.trap.transform;
player1.trap.customPhysics.bodyType = CustomPhysics::STATIC;
player1.trap.customPhysics.AllocateBody(GetCustomPhysicsWorld());
player1.trap.customPhysics.ActiveGhostCollision(false);
AddObject(&player1.trap);
AddCustomPhysicsComponent(&player1.trap);
}
}
if (State::m_input->IsTriggered(SDL_SCANCODE_KP_3) && player2.GetObject().customPhysics.GetVelocity().y == 0)
{
tutorialBeeb.sound.Play();
if (player2.trapCoolDown < 0.f)
{
if (player2.trap.customPhysics.GetBody() != nullptr)
{
player2.trap.RemoveCustomPhysicsComponent();
RemoveObject(&player2.trap);
}
player2.trapCoolDown = 5.f;
player2.trap.SetName("p2 Trap");
player2.trap.transform.position.Set(player2.GetObject().transform.position.x, player2.GetObject().transform.position.y - 40.f, 0.f);
player2.trap.transform.SetScale(50.f, 20.f);
player2.trap.sprite.color = SDL_Color{ 0, 0, 255, 255 };
player2.trap.sprite.LoadImage("texture/items/trap.png", m_renderer);
player2.trap.customPhysics.pOwnerTransform = &player2.trap.transform;
player2.trap.customPhysics.bodyType = CustomPhysics::STATIC;
player2.trap.customPhysics.AllocateBody(GetCustomPhysicsWorld());
player2.trap.customPhysics.ActiveGhostCollision(false);
AddObject(&player2.trap);
AddCustomPhysicsComponent(&player2.trap);
}
}
}
void TutorialLevel::CheckTrapCollision()
{
if (player2.GetObject().customPhysics.IsCollidingWith(&player1.trap))
{
if (player2.GetDirection() == Player::Direction::RIGHT)
{
trap.sound.Play();
player2.GetObject().customPhysics.SetVelocity(-100.f, 40.f);
player2.SetKnockBackDelay(0.4f);
}
else
{
trap.sound.Play();
player2.GetObject().customPhysics.SetVelocity(100.f, 40.f);
player2.SetKnockBackDelay(0.4f);
}
player1.trap.RemoveCustomPhysicsComponent();
RemoveObject(&player1.trap);
}
if (player1.GetObject().customPhysics.IsCollidingWith(&player2.trap))
{
if (player2.GetDirection() == Player::Direction::LEFT)
{
trap.sound.Play();
player1.GetObject().customPhysics.SetVelocity(100.f, 40.f);
player1.SetKnockBackDelay(0.4f);
}
else
{
trap.sound.Play();
player1.GetObject().customPhysics.SetVelocity(100.f, 40.f);
player1.SetKnockBackDelay(0.4f);
}
player2.trap.RemoveCustomPhysicsComponent();
RemoveObject(&player2.trap);
}
}
/*
* Effects
*/
void TutorialLevel::AttackEffect(Player& player, float dt)
{
if (player.isAttack == true && player.effectLifeTime < 0.f)
{
hitsound.sound.Play();
player.isAttack = false;
b2Vec3 pos = player.GetObject().transform.position;
player.effect.SetName("attackEffect");
if (player.GetDirection() == Player::Direction::LEFT)
{
pos.Set(pos.x - player.GetCharacterStatus().reach / 2.f, pos.y + 8, pos.z);
player.effect.sprite.LoadImage(player.GetLeftEffectFileName(), m_renderer);
}
if (player.GetDirection() == Player::Direction::RIGHT)
{
pos.Set(pos.x + player.GetCharacterStatus().reach / 2.f, pos.y + 8, pos.z);
player.effect.sprite.LoadImage(player.GetRightEffectFileName(), m_renderer);
}
player.effect.transform.position.Set(pos.x, pos.y, pos.z);
player.effect.transform.SetScale(player.GetCharacterStatus().reach, 100.f);
player.effect.transform.rotation = 0;
player.effect.sprite.color = SDL_Color{ 255, 255, 255, 255 };
player.effect.sprite.activeAnimation = false;
AddObject(&player.effect);
player.effectLifeTime = 0.5f;
}
if (player.effectLifeTime < 0.f && player.effect.sprite.GetTexture() != nullptr)
{
player.effect.sprite.Free();
RemoveObject(&player.effect);
}
else if (player.effectLifeTime > 0.f)
{
b2Vec3 pos = player.GetObject().transform.position;
if (player.GetDirection() == Player::Direction::LEFT)
{
pos.Set(pos.x - player.GetCharacterStatus().reach / 2.f, pos.y, pos.z);
}
if (player.GetDirection() == Player::Direction::RIGHT)
{
pos.Set(pos.x + player.GetCharacterStatus().reach / 2.f, pos.y, pos.z);
}
player.effect.transform.position.Set(pos.x, pos.y, pos.z);
}
player.effectLifeTime -= dt;
}
void TutorialLevel::CreateCommonUI()
{
p1.SetName("p1");
p1.sprite.LoadImage("texture/UI/p1.png", m_renderer);
p1.transform.SetScale(50, 50);
p1.transform.position.Set(-500.f, m_height / 2.f - 50.f, 0.f);
p1.sprite.isHud = true;
AddObject(&p1);
p1_trapImage.SetName("p1_trapImage");
p1_trapImage.sprite.LoadImage("texture/items/trap.png", m_renderer);
p1_trapImage.transform.SetScale(40, 30);
p1_trapImage.sprite.color = SDL_Color{ 255, 0, 0, 255 };
p1_trapImage.transform.position.Set(-500.f + 85.f, m_height / 2.f - 100.f, 0.f);
p1_trapImage.sprite.isHud = true;
AddObject(&p1_trapImage);
p1_trapcooldown_ui.SetName("p1trapcooldown");
p1_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p1_1.png", m_renderer);
p1_trapcooldown_ui.transform.SetScale(120, 40);
p1_trapcooldown_ui.transform.position.Set(-500.f, m_height / 2.f - 100.f, 0.f);
p1_trapcooldown_ui.sprite.isHud = true;
AddObject(&p1_trapcooldown_ui);
p2.SetName("p2");
p2.sprite.LoadImage("texture/UI/p2.png", m_renderer);
p2.transform.SetScale(50, 50);
p2.transform.position.Set(500.f, m_height / 2.f - 50.f, 0.f);
p2.sprite.isHud = true;
AddObject(&p2);
p2_trapImage.SetName("p2_trapImage");
p2_trapImage.sprite.LoadImage("texture/items/trap.png", m_renderer);
p2_trapImage.transform.SetScale(40, 30);
p2_trapImage.sprite.color = SDL_Color{ 0, 0, 255, 255 };
p2_trapImage.transform.position.Set(500.f - 85.f, m_height / 2.f - 100.f, 0.f);
p2_trapImage.sprite.isHud = true;
AddObject(&p2_trapImage);
p2_trapcooldown_ui.SetName("p2trapcooldown");
p2_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p2_1.png", m_renderer);
p2_trapcooldown_ui.transform.SetScale(120, 40);
p2_trapcooldown_ui.transform.position.Set(500.f, m_height / 2.f - 100.f, 0.f);
p2_trapcooldown_ui.sprite.isHud = true;
AddObject(&p2_trapcooldown_ui);
CreateScoreUI();
}
void TutorialLevel::CreateScoreUI()
{
p1_score_1.SetName("p1_score_1");
p1_score_2.SetName("p1_score_2");
if (m_game->p1WinCount == 1)
{
p1_score_1.sprite.LoadImage("texture/UI/score_p1win.png", m_renderer);
p1_score_2.sprite.LoadImage("texture/UI/score.png", m_renderer);
}
else if (m_game->p1WinCount == 2)
{
p1_score_1.sprite.LoadImage("texture/UI/score_p1win.png", m_renderer);
p1_score_2.sprite.LoadImage("texture/UI/score_p1win.png", m_renderer);
}
else
{
p1_score_1.sprite.LoadImage("texture/UI/score.png", m_renderer);
p1_score_2.sprite.LoadImage("texture/UI/score.png", m_renderer);
}
p1_score_1.transform.SetScale(30, 30);
p1_score_1.sprite.color = SDL_Color{ 255, 255, 255, 255 };
p1_score_1.transform.position.Set(-500.f + 50.f, m_height / 2.f - 50.f, 0.f);
p1_score_1.sprite.isHud = true;
AddObject(&p1_score_1);
p1_score_2.transform.SetScale(30, 30);
p1_score_2.sprite.color = SDL_Color{ 255, 255, 255, 255 };
p1_score_2.transform.position.Set(-500.f + 85.f, m_height / 2.f - 50.f, 0.f);
p1_score_2.sprite.isHud = true;
AddObject(&p1_score_2);
p2_score_1.SetName("p2_score_1");
p2_score_2.SetName("p2_score_2");
if (m_game->p2WinCount == 1)
{
p2_score_1.sprite.LoadImage("texture/UI/score_p2win.png", m_renderer);
p2_score_2.sprite.LoadImage("texture/UI/score.png", m_renderer);
}
else if (m_game->p2WinCount == 2)
{
p2_score_1.sprite.LoadImage("texture/UI/score_p2win.png", m_renderer);
p2_score_2.sprite.LoadImage("texture/UI/score_p2win.png", m_renderer);
}
else
{
p2_score_1.sprite.LoadImage("texture/UI/score.png", m_renderer);
p2_score_2.sprite.LoadImage("texture/UI/score.png", m_renderer);
}
p2_score_1.transform.SetScale(30, 30);
p2_score_1.sprite.color = SDL_Color{ 255, 255, 255, 255 };
p2_score_1.transform.position.Set(500.f - 50.f, m_height / 2.f - 50.f, 0.f);
p2_score_1.sprite.isHud = true;
AddObject(&p2_score_1);
p2_score_2.sprite.LoadImage("texture/UI/score.png", m_renderer);
p2_score_2.transform.SetScale(30, 30);
p2_score_2.sprite.color = SDL_Color{ 255, 255, 255, 255 };
p2_score_2.transform.position.Set(500.f - 85.f, m_height / 2.f - 50.f, 0.f);
p2_score_2.sprite.isHud = true;
AddObject(&p2_score_2);
}
void TutorialLevel::CheckRespawn()
{
// Check for p1
if (player1.GetObject().transform.position.y < camera.position.y - m_height / 2.f - 200 && p1_respawnText.text.GetTexture() == nullptr)
{
player1.SetRespawnTime(1.5f);
p1_respawnText.SetName("p1_respawnText");
p1_respawnText.text.SetText(m_renderer, "Respawn..", mainFont);
p1_respawnText.text.color = SDL_Color{ 0,0,0 , 255 };
p1_respawnText.transform.SetScale(140, 50);
p1_respawnText.transform.position.Set(-500.f - 200.f, m_height / 2.f - 50.f, 0.f);
p1_respawnText.sprite.isHud = true;
AddObject(&p1_respawnText);
}
else if (player1.GetRespawnTime() < 0.f && player1.GetObject().transform.position.y < camera.position.y - m_height / 2.f - 200)
{
RemoveObject(&p1_respawnText);
player1.GetObject().RemoveCustomPhysicsComponent();
RemoveObject(&player1.GetObject());
player1.CreatePlayerObject(&player2, { 0, 200 }, m_game->p1Character, 1);
player1.AllocateBody(GetCustomPhysicsWorld());
AddObject(&player1.GetObject());
AddCustomPhysicsComponent(&player1.GetObject());
}
// Check for p2
if (player2.GetObject().transform.position.y < camera.position.y - m_height / 2.f - 200 && p2_respawnText.text.GetTexture() == nullptr)
{
player2.SetRespawnTime(1.5f);
p2_respawnText.SetName("p2_respawnText");
p2_respawnText.text.SetText(m_renderer, "Respawn..", mainFont);
p2_respawnText.text.color = SDL_Color{ 0,0,0 , 255 };
p2_respawnText.transform.SetScale(140, 50);
p2_respawnText.transform.position.Set(500.f + 200.f, m_height / 2.f - 50.f, 0.f);
p2_respawnText.sprite.isHud = true;
AddObject(&p2_respawnText);
}
else if (player2.GetRespawnTime() < 0.f && player2.GetObject().transform.position.y < camera.position.y - m_height / 2.f - 200)
{
RemoveObject(&p2_respawnText);
player2.GetObject().RemoveCustomPhysicsComponent();
RemoveObject(&player2.GetObject());
player2.CreatePlayerObject(&player1, { 0, 200 }, m_game->p2Character, 2);
player2.AllocateBody(GetCustomPhysicsWorld());
AddObject(&player2.GetObject());
AddCustomPhysicsComponent(&player2.GetObject());
}
}
void TutorialLevel::TrapCooldownAnimation(float dt)
{
p1_trapcooldown_ui.sprite.Free();
p2_trapcooldown_ui.sprite.Free();
// Player1 UI
if (player1.trapCoolDown > 0.f)
{
p1_trapcooldown_ui.sprite.Free();
if (player1.trapCoolDown <= 5.f && player1.trapCoolDown > 4.f)
{
p1_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p1_6.png", m_renderer);
}
else if (player1.trapCoolDown <= 4.f && player1.trapCoolDown > 3.f)
{
p1_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p1_5.png", m_renderer);
}
else if (player1.trapCoolDown <= 3.f && player1.trapCoolDown > 2.f)
{
p1_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p1_4.png", m_renderer);
}
else if (player1.trapCoolDown <= 2.f && player1.trapCoolDown > 1.f)
{
p1_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p1_3.png", m_renderer);
}
else if (player1.trapCoolDown <= 1.f && player1.trapCoolDown > 0.f)
{
p1_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p1_2.png", m_renderer);
}
}
else
{
p1_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p1_1.png", m_renderer);
}
// Player2 UI
if (player2.trapCoolDown > 0.f)
{
p2_trapcooldown_ui.sprite.Free();
if (player2.trapCoolDown <= 5.f && player2.trapCoolDown > 4.f)
{
p2_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p2_6.png", m_renderer);
}
else if (player1.trapCoolDown <= 4.f && player2.trapCoolDown > 3.f)
{
p2_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p2_5.png", m_renderer);
}
else if (player1.trapCoolDown <= 3.f && player2.trapCoolDown > 2.f)
{
p2_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p2_4.png", m_renderer);
}
else if (player1.trapCoolDown <= 2.f && player2.trapCoolDown > 1.f)
{
p2_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p2_3.png", m_renderer);
}
else if (player1.trapCoolDown <= 1.f && player2.trapCoolDown > 0.f)
{
p2_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p2_2.png", m_renderer);
}
}
else
{
p2_trapcooldown_ui.sprite.LoadImage("texture/UI/trapcooldown/TrapCool_p2_1.png", m_renderer);
}
player1.trapCoolDown -= dt;
player2.trapCoolDown -= dt;
} |
import 'package:consorcios/src/repositories/authentication_repository/authentication_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:formz/formz.dart';
import 'package:bloc/bloc.dart';
import '../models/models.dart';
part 'login_event.dart';
part 'login_state.dart';
class LoginBloc extends Bloc<LoginEvent, LoginState> {
LoginBloc({required AuthenticationRepository authenticationRepository})
: _authenticationRepository = authenticationRepository,
super(const LoginState()) {
on<LoginInit>(_onInit);
on<LoginUsernameChanged>(_onUsernameChanged);
on<LoginPasswordChanged>(_onPasswordChanged);
on<LoginSubmitted>(_onSubmitted);
}
final AuthenticationRepository _authenticationRepository;
Future<void> _onInit(
LoginInit event,
Emitter<LoginState> emit,
) async {
try {
print("Token guardado");
// ir a buscar el token, si tiene un token guardado hacer el refresh token
await _authenticationRepository.logInWithToken(
token: "asdasd-asdasdas-dasd",
);
emit(state.copyWith(status: FormzStatus.submissionSuccess));
} catch (_) {
emit(state.copyWith(status: FormzStatus.submissionFailure));
}
}
void _onUsernameChanged(
LoginUsernameChanged event,
Emitter<LoginState> emit,
) {
final username = Username.dirty(event.username);
emit(
state.copyWith(
username: username,
status: Formz.validate([state.password, username]),
),
);
}
void _onPasswordChanged(
LoginPasswordChanged event,
Emitter<LoginState> emit,
) {
final password = Password.dirty(event.password);
emit(
state.copyWith(
password: password,
status: Formz.validate([password, state.username]),
),
);
}
Future<void> _onSubmitted(
LoginSubmitted event,
Emitter<LoginState> emit,
) async {
if (state.status.isValidated) {
emit(state.copyWith(status: FormzStatus.submissionInProgress));
try {
await _authenticationRepository.logIn(
username: state.username.value,
password: state.password.value,
);
emit(state.copyWith(status: FormzStatus.submissionSuccess));
} catch (_) {
emit(state.copyWith(status: FormzStatus.submissionFailure));
}
}
}
} |
# Copyright (C) 2007-2016 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# GNU Mailman is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# GNU Mailman. If not, see <http://www.gnu.org/licenses/>.
"""Model for messages."""
from mailman import public
from mailman.database.model import Model
from mailman.database.transaction import dbconnection
from mailman.interfaces.messages import IMessage
from sqlalchemy import Column, Integer, Unicode
from zope.interface import implementer
@public
@implementer(IMessage)
class Message(Model):
"""A message in the message store."""
__tablename__ = 'message'
id = Column(Integer, primary_key=True)
# This is a Messge-ID field representation, not a database row id.
message_id = Column(Unicode)
message_id_hash = Column(Unicode)
path = Column(Unicode)
@dbconnection
def __init__(self, store, message_id, message_id_hash, path):
super().__init__()
self.message_id = message_id
self.message_id_hash = message_id_hash
self.path = path
store.add(self) |
import {
render,
screen,
waitFor,
} from "../../../test-utils/testing-library-utils";
import OrderEntry from "../OrderEntry";
import { server } from "../../../mocks/server";
import { rest } from "msw";
test("handle errors for scoops & toppings routes", async () => {
// reset handler to make it return error (code: 500)
server.resetHandlers(
rest.get("http://localhost:3030/scoops", (req, res, ctx) =>
res(ctx.status(500))
),
rest.get("http://localhost:3030/toppings", (req, res, ctx) =>
res(ctx.status(500))
)
);
render(<OrderEntry setOrderPhase={jest.fn()} />);
// Here we use waitFor because without it, there will be an error caused by that it gets executed once any one of the 2 alerts get to be rendered and does not wait for the other
await waitFor(async () => {
const alerts = await screen.findAllByRole("alert");
expect(alerts).toHaveLength(2);
});
}); |
package com.example.jwt_customize.service;
import com.example.jwt_customize.repository.UserRepository;
import com.example.jwt_customize.request.RegisterRequest;
import com.example.jwt_customize.service.UserService;
import com.example.jwt_customize.common.Role;
import com.example.jwt_customize.entity.User;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
PasswordEncoder passwordEncoder;
@Override
public Optional<User> findByEmail(String email) {
return userRepository.findByEmail(email);
}
@Override
public List<User> findAll() {
return userRepository.findAll();
}
@Override
public void save(RegisterRequest request) {
if(userRepository.findByEmail(request.getEmail()).isPresent()){
throw new ServiceException("Email exists");
}
var user = User.builder()
.firstname(request.getFirstname())
.lastname(request.getLastname())
.email(request.getEmail())
.password(passwordEncoder.encode(request.getPassword()))
.role(Role.USER)
.build();
var savedUser = userRepository.save(user);
}
} |
import React, { useState, useEffect } from "react";
import style from "./forgetpassword.module.css";
import ModalWrap from "../ModalWrapper/ModalWrap";
import { CgCloseO } from "react-icons/cg";
import { Formik } from "formik";
import { useGetPasswordMutation } from "../../../state/services/ForgetPasswordApi";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
function SignupModal() {
// TOGGLE MENU
const [toggle, setToggle] = useState(false);
// Toggle Function
const toggleMenu = () => {
setToggle(!toggle);
};
//CALLINNG THE HOOK FUNCTION AND ALSO DESTRUCTING THE STATE
const [getPassword, { isLoading, error, isSuccess }] =
useGetPasswordMutation();
//FORMS VALIDATION
const initialValues = {
email: "",
otp: "",
password: "",
confirmpassword: "",
};
//TO HANDLE DIFFERENT STATE OF THE RESPONSE
useEffect(() => {
if (isSuccess) {
toast.success("Sucessfully Registered");
formik.handleReset();
}
if (error) {
toast.error("An error occured");
}
if (isLoading) {
toast.info("In progress...");
}
}, [isSuccess, error]);
const validate = (values) => {
let errors = {};
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i;
if (!values.email) {
errors.email = "Email is required";
} else if (!regex.test(values.email)) {
errors.email = "Invalid Email";
}
if (!values.password) {
errors.password = "Password is required";
} else if (values.password.length < 4) {
errors.password = "Password too short";
}
return errors;
};
//GETTING FORM DATA
const submitForm = async (data) => {
//getting the form data and sending it to the backend
//alert("SUCCESS!! :-)\n\n" + JSON.stringify(data, null, 4));
const { email, password, confirmPassword } = data;
try {
await getPassword({
email,
password,
confirmPassword,
}).unwrap();
} catch (error) {
alert(error);
}
};
// API function and code
// const [getpassword] = useGetPasswordMutation();
// const handleOtp = () => {};
return (
<ModalWrap>
<div className={`${!toggle ? style.backdrop : style.hidebackdrop}`}>
<ToastContainer/>
<div className={style.navbar_close} onClick={toggleMenu}>
<CgCloseO size={20} color="fff" className={style.close} />
</div>
<div className={style.text_wrap}>
<h3>Forgot Password</h3>
<p>
Enter details to change password or{" "}
<span className={style.span_header}>signin</span>
</p>
</div>
<div>
<Formik
initialValues={initialValues}
validate={validate}
onSubmit={submitForm}
>
{(formik) => {
const {
values,
handleChange,
handleSubmit,
errors,
touched,
handleBlur,
isValid,
dirty,
} = formik;
return (
<div className={style.container}>
<form onSubmit={handleSubmit} className={style.sign_form}>
<div className={style.form_row}>
<div>
<label htmlFor="email" className={style.input_label}>
Email address
</label>
</div>
<div className={style.email_otpbtn}>
<div className={style.input_wrapper}>
<input
type="email"
name="email"
id="email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
placeholder="andersonbanny@gmail.com"
className={`${
errors.email && touched.email
? style.input_error
: null
} ${style.inputs}`}
/>
</div>
<div>
<button
className={style.otp_btn}
// onClick={() => handleOtp()}
>
Send OTP
</button>
</div>
</div>
<div className={style.display_error}>
{errors.email && touched.email && (
<span className={style.error}>{errors.email}</span>
)}
</div>
{/* OTP code */}
<div className={style.labels}>
<label className={style.input_label} htmlFor="otp">
OTP
</label>
</div>
<div className={style.password_wrap}>
<input
type="number"
name="otp"
id="otp"
value={values.otp}
onChange={handleChange}
onBlur={handleBlur}
className={`${
errors.otp && touched.otp ? style.input_error : null
} ${style.inputs}`}
/>
</div>
<div className={style.display_error}>
{errors.otp && touched.otp && (
<span className={style.error}>{errors.otp}</span>
)}
</div>
{/* End of OTP code */}
</div>
<div className={style.form_row}>
<div className={style.labels}>
<label className={style.input_label} htmlFor="password">
New Password
</label>
</div>
<div className={style.password_wrap}>
<input
type="password"
name="password"
id="password"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
className={`${
errors.password && touched.password
? style.input_error
: null
} ${style.inputs}`}
/>
</div>
<div className={style.display_error}>
{errors.password && touched.password && (
<span className={style.error}>{errors.password}</span>
)}
</div>
{/* Confirm password */}
<div className={style.labels}>
<label className={style.input_label} htmlFor="password">
Confirm Password
</label>
</div>
<div className={style.password_wrap}>
<input
type="password"
name="password"
id="password"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
className={`${
errors.password && touched.password
? style.input_error
: null
} ${style.inputs}`}
/>
</div>
<div className={style.display_error}>
{errors.password && touched.password && (
<span className={style.error}>{errors.password}</span>
)}
</div>
{/* End of Confirm password */}
</div>
<button
type="submit"
className={`${
!(dirty && isValid) ? style.disabled_btn : ""
} ${style.btn}`}
disabled={!(dirty && isValid)}
>
Change Password
</button>
</form>
</div>
);
}}
</Formik>
</div>
</div>
</ModalWrap>
);
}
export default SignupModal; |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Season extends Model
{
protected $fillable = ['number'];
public $timestamps = false;
public function anime() {
return $this->belongsTo(Anime::class);
}
public function episodes() {
return $this->hasMany(Episode::class);
}
public function getEpisodesAssisted(): Collection {
return $this->episodes->filter(function (Episode $episode) {
return $episode->assisted;
});
}
} |
library(dplyr)
library(ggplot2)
library(patchwork)
library(purrr)
library(rstatix)
theme_set(theme_bw(base_size = 14) + theme(panel.grid = element_blank()))
source("./R_data-cleaning/EEMs/code/clean-EEMs.R")
eems <- bp_doc_eems()
DOC_lab <- expression(paste("DOC concentration (mg L"^-1*")"))
SUVA_lab <- expression(paste("SUVA"[254]*" (L mg-C"^-1*" m"^-1*")"))
BA_lab <- expression(paste("Freshness index (", italic(β), ":", italic(α), ")"))
S_lab <- "<i>S</i><sub>275–295</sub>"
HIX_lab <- "Humification index"
FI_lab <- "Fluorescence index"
dist_lab <- "Distance from Buffalo Pound Lake inflow (km)"
# Are inflow sites statistically different? -------------------------------
inflow <- eems %>% filter(grepl("Inflow", site_code_long))
inflow %>%
ggplot(aes(site_code_long, DOC_mg.L)) +
# facet_wrap(~ Year) +
geom_boxplot()
inflow %>% group_by(site_code_long) %>% summarise(n = n())
iaov <- anova_test(DOC_mg.L ~ site_code_long, data = inflow)
# F(2, 52) = 0.126, p = 0.882 // inflow sites are not significantly different
# Are causeway upstream sites statistically different? -------------------
us_causeway <- eems %>% filter(grepl("Upstream Causeway", site_code_long))
us_causeway %>%
ggplot(aes(site_code_long, DOC_mg.L)) +
# facet_wrap(~ Year) +
geom_boxplot()
us_causeway %>% group_by(site_code_long) %>% summarise(n = n())
ccc <- us_causeway %>% filter(site_code_long == "Upstream Causeway Centre") %>% select(DOC_mg.L)
cce <- us_causeway %>% filter(site_code_long == "Upstream Causeway East") %>% select(DOC_mg.L)
t.test(ccc, cce, alternative = "two.sided", var.equal = FALSE)
# upstream causeway sites are not significantly different
lake_inflow <- inflow %>%
group_by(date_ymd) %>%
summarise(across(TDN_mg.L:ext_coeff_m, ~ mean(.x, na.rm = TRUE))) %>%
mutate(site_name = "1.5 km below Qu'Appelle R. Inflow Centre",
site_code_long = as.factor("Lake Inflow"),
site_abbr = as.factor("LI"),
Year = as.factor(year(date_ymd)),
Month = month(date_ymd, label = TRUE, abbr = TRUE),
DOY = yday(date_ymd),
latitude = 50.722927,
longitude = -105.605669,
distHaversine_km = 0) %>%
select(site_name, site_code_long, site_abbr, date_ymd, Year:distHaversine_km, everything())
upstream_causeway <- us_causeway %>%
group_by(date_ymd) %>%
summarise(across(TDN_mg.L:ext_coeff_m, ~ mean(.x, na.rm = TRUE))) %>%
mutate(site_name = "Upstream Causeway",
site_code_long = as.factor("Upstream Causeway"),
site_abbr = as.factor("CU"),
Year = as.factor(year(date_ymd)),
Month = month(date_ymd, label = TRUE, abbr = TRUE),
DOY = yday(date_ymd),
latitude = 50.722927,
longitude = -105.605669,
distHaversine_km = 2.18) %>%
select(site_name, site_code_long, site_abbr, date_ymd, Year:distHaversine_km, everything())
eems <- subset(eems, !grepl("Inflow", site_code_long))
eems <- subset(eems, !grepl("Upstream Causeway", site_code_long))
eems <- eems %>% bind_rows(lake_inflow) %>% bind_rows(upstream_causeway) %>% arrange(date_ymd)
site_codes <- tribble(
~site_code_long, ~site_abbr,
"Lake Inflow", "LI",
"Upstream Causeway", "CU",
"Below Causeway", "CB",
"Opposite South Lake", "SL",
"Opposite Sun Valley", "SV",
"Opposite Parkview", "PK",
"WTP Intake", "TP",
"Above Outlet", "AO"
)
site_codes_c <- site_codes[["site_code_long"]]
site_abbrs_c <- site_codes[["site_abbr"]]
eems <- eems %>%
mutate(site_code_long = forcats::fct_relevel(site_code_long, site_codes_c),
site_abbr = forcats::fct_relevel(site_abbr, site_abbrs_c))
eems %>%
group_by(site_abbr, distHaversine_km) %>%
summarise(DOC_mg.L = mean(DOC_mg.L, na.rm = TRUE)) %>%
ggplot(aes(distHaversine_km, DOC_mg.L, col = site_abbr)) +
geom_point() +
scale_color_viridis_d(end = 0.8)
# Seasonal ANOVA ----------------------------------------------------------
ee_spring <- eems %>% filter(Month %in% c("Mar", "Apr", "May", "June")) # n = 61
ee_summer <- eems %>% filter(Month %in% c("Jul", "Aug", "Sep")) # n = 78
ee_seasons <- eems %>%
mutate(Season = ifelse(Month %in% c("Mar", "Apr", "May", "June"), "Spring", "Summer"),
Season = factor(Season))
ee_seasons %>%
group_by(Season, distHaversine_km) %>%
summarise(DOC_mg.L = mean(DOC_mg.L, na.rm = TRUE)) %>%
ggplot(aes(distHaversine_km, DOC_mg.L, col = Season, shape = Season)) +
# geom_line(size = 1) +
geom_point(size = 3, col = "white") +
geom_point(size = 3) +
geom_smooth(method = 'lm', se = F, alpha = 1/4, size = 1) +
lims(x = c(0, 30)) +
labs(x = dist_lab, y = DOC_lab)
ee_seasons %>%
group_by(Season, distHaversine_km, Year) %>%
summarise(DOC_mg.L = mean(DOC_mg.L, na.rm = TRUE)) %>%
ggplot(aes(distHaversine_km, DOC_mg.L, col = Season, shape = Season)) +
facet_wrap(~ Year) +
geom_line(size = 1) +
geom_point(size = 3, col = "white") +
geom_point(size = 3) +
# geom_smooth(method = 'lm', se = F, alpha = 1/4, size = 1) +
lims(x = c(0, 30)) +
labs(x = dist_lab, y = DOC_lab)
spr <- ee_seasons %>% filter(Season == "Spring") %>% select(DOC_mg.L)
sum <- ee_seasons %>% filter(Season == "Summer") %>% select(DOC_mg.L)
t.test(spr, sum, alternative = "two.sided", var.equal = FALSE)
# Spring and summer DOC concentrations are not significantly different
mean_spr <- ee_seasons %>%
filter(Season == "Spring") %>%
group_by(distHaversine_km) %>%
summarise(DOC_mg.L = mean(DOC_mg.L, na.rm = TRUE))
var(mean_spr$DOC_mg.L) # = 0.02756821
mean_sum <- ee_seasons %>%
filter(Season == "Summer") %>%
group_by(distHaversine_km) %>%
summarise(DOC_mg.L = mean(DOC_mg.L, na.rm = TRUE))
var(mean_sum$DOC_mg.L) # = 0.2977929
mspr <- lm(DOC_mg.L ~ distHaversine_km, data = mean_spr)
summary(mspr)
# R2 = 0.7232, p = 0.004608 // y = 0.014014x + 5.328478
par(mfrow = c(2, 2)); plot(mspr)
gratia::appraise(mspr)
msum <- lm(DOC_mg.L ~ distHaversine_km, data = mean_sum)
summary(msum)
# R2 = 0.9575, p = 1.536e-05 // y = 0.051766x + 4.835060
par(mfrow = c(2, 2)); plot(msum)
gratia::appraise(msum)
## // ##
ee_seasons_avg <- ee_seasons %>%
group_by(Season, distHaversine_km) %>%
summarise(DOC_mg.L = mean(DOC_mg.L, na.rm = TRUE)) %>%
ungroup() %>%
mutate(logDOC_mg.L = log(DOC_mg.L))
model1 <- glm(DOC_mg.L ~ distHaversine_km * Season, data = ee_seasons_avg)
summary(model1)
anova(model1, test = 'F')
# compare to null model
model_null <- glm(DOC_mg.L ~ 1, data = ee_seasons_avg)
anova(model_null, model1, test = 'F')
# model1 is significantly different from the null model
# check the model assumptions
par(mfrow = c(2,2)); plot(model1)
# check distribution
ee_seasons_avg %>%
ggplot(aes(log(DOC_mg.L))) +
geom_histogram()
# try log-transformation
model2 <- glm(logDOC_mg.L ~ distHaversine_km * Season, data = ee_seasons_avg)
summary(model2)
anova(model2, test = 'F')
par(mfrow = c(2,2)); plot(model2)
coef(model2)
ee_seasons_avg %>%
ggplot(aes(distHaversine_km, logDOC_mg.L, col = Season, shape = Season)) +
geom_point(size = 3) +
lims(x = c(0, 30), y = c(1, 3)) +
labs(x = dist_lab, y = DOC_lab)
# all terms significant so no need for model simplication
# the next step in model simplification is to test whether or not Season has a
# significant effect on DOC concentration when we control for distHaversine_km;
# to do this we use update(), and remove Season:
model3 <- update(model2, ~ . - Season)
summary(model3)
anova(model3, test = 'F')
mmm <- glm(logDOC_mg.L ~ distHaversine_km, data = ee_seasons_avg)
summary(mmm)
anova(model2, model3, test = 'F')
model4 <- glm(formula = logDOC_mg.L ~ distHaversine_km + Season, data = ee_seasons_avg)
## // ##
ee_seasons_avg %>%
ggplot(aes(Season, DOC_mg.L)) +
geom_boxplot()
ee_seasons_avg %>%
ungroup() %>%
mutate(Season = factor(Season)) %>%
t_test(formula = DOC_mg.L ~ Season, p.adjust.method = 'bonferroni', detailed = TRUE)
ggpubr::ggpaired(ee_seasons_avg, x = "Season", y = "DOC_mg.L",
order = c("Spring", "Summer"),
xlab = "Season", ylab = DOC_lab)
ee_seasons_avg_wide <- ee_seasons_avg %>%
select(-logDOC_mg.L) %>%
pivot_wider(names_from = Season, values_from = DOC_mg.L) %>%
mutate(differences = Spring - Summer)
ee_seasons_avg_wide %>% identify_outliers(differences) # no extreme outliters
ee_seasons_avg_wide %>% shapiro_test(differences) # ~ normal
ggpubr::ggqqplot(ee_seasons_avg_wide, "differences")
t_test_res <- ee_seasons_avg %>% t_test(DOC_mg.L ~ Season, paired = TRUE, detailed = TRUE) %>% add_significance()
# not significantly different
t_test_res <- t_test_res %>% add_xy_position(x = "Season")
ggpubr::ggpaired(ee_seasons_avg, x = "Season", y = "DOC_mg.L",
order = c("Spring", "Summer"),
xlab = "Season", ylab = DOC_lab) +
ggpubr::stat_pvalue_manual(t_test_res) +
labs(subtitle = get_test_label(t_test_res, detail = TRUE))
eese
# Group sites -------------------------------------------------------------
lake_order <- c("Inflow", "Causeway", "Mid-lake", "Outlet")
eems <- eems %>%
mutate(lake_section = ifelse(site_num %in% c(1:3), "Inflow",
ifelse(site_num %in% c(4:6), "Causeway",
ifelse(site_num %in% c(7:9), "Mid-lake", "Outlet"))),
lake_section = factor(lake_section),
lake_section = forcats::fct_relevel(lake_section, lake_order)) %>%
select(site_num, lake_section, everything())
eems %>%
filter(!is.na(DOC_mg.L)) %>%
ggplot(aes(site_code_long, DOC_mg.L, fill = lake_section)) +
facet_wrap(~ Year, ncol = 4) +
geom_boxplot(alpha = 3/4) +
coord_flip() +
scale_x_discrete(limits = rev) +
theme(legend.position = "bottom", legend.title = element_blank()) +
labs(x = NULL, y = DOC_lab)
eems %>%
filter(!is.na(DOC_mg.L)) %>%
ggplot(aes(site_code_long, DOC_mg.L, fill = lake_section)) +
# facet_wrap(~ Year, ncol = 4) +
geom_boxplot(alpha = 9/10) +
coord_flip() +
scale_x_discrete(limits = rev) +
theme(legend.position = "bottom", legend.title = element_blank()) +
labs(x = NULL, y = DOC_lab)
eems %>%
filter(!is.na(DOC_mg.L)) %>%
ggplot(aes(lake_section, DOC_mg.L, fill = lake_section)) +
facet_wrap(~ Year, ncol = 4) +
geom_boxplot(alpha = 9/10) +
coord_flip() +
scale_x_discrete(limits = rev) +
theme(legend.position = "bottom", legend.title = element_blank()) +
labs(x = NULL, y = DOC_lab)
eems %>%
filter(!is.na(DOC_mg.L)) %>%
group_by(site_num, site_code_long, Year) %>%
summarise(obs_n = n()) %>%
mutate(lake_section = ifelse(site_num %in% c(1:3), "Inflow",
ifelse(site_num %in% c(4:6), "Causeway",
ifelse(site_num %in% c(7:9), "Mid-lake", "Outlet"))),
lake_section = factor(lake_section),
lake_section = forcats::fct_relevel(lake_section, lake_order)) %>%
ggplot(aes(site_code_long, obs_n, fill = lake_section)) +
facet_wrap(~ Year, nrow = 1) +
geom_col(alpha = 9/10) +
coord_flip() +
scale_x_discrete(limits = rev) +
theme(legend.position = "bottom", legend.title = element_blank()) +
labs(x = NULL, y = "Number of observations")
# Summary stats -----------------------------------------------------------
# // DOC ------------------------------------------------------------------
eems %>%
# group_by(site_code_long, Year) %>%
get_summary_stats(DOC_mg.L, type = "common")
eems %>%
filter(site_num %in% c(1:6)) %>%
get_summary_stats(DOC_mg.L, type = "common")
eems %>%
filter(site_num %in% c(7:11)) %>%
get_summary_stats(DOC_mg.L, type = "common")
eems %>%
filter(site_num %in% c(10)) %>%
get_summary_stats(DOC_mg.L, type = "common")
eems %>%
filter(Month %in% c("Mar", "Apr", "May", "Jun")) %>%
get_summary_stats(DOC_mg.L, type = "common")
eems %>%
filter(Month %in% c("Jul", "Aug", "Sep")) %>%
get_summary_stats(DOC_mg.L, type = "common")
abbr_levs <- c('IE','IC','IW','CC','CE','CB','SL','SV','PK','TP','AO')
eems <- eems %>% mutate(site_abbr = ifelse(site_num == 1, "IE",
ifelse(site_num == 2, "IC",
ifelse(site_num == 3, "IW",
ifelse(site_num == 4, "CC",
ifelse(site_num == 5, "CE",
ifelse(site_num == 6, "CB",
ifelse(site_num == 7, "SL",
ifelse(site_num == 8, "SV",
ifelse(site_num == 9, "PK",
ifelse(site_num == 10, "TP",
ifelse(site_num == 11, "AO", site_abbr))))))))))),
site_abbr = as.factor(site_abbr),
site_abbr = fct_relevel(site_abbr, abbr_levs))
pppp <- eems %>%
rename(`Day of year` = DOY) %>%
ggplot(aes(site_num, DOC_mg.L, col = `Day of year`, group = `Day of year`)) +
facet_wrap(~ Year) +
geom_line(size = 0.75) +
geom_point(col = "white", size = 2) +
geom_point() +
scale_x_continuous(breaks = c(1,2,3,4,5,6,7,8,9,10,11),
labels = c("1","2","3","4","5","6","7","8","9","10","11")) +
scale_color_viridis_c() +
theme(legend.position = "bottom") +
labs(x = "Site", y = DOC_lab)
eems %>%
rename(`Day of year` = DOY) %>%
ggplot(aes(site_abbr, DOC_mg.L, col = `Day of year`, group = `Day of year`)) +
facet_wrap(~ Year) +
geom_line(size = 0.75) +
geom_point(col = "white", size = 2) +
geom_point() +
# scale_x_continuous(breaks = c(1,2,3,4,5,6,7,8,9,10,11),
# labels = c("1","2","3","4","5","6","7","8","9","10","11")) +
scale_color_viridis_c() +
theme(legend.position = "bottom") +
labs(x = "Site", y = DOC_lab)
doc_mean <- eems %>%
group_by(distHaversine_km) %>%
summarise(DOC_mean = mean(DOC_mg.L, na.rm = TRUE))
mmdoc <- lm(doc_mean$DOC_mean ~ doc_mean$distHaversine_km)
summary(mmdoc)
# R2 = 0.94, p = 4.5e-7
p_lm_doc <- doc_mean %>%
ggplot(aes(distHaversine_km, DOC_mean)) +
geom_point(size = 3) +
geom_smooth(method = 'lm') +
lims(x = c(0, 30)) +
labs(x = NULL, y = DOC_lab)
(p_lm_doc + p_lm_suva) / (p_lm_s + p_lm_fi) / (p_lm_hix + p_lm_ba)
# // SUVA -----------------------------------------------------------------
eems %>%
# group_by(site_code_long, Year) %>%
get_summary_stats(SUVA, type = "common")
eems %>%
filter(site_num %in% c(1:6)) %>%
get_summary_stats(SUVA, type = "common")
eems %>%
filter(site_num %in% c(7:11)) %>%
get_summary_stats(SUVA, type = "common")
eems %>%
filter(site_num %in% c(10)) %>%
get_summary_stats(SUVA, type = "common")
eems %>%
filter(Month %in% c("Mar", "Apr", "May", "Jun")) %>%
get_summary_stats(SUVA, type = "common")
eems %>%
filter(Month %in% c("Jul", "Aug", "Sep")) %>%
get_summary_stats(SUVA, type = "common")
eems %>%
ggplot(aes(site_num, SUVA, col = DOY, group = DOY)) +
facet_wrap(~ Year) +
geom_line(size = 0.75) +
geom_point(col = "white", size = 2) +
geom_point() +
scale_x_continuous(breaks = c(1,2,3,4,5,6,7,8,9,10,11),
labels = c("1","2","3","4","5","6","7","8","9","10","11")) +
scale_color_viridis_c()
eems %>%
mutate(DOY = as.factor(DOY)) %>%
ggplot(aes(DOY, SUVA)) +
facet_wrap(~ Year, scales = "free_x") +
geom_boxplot()
suva_mean <- eems %>%
group_by(distHaversine_km) %>%
summarise(suva_mean = mean(SUVA, na.rm = TRUE))
mmsuva <- lm(suva_mean$suva_mean ~ suva_mean$distHaversine_km)
summary(mmsuva)
# R2 = 0.98, p = 1.56e-9
p_lm_suva <- suva_mean %>%
ggplot(aes(distHaversine_km, suva_mean)) +
geom_point(size = 3) +
geom_smooth(method = 'lm') +
lims(x = c(0, 30)) +
labs(x = NULL, y = SUVA_lab)
# // S275to295 ------------------------------------------------------------
eems %>% get_summary_stats(S275to295, type = 'common')
eems %>%
filter(site_num %in% c(1:6)) %>%
get_summary_stats(S275to295, type = "common")
eems %>%
filter(site_num %in% c(7:11)) %>%
get_summary_stats(S275to295, type = "common")
eems %>%
group_by(Month) %>%
get_summary_stats(S275to295, type = "common")
eems %>%
group_by(site_code_long) %>%
get_summary_stats(S275to295, type = "common")
eems %>%
group_by(site_code_long, Year) %>%
get_summary_stats(S275to295, type = "common") %>%
arrange(Year) %>%
filter(Year == 2019)
eems %>%
# group_by(site_code_long, date_ymd) %>%
# group_by(site_code_long, Year) %>%
# get_summary_stats(S275to295, type = "common") %>%
ggplot(aes(site_num, S275to295, col = DOY, group = DOY)) +
facet_wrap(~ Year) +
geom_point() +
geom_line() +
lims(x = c(0, 12))
# In all years S increased from inflow sites and peaked at the outlet site,
# with average values reaching 0.025 in 2017, 2018, and 2019, and 0.023 in 2016.
# The highest mean S values were observed in 2019 where they ranged from
# 0.023—0.025.
eems %>%
ggplot(aes(site_num, S275to295, col = DOY, group = DOY)) +
facet_wrap(~ Year) +
geom_line(size = 0.75) +
geom_point(col = "white", size = 2) +
geom_point() +
scale_x_continuous(breaks = c(1,2,3,4,5,6,7,8,9,10,11),
labels = c("1","2","3","4","5","6","7","8","9","10","11")) +
scale_color_viridis_c() +
labs(y = S_lab) +
theme(axis.title.y = ggtext::element_markdown())
s_mean <- eems %>%
group_by(distHaversine_km) %>%
summarise(S_mean = mean(S275to295, na.rm = TRUE))
mms <- lm(s_mean$S_mean ~ s_mean$distHaversine_km)
summary(mms)
# R2 = 0.96, p = 4.75e-8
p_lm_s <- s_mean %>%
ggplot(aes(distHaversine_km, S_mean)) +
geom_point(size = 3) +
geom_smooth(method = 'lm') +
lims(x = c(0, 30)) +
labs(x = NULL, y = S_lab) +
theme(axis.title.y = ggtext::element_markdown())
eems %>%
mutate(DOY = as.factor(DOY)) %>%
ggplot(aes(DOY, S275to295)) +
facet_wrap(~ Year, scales = "free_x") +
geom_boxplot()
# // Fluorescence Index ---------------------------------------------------
eems %>%
filter(FI < 1.69) %>%
get_summary_stats(FI, type = 'common')
# mean = 1.56 ± 0.033 (1.48—1.66), N = 211
eems %>%
filter(FI < 1.69) %>%
filter(site_num %in% c(1:6)) %>%
get_summary_stats(FI, type = "common")
# mean = 1.54 ± 0.027 (1.48—1.61), N = 112
eems %>%
filter(FI < 1.69) %>%
filter(site_num %in% c(7:11)) %>%
get_summary_stats(FI, type = "common")
# mean = 1.58 ± 0.028 (1.51—1.66), N = 99
eems %>%
filter(FI < 1.69) %>%
group_by(Month) %>%
get_summary_stats(FI, type = "common")
# Obvious seasonal differences in FI values were absent; mean FI was highest in
# March and September (1.57), lowest in June (1.55), and 1.56 in April, May,
# July, and August.
eems %>%
filter(FI < 1.69) %>%
group_by(site_code_long) %>%
get_summary_stats(FI, type = "common")
# While seasonal patterns were not evident, mean FI values increased linearly
# with increasing distance from the lake inflow 1.54 at the five sites above the
# causeway to 1.59 at WTP Intake and 1.60 at Above Outlet (R2 = 0.94, p =
# 4.9e-7, Figure nD). Hansen et al. (2016) report increasing FI values with
# microbial processing for plant and algae leachates that underwent an 111 day
# incubation; however the FI values in this study are lower than their FI values
# for peat soils (1.6-1.9).
eems %>%
filter(FI < 1.69) %>%
group_by(site_code_long, Year) %>%
get_summary_stats(FI, type = "common") %>% filter(Year == 2019)
eems %>%
filter(FI < 1.69) %>%
group_by(Year) %>%
get_summary_stats(FI, type = "common")
eems %>%
ggplot(aes(site_num, FI, col = DOY, group = DOY)) +
facet_wrap(~ Year) +
geom_line(size = 0.75) +
geom_point(col = "white", size = 2) +
geom_point() +
scale_x_continuous(breaks = c(1,2,3,4,5,6,7,8,9,10,11),
labels = c("1","2","3","4","5","6","7","8","9","10","11")) +
scale_color_viridis_c()
fi_mean <- eems %>%
filter(FI < 1.69) %>%
group_by(distHaversine_km) %>%
summarise(FI_mean = mean(FI, na.rm = TRUE))
mmfi <- lm(fi_mean$FI_mean ~ fi_mean$distHaversine_km)
summary(mmfi)
# R2 = 0.94, p = 4.9e-7
p_lm_fi <- fi_mean %>%
ggplot(aes(distHaversine_km, FI_mean)) +
geom_point(size = 3) +
geom_smooth(method = 'lm') +
lims(x = c(0, 30)) +
labs(x = NULL, y = FI_lab)
# // Humification Index ---------------------------------------------------
eems %>%
ggplot(aes(site_num, HIX_Ohno, col = DOY, group = DOY)) +
facet_wrap(~ Year) +
geom_line(size = 0.75) +
geom_point(col = "white", size = 2) +
geom_point() +
scale_x_continuous(breaks = c(1,2,3,4,5,6,7,8,9,10,11),
labels = c("1","2","3","4","5","6","7","8","9","10","11")) +
scale_color_viridis_c()
hix_mean <- eems %>%
group_by(distHaversine_km) %>%
summarise(HIX_mean = mean(HIX_Ohno, na.rm = TRUE))
mmhix <- lm(hix_mean$HIX_mean ~ hix_mean$distHaversine_km)
summary(mmhix)
# R2 = 0.88, p = 1.08e-5
p_lm_hix <- hix_mean %>%
ggplot(aes(distHaversine_km, HIX_mean)) +
geom_point(size = 3) +
geom_smooth(method = 'lm') +
lims(x = c(0, 30)) +
labs(x = dist_lab, y = HIX_lab)
# // Freshness Index (β:α) ------------------------------------------------
eems %>%
ggplot(aes(site_num, BA, col = DOY, group = DOY)) +
facet_wrap(~ Year) +
geom_line(size = 0.75) +
geom_point(col = "white", size = 2) +
geom_point() +
scale_x_continuous(breaks = c(1,2,3,4,5,6,7,8,9,10,11),
labels = c("1","2","3","4","5","6","7","8","9","10","11")) +
scale_color_viridis_c()
ba_mean <- eems %>%
group_by(distHaversine_km) %>%
summarise(BA_mean = mean(BA, na.rm = TRUE))
mmba <- lm(ba_mean$BA_mean ~ ba_mean$distHaversine_km)
summary(mmba)
# R2 = 0.94, p = 7.54e-7
p_lm_ba <- ba_mean %>%
ggplot(aes(distHaversine_km, BA_mean)) +
geom_point(size = 3) +
geom_smooth(method = 'lm') +
lims(x = c(0, 30)) +
labs(x = dist_lab, y = BA_lab)
# // C:T ratio ------------------------------------------------------------
eems %>%
filter(!Year == 2019) %>%
ggplot(aes(site_num, CT_ratio, col = DOY, group = DOY)) +
# facet_wrap(~ Year, ncol = 1, scale = "free_y") +
geom_point() +
geom_line() +
lims(x = c(0, 12))
# // A:T ratio ------------------------------------------------------------
eems %>%
filter(!Year == 2019) %>%
ggplot(aes(site_num, AT_ratio, col = DOY, group = DOY)) +
# facet_wrap(~ Year, ncol = 1, scale = "free_y") +
geom_point() +
geom_line() +
lims(x = c(0, 12))
# // C:A ratio ------------------------------------------------------------
eems %>%
filter(!Year == 2019) %>%
ggplot(aes(site_num, CA_ratio, col = DOY, group = DOY)) +
# facet_wrap(~ Year, ncol = 1, scale = "free_y") +
geom_point() +
geom_line() +
lims(x = c(0, 12))
# // C:M ratio ------------------------------------------------------------
eems %>%
filter(!Year == 2019) %>%
ggplot(aes(site_num, CM_ratio, col = DOY, group = DOY)) +
# facet_wrap(~ Year, ncol = 1, scale = "free_y") +
geom_point() +
geom_line() +
lims(x = c(0, 12))
# Some plots --------------------------------------------------------------
eems %>%
filter(!is.na(DOC_mg.L)) %>%
ggplot(aes(Month, DOC_mg.L)) +
facet_wrap(~ Year) +
geom_boxplot()
eems %>%
filter(!is.na(SUVA)) %>%
ggplot(aes(Month, SUVA)) +
facet_wrap(~ Year) +
geom_boxplot()
eems %>%
filter(!is.na(S275to295)) %>%
ggplot(aes(Month, S275to295)) +
facet_wrap(~ Year) +
geom_boxplot()
eems %>%
filter(!is.na(DOC_mg.L)) %>%
group_by(site_code_long, Year) %>%
summarise(n = n()) %>%
pivot_wider(names_from = Year, values_from = n) %>%
ungroup() %>%
summarise(sum17 = sum(`2017`),
sum18 = sum(`2018`))
eems %>%
filter(!is.na(DOC_mg.L)) %>%
group_by(site_code_long, Year) %>%
summarise(n = n()) %>%
ungroup() %>%
ggplot(aes(n, site_code_long)) +
facet_wrap(~ Year, ncol = 1) +
geom_col(alpha = 3/4) +
scale_y_discrete(limits = rev) +
theme_bw(base_size = 11) +
labs(y = NULL, x = "Number of DOC samples")
dd <- tribble(
~ydays,
yday("2022-03-01"), # 60
yday("2022-04-01"), # 91
yday("2022-05-01"), # 121
yday("2022-06-01"), # 152
yday("2022-07-01"), # 182
yday("2022-08-01"), # 213
yday("2022-09-01"), # 244
yday("2022-10-01") # 274
)
tibble(date_ymd = unique(eems$date_ymd),
doy = yday(date_ymd),
year = year(date_ymd),
val = ifelse(year == 2016, "2016",
ifelse(year == 2017, "2017",
ifelse(year == 2018, "2018", "2019")))) %>%
mutate(val = factor(val),
year = factor(year)) %>%
ggplot(aes(doy, val, col = year)) +
geom_vline(xintercept = dd$ydays, lty = 2) +
geom_point(size = 3) +
geom_line(size = 1) +
scale_y_discrete(limits = rev) +
xlim(c(1, 366)) +
theme(legend.position = 'none') +
labs(x = "Day of year", y = NULL)
eems %>%
pivot_longer(cols = c(TDN_mg.L:ext_coeff_m),
names_to = "parameter",
values_to = "result") %>%
group_by(parameter) %>%
filter(!is.na(result)) %>%
summarize(n = n(),
min = min(result),
max = max(result),
q1 = quantile(result, 0.25),
q3 = quantile(result, 0.75),
iqr = IQR(result),
median = median(result),
mean = mean(result),
sd = sd(result),
se = sd / sqrt(n),
ci = mean - (1.96*sd))
summary_all_eems <- eems %>%
select(-c(site_num:distHaversine_km)) %>%
get_summary_stats(type = 'full')
summary_select_eems <- eems %>%
select(-c(site_num:distHaversine_km)) %>%
select(-c(A280, A350, A440, S350to400)) %>%
get_summary_stats(type = 'full')
write_csv(summary_select_eems, "./R_EEMs/outputs/data/eems-summary-stats.csv")
summary_select_eems %>% filter(variable == "S275to295")
# Correlation matrix ------------------------------------------------------
dat<- matrix(rnorm(50), nrow=10, ncol=5)
set.seed (877)
naInd<- sample(1:length(dat), 10)
dat[naInd]<- NA
colnames(dat)<- paste("col", 1:ncol(dat), sep="")
rownames(dat)<- paste("row", 1:nrow(dat), sep="")
dat
cor(dat)
as.data.frame(na.omit(dat))
cor(na.omit(dat))
myCorDat<- mycor(dat, method="pearson", na.action=na.omit)
mycor <- function(x, ...) {
r<- apply(x, 2, function(j) {
apply(x, 2, function(i) {
as.numeric(cor.test(i, j, ...)$estimate)
})
})
P<- apply(x, 2, function(j){
apply(x, 2, function(i){
as.numeric(cor.test(i, j, ...)$p.value)
})
})
out <- c()
out$P <- P
out$r <- r
return(out)
}
ee <- eems %>%
select(-c(site_num:distHaversine_km)) %>%
select(-c(A280, A350, A440, S350to400, SR, HIX, Fmax)) %>%
mutate(spA = PeakA_RU / DOC_mg.L,
spB = PeakB_RU / DOC_mg.L,
spC = PeakC_RU / DOC_mg.L,
spD = PeakD_RU / DOC_mg.L,
spE = PeakE_RU / DOC_mg.L,
spM = PeakM_RU / DOC_mg.L,
spN = PeakN_RU / DOC_mg.L,
spP = PeakP_RU / DOC_mg.L,
spT = PeakT_RU / DOC_mg.L)
eem <- as.matrix(ee)
eem_corr <- Hmisc::rcorr(eem, type = "pearson")
corrplot::corrplot(corr = eem_corr$r, p.mat = eem_corr$P,
type = "full",
insig = "pch",
sig.level = 0.05,
pch.cex = 0.9)
View(eem_corr)
eem_corr_rvals <- as_tibble(eem_corr[["r"]])
# ANOVAs ------------------------------------------------------------------
# https://www.datanovia.com/en/lessons/anova-in-r/
# https://www.datanovia.com/en/lessons/repeated-measures-anova-in-r/
# https://www.datanovia.com/en/lessons/kruskal-wallis-test-in-r/
# Basic one-way ANOVA -----------------------------------------------------
eems %>%
ggplot(aes(x = DOC_mg.L)) +
geom_histogram(binwidth = 0.2, col = "grey70") +
facet_wrap(~ lake_section) +
labs(x = DOC_lab)
library(tidyverse)
library(ggpubr)
library(rstatix)
eems %>%
group_by(site_code_long, Year) %>%
get_summary_stats(DOC_mg.L, type = "mean_sd")
eems %>%
select(site_code_long, Year, DOC_mg.L) %>%
group_by(site_code_long, Year) %>%
identify_outliers(DOC_mg.L)
model <- lm(DOC_mg.L ~ site_code_long, data = eems)
ggqqplot(residuals(model))
shapiro_test(residuals(model))
eems %>%
select(site_code_long, Year, DOC_mg.L) %>%
group_by(site_code_long, Year) %>%
shapiro_test(DOC_mg.L) %>% View()
ggqqplot(eems, "DOC_mg.L", facet.by = "site_code_long")
plot(model, 1)
eems %>% levene_test(DOC_mg.L ~ site_code_long)
prep_rm <- function(df = eems, year = year) {
df <- df %>%
filter(Year == year) %>%
select(lake_section, site_code_long, date_ymd, DOC_mg.L) %>%
mutate(date_ymd = factor(date_ymd)) %>%
distinct()
}
eems16 <- prep_rm(eems, 2016)
eems17 <- prep_rm(eems, 2017)
eems18 <- prep_rm(eems, 2018)
eems19 <- prep_rm(eems, 2019)
res_aov16 <- eems16 %>% anova_test(DOC_mg.L ~ site_code_long)
res_aov17 <- eems17 %>% anova_test(DOC_mg.L ~ site_code_long)
res_aov18 <- eems18 %>% anova_test(DOC_mg.L ~ site_code_long)
res_aov19 <- eems19 %>% anova_test(DOC_mg.L ~ site_code_long)
res_aov16 # F(10, 42) = 1.469, p = 0.185, ges = 0.26
res_aov17 # F(10, 50) = 2.903, p = 0.006, ges = 0.37
res_aov18 # F(10, 46) = 2.675, p = 0.011, ges = 0.37
res_aov19 # F(10, 55) = 1.718, p = 0.1, ges = 0.24
pwc17 <- eems17 %>% tukey_hsd(DOC_mg.L ~ site_code_long)
pwc18 <- eems18 %>% tukey_hsd(DOC_mg.L ~ site_code_long)
pwc17
pwc18
# Repeated measures one-way ANOVA -----------------------------------------
### 2016 ###
eems16 %>%
group_by(site_code_long) %>%
get_summary_stats(type = "mean_sd")
# no extreme outliers
eems16 %>%
group_by(site_code_long) %>%
identify_outliers(DOC_mg.L)
# not normal; try Friedman Test
eems16 %>%
group_by(site_code_long) %>%
shapiro_test(DOC_mg.L)
rmaov16 <- anova_test(data = eems16, dv = DOC_mg.L, wid = site_code_long, within = date_ymd)
get_anova_table(rmaov16)
# F(1.25, 11.21) = 10.122, p = 0.006, generalized effect size (ges) = 0.364
# post-hoc Bonferroni -- doesn't work with a missing observation
pwc16 <- eems16 %>%
pairwise_t_test(DOC_mg.L ~ date_ymd, paired = TRUE, p.adjust.method = "bonferroni")
### 2017 ###
eems17 %>%
group_by(date_ymd) %>%
get_summary_stats(type = "mean_sd")
# no extreme outliers
eems17 %>%
group_by(date_ymd) %>%
identify_outliers(DOC_mg.L)
# not normal; try Friedman Test
eems17 %>%
group_by(date_ymd) %>%
shapiro_test(DOC_mg.L)
rmaov17 <- anova_test(data = eems17, dv = DOC_mg.L, wid = site_code_long, within = date_ymd)
get_anova_table(rmaov17)
# F(5, 25) = 3.268, p = 0.021, generalized effect size (ges) = 0.262
# post-hoc Bonferroni -- doesn't work with too few observations or missing values
pwc17 <- eems17 %>%
pairwise_t_test(DOC_mg.L ~ date_ymd, paired = TRUE, p.adjust.method = "bonferroni")
### 2018 ###
eems18 %>%
group_by(date_ymd) %>%
get_summary_stats(type = "mean_sd")
# one extreme outliers
eems18 %>%
group_by(date_ymd) %>%
identify_outliers(DOC_mg.L)
# not normal; try Friedman Test
eems18 %>%
group_by(date_ymd) %>%
shapiro_test(DOC_mg.L)
rmaov18 <- anova_test(data = eems18, dv = DOC_mg.L, wid = site_code_long, within = date_ymd)
get_anova_table(rmaov18)
# F(5, 20) = 0.676, p = 0.647, generalized effect size (ges) = 0.101
# post-hoc Bonferroni -- doesn't work when groups have different lengths
pwc18 <- eems18 %>%
pairwise_t_test(DOC_mg.L ~ date_ymd, paired = TRUE, p.adjust.method = "bonferroni")
### 2019 ###
eems19 %>%
group_by(site_code_long) %>%
get_summary_stats(type = "mean_sd")
# one extreme outlier
eems19 %>%
group_by(site_code_long) %>%
identify_outliers(DOC_mg.L)
# normality met
eems19 %>%
group_by(site_code_long) %>%
shapiro_test(DOC_mg.L)
rmaov19 <- anova_test(data = eems19, dv = DOC_mg.L, wid = date_ymd, within = site_code_long)
get_anova_table(rmaov19)
# F(2.52, 25.25) = 10.293, p = 0.000245, generalized effect size (ges) = 0.386
# post-hoc Bonferroni -- doesn't work when groups have different lengths
pwc19 <- eems19 %>%
pairwise_t_test(DOC_mg.L ~ site_code_long, paired = TRUE, p.adjust.method = "bonferroni")
bxp19 <- ggboxplot(eems19, x = "site_code_long", y = "DOC_mg.L", add = "point")
pwc19 <- pwc19 %>% add_xy_position(x = "date_ymd")
bxp19 +
stat_pvalue_manual(pwc19, hide.ns = FALSE) +
labs(subtitle = get_test_label(rmaov19, detail = TRUE),
caption = get_pwc_label(pwc19),
x = NULL,
y = DOC_lab) +
scale_x_discrete(limits = rev) +
coord_flip()
# Friedman Test -----------------------------------------------------------
### 2016 ###
eems16 %>%
group_by(date_ymd) %>%
get_summary_stats(DOC_mg.L, type = "common")
fried16 <- eems16 %>% friedman_test(DOC_mg.L ~ date_ymd | site_code_long)
### 2017 ###
eems17 %>%
group_by(date_ymd) %>%
get_summary_stats(DOC_mg.L, type = "common")
### 2018 ###
eems18 %>%
group_by(date_ymd) %>%
get_summary_stats(DOC_mg.L, type = "common")
### 2019 ###
eems19 %>%
group_by(site_code_long) %>%
get_summary_stats(DOC_mg.L, type = "common")
fried19 <- eems19 %>% friedman_test(DOC_mg.L ~ site_code_long | date_ymd)
# n = 6 sites, X^2(10) = 21.7, p = 0.0166
effried19 <- eems19 %>% friedman_effsize(DOC_mg.L ~ site_code_long | date_ymd)
# Kendall's W coefficient = 0.362 (moderate effect)
# Wilcoxon signed-rank test for multiple pariwise comparisons
wpwc19 <- eems19 %>% wilcox_test(DOC_mg.L ~ site_code_long, paired = TRUE, p.adjust.method = "BY")
wpwc19 <- wpwc19 %>% add_xy_position(x = "site_code_long")
bxp19 +
stat_pvalue_manual(wpwc19, hide.ns = TRUE) +
labs(subtitle = get_test_label(fried19, detailed = TRUE),
caption = get_pwc_label(wpwc19),
x = NULL,
y = DOC_lab) +
scale_x_discrete(limits = rev) +
coord_flip()
# Kruskal-Wallis Test -----------------------------------------------------
# The effect size (eta^2) is based on the Kruskal-Wallis H statistic.
# eta^2[H] = (H - k + 1)/(n - k)
# where H = stat, k = number of groups, n = N.
# The effect size indicates the percentage of variance in the dependent var
# explained by the independent var.
# 0.01 to < 0.06 = small effect
# 0.06 to < 0.14 = moderate effect
# >= 0.14 = large effect
eems16 %>% kruskal_test(DOC_mg.L ~ site_code_long)
# n = 32, H(10) = 13.4, p = 0.203 -- not significant
eems16 %>% kruskal_effsize(DOC_mg.L ~ site_code_long)
# eta^2[H] = 0.161 (large effect)
eems17 %>% kruskal_test(DOC_mg.L ~ site_code_long)
# n = 61, H(10) = 23.8, p = 0.00822 -- significant at 0.99
eems17 %>% kruskal_effsize(DOC_mg.L ~ site_code_long)
# eta^2[H] = 0.275 (large effect)
eems18 %>% kruskal_test(DOC_mg.L ~ site_code_long)
# n = 57, H(10) = 20.6, 0.0243 -- significant at 0.95
eems18 %>% kruskal_effsize(DOC_mg.L ~ site_code_long)
# eta^2[H] = 0.230 (large effect)
eems19 %>% kruskal_test(DOC_mg.L ~ site_code_long)
# n = 66, H(10) = 7.99, p = 0.175 -- not significant
eems19 %>% kruskal_effsize(DOC_mg.L ~ site_code_long)
# eta^2[H] = 0.0719 (moderate effect)
# Multiple pairwise comparisons
# Use Dunn's test to identify which groups are different.
# Can also use Wolcoxon's test to calculate pairwise comparisons between
# groups levels with corrections for multiple testing.
# Compared to Wilcoxon's test, Dunn's test takes into account the rankings used
# by the Kruskwal-Wallis test and adjusts for ties.
# Dunn Test
pwc_kw17 <- eems17 %>% dunn_test(DOC_mg.L ~ site_code_long, p.adjust.method = "BY")
pwc_kw18 <- eems18 %>% dunn_test(DOC_mg.L ~ site_code_long, p.adjust.method = "BY")
pwc_kw17 %>% arrange(p.adj)
pwc_kw18 %>% arrange(p.adj)
# Wilcoxon Test
pwc2_kw17 <- eems17 %>% wilcox_test(DOC_mg.L ~ site_code_long, p.adjust.method = "BY")
pwc2_kw18 <- eems18 %>% wilcox_test(DOC_mg.L ~ site_code_long, p.adjust.method = "BY")
pwc2_kw17 %>% arrange(p.adj)
pwc2_kw18 %>% arrange(p.adj)
# Kruskal-Wallis with lake sections ---------------------------------------
### Summary stats
eems16 %>% group_by(lake_section) %>% get_summary_stats(DOC_mg.L, type = "common")
# lake_section variable n min max median iqr mean sd se ci
# <fct> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 Inflow DOC_mg.L 9 4.09 6.58 6.20 2.33 5.66 1.12 0.374 0.863
# 2 Causeway DOC_mg.L 9 4.80 7.12 6.24 1.04 6.09 0.734 0.245 0.564
# 3 Mid-lake DOC_mg.L 8 6.25 7.12 6.74 0.185 6.72 0.254 0.09 0.213
# 4 Outlet DOC_mg.L 6 6.51 6.97 6.65 0.087 6.70 0.157 0.064 0.164
eems17 %>% group_by(lake_section) %>% get_summary_stats(DOC_mg.L, type = "common")
# lake_section variable n min max median iqr mean sd se ci
# <fct> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 Inflow DOC_mg.L 15 4.55 7.97 5.18 0.784 5.52 1.08 0.279 0.599
# 2 Causeway DOC_mg.L 17 4.86 7.82 5.50 1.33 5.67 0.795 0.193 0.409
# 3 Mid-lake DOC_mg.L 18 4.85 6.95 6.32 0.967 6.12 0.612 0.144 0.304
# 4 Outlet DOC_mg.L 11 5.74 8.13 7.02 0.422 7.02 0.596 0.18 0.4
eems18 %>% group_by(lake_section) %>% get_summary_stats(DOC_mg.L, type = "common")
# lake_section variable n min max median iqr mean sd se ci
# <fct> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 Inflow DOC_mg.L 13 3.86 5.66 4.29 0.549 4.47 0.552 0.153 0.334
# 2 Causeway DOC_mg.L 15 3.92 5.30 4.43 0.484 4.49 0.426 0.11 0.236
# 3 Mid-lake DOC_mg.L 17 4.33 5.43 4.97 0.343 4.93 0.325 0.079 0.167
# 4 Outlet DOC_mg.L 12 4.23 6.50 5.29 0.839 5.24 0.696 0.201 0.442
eems19 %>% group_by(lake_section) %>% get_summary_stats(DOC_mg.L, type = "common")
# lake_section variable n min max median iqr mean sd se ci
# <fct> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 Inflow DOC_mg.L 18 4 5.9 4.6 1.42 4.83 0.706 0.166 0.351
# 2 Causeway DOC_mg.L 18 3.7 5 4.6 0.4 4.52 0.389 0.092 0.193
# 3 Mid-lake DOC_mg.L 18 4.2 6.3 4.95 0.35 5.03 0.517 0.122 0.257
# 4 Outlet DOC_mg.L 12 4.2 6.4 5.35 0.45 5.31 0.62 0.179 0.394
### Outliers
eems16 %>% group_by(lake_section) %>% identify_outliers(DOC_mg.L) # no extreme outliers
eems17 %>% group_by(lake_section) %>% identify_outliers(DOC_mg.L) # one extreme outlier
eems18 %>% group_by(lake_section) %>% identify_outliers(DOC_mg.L) # no extreme outliers
eems19 %>% group_by(lake_section) %>% identify_outliers(DOC_mg.L) # one extreme outliers
### Normality
m16 <- lm(DOC_mg.L ~ lake_section, data = eems16)
ggqqplot(residuals(m16)) # not great on bottom tail
shapiro_test(residuals(m16)) # p = 0.0229 (normality not true)
m17 <- lm(DOC_mg.L ~ lake_section, data = eems17)
ggqqplot(residuals(m17)) # not great on top tail
shapiro_test(residuals(m17)) # p = 0.00155 (normality not true)
m18 <- lm(DOC_mg.L ~ lake_section, data = eems18)
ggqqplot(residuals(m18)) # not great on top tail
shapiro_test(residuals(m18)) # p = 0.0721 (~ normal)
m19 <- lm(DOC_mg.L ~ lake_section, data = eems19)
ggqqplot(residuals(m19)) # looks decent
shapiro_test(residuals(m19)) # p = 0.260 (~ normal)
### Homogeneity of variance
eems16 %>% levene_test(DOC_mg.L ~ lake_section) # p = 0.0460, close to equal variance
eems17 %>% levene_test(DOC_mg.L ~ lake_section) # p = 0.574, equal variance
eems18 %>% levene_test(DOC_mg.L ~ lake_section) # p = 0.164, equal variance
eems19 %>% levene_test(DOC_mg.L ~ lake_section) # p = 0.0741, equal variance
### Assumptions summary
# 2016 --- no extreme outliers, data not normal and heteroscedastic
# 2017 --- one extreme outlier, data not normal but have equal variance
# 2018 --- no extreme outliers, data approach normality and have equal variance
# 2019 --- one extreme outlier, data approach normality and have equal variance
# Because 2016, 2017, and 2019 do not meet one or more of the assumptions of the
# one-way ANOVA, and because group sizes are unequal, I will instead use the
# non-parametric Kruskwal-Wallis test.
### Kruskal-Wallis tests
eems16 %>% kruskal_test(DOC_mg.L ~ lake_section)
# n = 32, H(3) = 12.1, p = 0.00701 -- significant at 0.99
eems16 %>% kruskal_effsize(DOC_mg.L ~ lake_section)
# eta^2[H] = 0.325 (large effect)
eems17 %>% kruskal_test(DOC_mg.L ~ lake_section)
# n = 61, H(3) = 21.4, p = 0.0000876 -- significant at 0.9999
eems17 %>% kruskal_effsize(DOC_mg.L ~ lake_section)
# eta^2[H] = 0.323 (large effect)
eems18 %>% kruskal_test(DOC_mg.L ~ lake_section)
# n = 57, H(3) = 16.6, p = 0.000868 -- significant at 0.999
eems18 %>% kruskal_effsize(DOC_mg.L ~ lake_section)
# eta^2[H] = 0.256 (large effect)
eems19 %>% kruskal_test(DOC_mg.L ~ lake_section)
# n = 66, H(3) = 12.7, p = 0.00532 -- significant at 0.99
eems19 %>% kruskal_effsize(DOC_mg.L ~ lake_section)
# eta^2[H] = 0.157 (large effect)
### Multiple pairwise comparisons
# Use Dunn's test to identify which groups are different.
# Can also use Wolcoxon's test to calculate pairwise comparisons between groups
# levels with corrections for multiple testing.
# Compared to Wilcoxon's test, Dunn's test takes into account the rankings used
# by the Kruskwal-Wallis test and adjusts for ties.
## Dunn Test
pwc3_kw16 <- eems16 %>% dunn_test(DOC_mg.L ~ lake_section, p.adjust.method = "BY")
pwc3_kw17 <- eems17 %>% dunn_test(DOC_mg.L ~ lake_section, p.adjust.method = "BY")
pwc3_kw18 <- eems18 %>% dunn_test(DOC_mg.L ~ lake_section, p.adjust.method = "BY")
pwc3_kw19 <- eems19 %>% dunn_test(DOC_mg.L ~ lake_section, p.adjust.method = "BY")
pwc3_kw16 %>% arrange(p.adj)
# Inflow and Mid-lake sig diff: p.adj = 0.0357
pwc3_kw17 %>% arrange(p.adj)
# Inflow and Outlet sig diff: p.adj = 0.000307
# Causeway and Outlet sig diff: p.adj = 0.00110
pwc3_kw18 %>% arrange(p.adj)
# Inflow and Outlet sig diff: p.adj = 0.0173
# Causeway and Outlet sig diff: p.adj = 0.0173
# Inflow and Mid-lake sig diff: p.adj = 0.0353
pwc3_kw19 %>% arrange(p.adj)
# Causeway and Outlet sig diff: p.adj = 0.0169
## Wilcoxon Test
pwc4_kw16 <- eems16 %>% wilcox_test(DOC_mg.L ~ lake_section, p.adjust.method = "BY")
pwc4_kw17 <- eems17 %>% wilcox_test(DOC_mg.L ~ lake_section, p.adjust.method = "BY")
pwc4_kw18 <- eems18 %>% wilcox_test(DOC_mg.L ~ lake_section, p.adjust.method = "BY")
pwc4_kw19 <- eems19 %>% wilcox_test(DOC_mg.L ~ lake_section, p.adjust.method = "BY")
pwc4_kw16 %>% arrange(p.adj)
# Inflow and Mid-lake sig diff: p.adj = 0.027
# Inflow nad Outlet sig diff: p.adj = 0.027
pwc4_kw17 %>% arrange(p.adj)
# Causeway and Outlet sig diff: p.adj = 0.000917
# Mid-lake and Outlet sig diff: p.adj = 0.001
# Inflow and Outlet sig diff: p.adj = 0.01
# Inflow and Mid-lake sig diff: p.adj = 0.049
pwc4_kw18 %>% arrange(p.adj)
# Inflow and Mid-lake sig diff: p.adj = 0.022
# Inflow nad Outlet sig diff: p.adj = 0.022
# Causeway and Mid-lake sig diff: p.adj = 0.022
# Causeway and Outlet sig diff: p.adj = 0.022
pwc4_kw19 %>% arrange(p.adj)
# Causeway and Mid-lake sig diff: p.adj = 0.017
# Causeway and Outlet sig diff: p.adj = 0.017
### Plot pairwise comparisons
# 2016
pwc3_kw16 <- pwc3_kw16 %>% add_xy_position(x = "lake_section")
p_kwd16 <- eems16 %>%
ggboxplot("lake_section", "DOC_mg.L") +
stat_pvalue_manual(pwc3_kw16, hide.ns = TRUE) +
labs(x = "Lake section", y = DOC_lab,
title = "Kruskwall-Wallis test Dunn pairwise comparisons (2016)")
pwc4_kw16 <- pwc4_kw16 %>% add_xy_position(x = "lake_section")
p_kww16 <- eems16 %>%
ggboxplot("lake_section", "DOC_mg.L") +
stat_pvalue_manual(pwc4_kw16, hide.ns = TRUE) +
labs(x = "Lake section", y = DOC_lab,
title = "Kruskwall-Wallis Test with Wilcoxon pairwise comparisons (2016)")
# 2017
pwc3_kw17 <- pwc3_kw17 %>% add_xy_position(x = "lake_section")
p_kwd17 <- eems17 %>%
ggboxplot("lake_section", "DOC_mg.L") +
stat_pvalue_manual(pwc3_kw17, hide.ns = TRUE) +
labs(x = "Lake section", y = DOC_lab,
title = "Kruskwall-Wallis Test with Dunn pairwise comparisons (2017)")
pwc4_kw17 <- pwc4_kw17 %>% add_xy_position(x = "lake_section")
p_kww17 <- eems17 %>%
ggboxplot("lake_section", "DOC_mg.L") +
stat_pvalue_manual(pwc4_kw17, hide.ns = TRUE) +
labs(x = "Lake section", y = DOC_lab,
title = "Kruskwall-Wallis Test with Wilcoxon pairwise comparisons (2017)")
# 2018
pwc3_kw18 <- pwc3_kw18 %>% add_xy_position(x = "lake_section")
p_kwd18 <- eems18 %>%
ggboxplot("lake_section", "DOC_mg.L") +
stat_pvalue_manual(pwc3_kw18, hide.ns = TRUE) +
labs(x = "Lake section", y = DOC_lab,
title = "Kruskwall-Wallis Test with Dunn pairwise comparisons (2018)")
pwc4_kw18 <- pwc4_kw18 %>% add_xy_position(x = "lake_section")
p_kww18 <- eems18 %>%
ggboxplot("lake_section", "DOC_mg.L") +
stat_pvalue_manual(pwc4_kw18, hide.ns = TRUE) +
labs(x = "Lake section", y = DOC_lab,
title = "Kruskwall-Wallis Test with Wilcoxon pairwise comparisons (2018)")
# 2019
pwc3_kw19 <- pwc3_kw19 %>% add_xy_position(x = "lake_section")
p_kwd19 <- eems19 %>%
ggboxplot("lake_section", "DOC_mg.L") +
stat_pvalue_manual(pwc3_kw19, hide.ns = TRUE) +
labs(x = "Lake section", y = DOC_lab,
title = "Kruskwall-Wallis Test with Dunn pairwise comparisons (2019)")
pwc4_kw19 <- pwc4_kw19 %>% add_xy_position(x = "lake_section")
p_kww19 <- eems19 %>%
ggboxplot("lake_section", "DOC_mg.L") +
stat_pvalue_manual(pwc4_kw19, hide.ns = TRUE) +
labs(x = "Lake section", y = DOC_lab,
title = "Kruskwall-Wallis Test with Wilcoxon pairwise comparisons (2019)")
p_kwd16 + p_kwd17 + p_kwd18 + p_kwd19
p_kww16 + p_kww17 + p_kww18 + p_kww19
eems %>%
ggplot(aes(date_ymd, chla_ug.L)) +
geom_point()
eems %>%
select(-Month) %>%
filter(!is.na(chla_ug.L)) %>%
rename(Month = date_ymd) %>%
ggplot(aes(lake_section, chla_ug.L)) +
geom_boxplot() +
geom_point(aes(col = Month)) +
labs(x = "Lake section",
y = "Chl a (µg/L)",
subtitle = "2019 Chl a concentrations")
eems %>%
select(-Month) %>%
filter(!is.na(ext_coeff_m)) %>%
rename(Month = date_ymd) %>%
ggplot(aes(lake_section, ext_coeff_m)) +
geom_boxplot() +
geom_point(aes(col = Month)) +
labs(x = "Lake section",
y = "Extinction coefficient (m)",
subtitle = "2019 extinction coefficients")
eems %>%
select(-Month) %>%
filter(!is.na(secchi_depth_m)) %>%
rename(Month = date_ymd) %>%
ggplot(aes(lake_section, secchi_depth_m)) +
geom_boxplot() +
geom_point(aes(col = Month)) +
labs(x = "Lake section",
y = "Secchi depth (m)",
subtitle = "2019 Secchi depths")
eems %>%
select(-Month) %>%
filter(!is.na(turb_field_NTU)) %>%
rename(Month = date_ymd) %>%
ggplot(aes(lake_section, turb_field_NTU)) +
geom_boxplot() +
geom_point(aes(col = Month)) +
labs(x = "Lake section",
y = "Field turbidity (NTU)",
subtitle = "2019 field turbidity")
eems %>%
select(-Month) %>%
filter(!is.na(turb_lab_NTU)) %>%
rename(Month = date_ymd) %>%
ggplot(aes(lake_section, turb_lab_NTU)) +
geom_boxplot() +
geom_point(aes(col = Month)) +
labs(x = "Lake section",
y = "Lab turbidity (NTU)",
subtitle = "2019 lab turbidity")
# Linear models with distance ---------------------------------------------
eems %>%
rename(Site = site_code_long) %>%
group_by(Site, distHaversine_km, Year) %>%
summarise(DOC_mg.L = mean(DOC_mg.L, na.rm = TRUE)) %>%
ungroup() %>%
ggplot(aes(distHaversine_km, DOC_mg.L)) +
facet_wrap(~ Year) +
geom_point() +
geom_smooth(method = 'lm') +
theme(legend.position = 'bottom', axis.title.y = element_markdown()) +
labs(x = "Distance from Buffalo Pound Lake inflow (km)", y = DOC_lab)
dd_means <- eems %>%
group_by(distHaversine_km) %>%
summarise(DOC_mg.L = mean(DOC_mg.L, na.rm = TRUE)) %>%
ungroup()
dd_means_year <- eems %>%
group_by(distHaversine_km, Year) %>%
summarise(DOC_mg.L = mean(DOC_mg.L, na.rm = TRUE)) %>%
ungroup()
dd_means16 <- dd_means_year %>% filter(Year == "2016")
dd_means17 <- dd_means_year %>% filter(Year == "2017")
dd_means18 <- dd_means_year %>% filter(Year == "2018")
dd_means19 <- dd_means_year %>% filter(Year == "2019")
mm1 <- lm(dd_means$DOC_mg.L ~ dd_means$distHaversine_km)
summary(mm1) # R2 = 0.9484, p = 5.7777e-06 // y = 0.038293x + 5.010753
dd_means %>% ggplot(aes(distHaversine_km, DOC_mg.L)) + geom_point() + geom_smooth(method = 'lm')
mm16 <- lm(dd_means16$DOC_mg.L ~ dd_means16$distHaversine_km)
summary(mm16) # R2 = 0.4911, p = 0.02131 // y = 0.03241x + 6.03693
mm17 <- lm(dd_means17$DOC_mg.L ~ dd_means17$distHaversine_km)
summary(mm17) # R2 = 0.9231, p = 2.361e-05 // y = 0.059415x + 5.474772
mm18 <- lm(dd_means18$DOC_mg.L ~ dd_means18$distHaversine_km)
summary(mm18) # R2 = 0.8711, p = 0.0001468 // y = 0.033329x + 4.436347
mm19 <- lm(dd_means19$DOC_mg.L ~ dd_means19$distHaversine_km)
summary(mm19) # R2 = 0.7726, p = 0.001113 // y = 0.030489x + 4.573036 |
library(lubridate)
library(MASS)
library(moments)
#import data
datClose10 <- read.csv('D:/study/Y3.1/AUCC/FE+SML+EDA/dataset/Priceclose_2y_10.csv',header = T)
head(as.data.frame(datClose10))
#change chr -> date
datClose10 = datClose10 %>% mutate(Date = mdy(Date)) %>% arrange(Date)
head(datClose10)
str(datClose10)
#split data
index <- nrow(datClose10)*0.8
train <- datClose10[(1:index),]
test <- datClose10[-(1:index),]
#model (not select)
reg <- lm(Close ~ Close_1+Open_1+High_1+Low_1+Vol_1+Change_1+Close_2+Open_2+High_2+Low_2+Vol_2+Change_2+Close_3+Open_3+High_3+Low_3+Vol_3+Change_3+Close_4+Open_4+High_4+Low_4+Vol_4+Change_4+Close_5+Open_5+High_5+Low_5+Vol_5+Change_5+
Close_6+Open_6+High_6+Low_6+Vol_6+Change_6+Close_7+Open_7+High_7+Low_7+Vol_7+Change_7+Close_8+Open_8+High_8+Low_8+Vol_8+Change_8+Close_9+Open_9+High_9+Low_9+Vol_9+Change_9+Close_10+Open_10+High_10+Low_10+Vol_10+Change_10,data = train)
summary(reg)
par(mfrow=c(2,2))
plot(reg)
par(mfrow=c(1,1))
#transform
#model with log()
reg_l <- lm(log(Close)~ log(Close_1)+log(Open_1)+log(High_1)+log(Low_1)+log(Vol_1)+log(Close_2)+log(Open_2)+log(High_2)+log(Low_2)+log(Vol_2)+log(Close_3)+log(Open_3)+log(High_3)+log(Low_3)+log(Vol_3)+log(Close_4)+log(Open_4)+log(High_4)+log(Low_4)+log(Vol_4)+
log(Close_5)+log(Open_5)+log(High_5)+log(Low_5)+log(Vol_5)+log(Close_6)+log(Open_6)+log(High_6)+log(Low_6)+log(Vol_6)+log(Close_7)+log(Open_7)+log(High_7)+log(Low_7)+log(Vol_7)+log(Close_8)+log(Open_8)+log(High_8)+log(Low_8)+log(Vol_8)+
log(Close_9)+log(Open_9)+log(High_9)+log(Low_9)+log(Vol_9)+log(Close_10)+log(Open_10)+log(High_10)+log(Low_10)+log(Vol_10),data = train)
summary(reg_l)
par(mfrow=c(2,2))
plot(reg_l)
par(mfrow=c(1,1))
#model (selected features)
step.model <- stepAIC(reg_l, direction = "both", trace = FALSE)
summary(step.model)
par(mfrow=c(2,2))
plot(step.model)
par(mfrow=c(1,1))
#predict
pred.d10 <- predict(step.model,newdata=test)
#result
MSE <- mean(summary(step.model)$residuals^2)
R2 <- cor(test$Close,pred.d10)^2
RMSE <- sqrt(MSE)
MSE; R2; RMSE
#plot
pred.d10.table <- data.frame(test$Date,test$Close, pred.d10)
names(pred.d10.table)[1] = 'Date' ;names(pred.d10.table)[2] = 'Actual' ;names(pred.d10.table)[3] = 'Predict'
gp_d10 <- test %>% ggplot(aes(Date, Close)) + theme_bw()
gd10 <- gp_d10 + geom_line(data=test, aes(x = Date, y = log(Close))) +
geom_line(data = pred.d10.table, aes(x = Date, y = Predict),size = 1,color ="red")+
labs(title = 'Change Closing Price - d10', y = "", x = "") +
scale_y_continuous(breaks = c(0, 1250, 2500 , 3750, 5000),
labels = c('$0', '$1,250','2,500', '$3,750', '$5,000'))
gd10 |
<?php
namespace App\Http\Livewire\Venta;
use App\Models\Producto;
use App\Models\Tipo;
use App\Models\Venta;
use App\Models\Caja;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Throwable;
use Jantinnerezo\LivewireAlert\LivewireAlert;
class Modificar extends Component
{
use LivewireAlert;
public Venta $venta;
public $productos, $vendedores, $formasdepago, $descuentos;
public $vendedor, $cantidadprenda, $monto, $descripcion, $producto, $formadepago, $preciodeventa,$descuento,$cantidaddescuento;
public $opcionSeleccionada, $descuentoSeleccionado;
public $propiedades;
public function mount(){
$this->vendedores = Tipo::where('categoria','Vendedor')->get();
$this->formasdepago = Tipo::where('categoria','MedioPago')->get();
$this->descuentos = Tipo::where('categoria','Descuento')->get();
$this->productos = Producto::all();
$this->vendedor = $this->venta->vendedor;
$this->cantidadprenda = $this->venta->cantidadprenda;
$this->descripcion = $this->venta->descripcion;
$this->opcionSeleccionada = $this->venta->producto;
$this->formadepago = $this->venta->formadepago;
}
public function updatedOpcionSeleccionada()
{
// Verifica si la opción seleccionada no es nula antes de acceder a las propiedades
if ($this->opcionSeleccionada) {
$this->propiedades = Producto::where('id', $this->opcionSeleccionada)->first();
} else {
$this->propiedades = null;
}
}
public function submit() {
//$this->validate();
DB::beginTransaction();
try {
//dd($this->descripcion);
$montoAnterior = $this->venta->monto;
$this->venta->vendedor = $this->vendedor;
$this->venta->cantidadprenda = $this->cantidadprenda;
$this->venta->descripcion = $this->descripcion;
$this->venta->producto = $this->opcionSeleccionada;
$this->venta->formadepago = $this->formadepago;
$producto = Producto::where('id', $this->opcionSeleccionada)->first();
if($this->descuento === 'SI'){
$this->venta->descuento = $this->descuento;
$this->venta->cantidaddescuento = $this->cantidaddescuento;
//$descuentoaplicado = ($this->cantidaddescuento * $producto->precioFinal)/100;
$totalventa = $producto->precioFinal * $this->cantidadprenda;
$descuento = ($totalventa * $this->cantidaddescuento)/100;
$this->venta->monto = $totalventa - $descuento;
$caja = Caja::latest()->first();
$caja->valor -= $montoAnterior;
$caja->valor += $this->venta->monto;
$caja->save();
}
else{
$this->venta->descuento = $this->descuento;
$this->venta->monto = ($producto->precioFinal*$this->cantidadprenda);
$caja = Caja::latest()->first();
$caja->valor -= $montoAnterior;
$caja->valor += $this->venta->monto;
$caja->save();
}
$this->venta->save();
$producto->cantidad = $producto->cantidad - $this->cantidadprenda;
$producto->save();
DB::commit();
return $this->flash('success', 'Venta agregada', [
'position' => 'top',
'toast' => true,
], route('venta.listado'));
} catch (Throwable $e) {
dd($e);
DB::rollBack();
return $this->alert('error', 'Error', [
'position' => 'top',
]);
}
}
public function render()
{
if ($this->opcionSeleccionada) {
$this->propiedades = Producto::where('id', $this->opcionSeleccionada)->first();
} else {
$this->propiedades = null;
}
$this->descuentoSeleccionado = $this->descuento;
return view('livewire.venta.modificar');
}
} |
package io.ensueno.kafka.consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConsumerWithMultiThread {
private static String TOPIC_NAME = "test";
private static String GROUP_ID = "test";
private static String BOOTSTRAP_SERVERS = "localhost:9092";
private static int CONSUMER_COUNT = 3;
private static List<ConsumerWorker> workerThreads = new ArrayList<>();
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new ShutdownThread());
Properties configs = new Properties();
configs.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS);
configs.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP_ID);
configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i=0; i<CONSUMER_COUNT; i++){
ConsumerWorker worker = new ConsumerWorker(configs, TOPIC_NAME, i);
workerThreads.add(worker);
executorService.execute(worker);
}
}
static class ShutdownThread extends Thread {
public void run() {
workerThreads.forEach(ConsumerWorker::shutdown);
System.out.println("Bye");
}
}
} |
---
layout: '../../layouts/Post.astro'
title: Is Coding For You?
description: Before you jump into it, it's important to weigh the pros and cons and understand the reality of what it takes to become a successful programmer.
publishDate: April 18, 2023
featuredImage: '/assets/images/blog/is-coding-for-you/featured.png'
showFeaturedImageOnPostPage: false
excerpt: Before you jump into it, it's important to weigh the pros and cons and understand the reality of what it takes to become a successful programmer.
tags: ['Dev Careers', 'Roadmap']
---
import YTEmbed from '../../components/YTEmbed.astro';
<YTEmbed videoId="znY8kzDYgOk" />
_Prefer video format? [Watch it on YouTube.](https://youtu.be/znY8kzDYgOk)_
---
Software development has become one of the most sought-after career paths in recent years, but before you jump into it, it's important to weigh the pros and cons and understand the reality of what it takes to become a successful programmer.
So, let's start with the pros of coding as a career.
### The Pros
> You can enjoy a flexible work schedule and have a good work-life balance.
Firstly, coding is a **high-demand job**. With the increasing use of technology in various industries, the demand for skilled programmers has grown exponentially. This means that there are plenty of job opportunities available in this field.

There's a whole bunch of people who believe that as artificial intelligence becomes more sophisticated, programming as a skill will no longer will valuable. I'm definitely not one of the doomsayers. I think rather than taking jobs away from developers, AI will more likely complement their existing skill sets as a good friend or an assistant. So, developers who learn to delegate the boring or repetitive parts to AI technologies such as ChatGPT will have that extra edge and be more productive at work.
Secondly, coding is a **well-paid job**. Programmers are some of the highest-paid professionals in the job market. If you have the skills and experience, you can earn a great salary and enjoy a comfortable lifestyle.
Thirdly, coding is a career that allows you to **work remotely**. Many software development jobs can be done from anywhere in the world as long as you have a stable internet connection. This means that you can enjoy a flexible work schedule and have a good work-life balance.
Now, let's talk about the cons of coding as a career.
### The Cons
> This can be tiring and can lead to burnout if you're not careful.

Firstly, coding can be **frustrating** at times. Programming is a complex process that involves a lot of trial and error. You may spend hours or even days working on a code only to find out that it doesn't work. This can be demotivating and frustrating.
Secondly, coding can be **mentally exhausting**. It requires you to think critically and creatively to solve problems. This can be tiring and can lead to burnout if you're not careful.
Thirdly, coding requires **continuous learning**. The technology landscape is constantly changing, and as a programmer, you need to keep up with the latest trends and technologies to stay relevant in the job market.
Now, let's talk about the reality of coding as a career.
### The Reality
Many people have the misconception that programming is _all about writing lines of code_. However, in reality, coding is just one part of the actual job: software engineering. It's kind of naive to think that as a developer spinning out code is all you'll be doing the whole day. In reality, you will be spending much more time on other related things such as planning & estimating your work, setting up & constantly adjusting your local and test environments, documenting your code, going into meetings, and much more.

Also, as a programmer, you will work with complex problems at some point, which will require plenty of logical and analytical thinking. When that happens, you will spend more time thinking than writing code.
### So, Is It For You?
All said and done, is coding for everyone?
I am a strong believer in the idea that anyone can learn to code. But being a programmer suits certain personality types more than others. If you enjoy problem-solving, critical thinking, and attention to detail, you may enjoy coding as a career. However, if you're not interested in these things, programming may be tedious and frustrating.
### Conclusion
**Coding can be a great career path for those who enjoy making computers work for them to solve real-world problems.** It can be financially rewarding and offer a flexible work schedule. However, it requires a certain mindset and a continuous desire to learn and improve.
So, if you're considering software development as a career, ask yourself if you enjoy problem-solving and if you're willing to put in the effort to continuously learn and improve. If the answer is yes, then coding may be the perfect career for you.
### Next
In the <a href="/posts/career-paths">next video</a>, we'll look at the different career paths to see what excites you the most. |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class ProcessRecord extends Model
{
use HasFactory;
/**
* @var string
*/
protected $table = 'process_records';
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'run',
'type',
'reference',
'retain_days',
'created_at'
];
// If you want to use dates casting for the property
protected $dates = [
'retain_days',
];
/**
* @var string
*/
protected $run;
/**
* @var string
*/
protected $type;
/**
* @var string
*/
protected $reference;
public function client(): BelongsTo
{
return $this->belongsTo(Client::class);
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function process(): BelongsTo
{
return $this->belongsTo(Process::class);
}
public function processStatus(): BelongsTo
{
return $this->belongsTo(ProcessStatus::class);
}
public function processRecordTagValues(): HasMany
{
return $this->hasMany(ProcessRecordTagValue::class);
}
public function processRecordValues(): HasMany
{
return $this->hasMany(ProcessRecordValue::class);
}
public function delete(): bool|null
{
$this->processRecordValues()->delete();
$this->processRecordTagValues()->delete();
return parent::delete();
}
public function addValue(string $value): void
{
$recordValue = new ProcessRecordValue;
$recordValue->value = $value;
$this->processRecordValues()->save($recordValue);
}
public function updateTags(?array $tags): void
{
$this->processRecordTagValues()->delete();
$this->processRecordTagValues()->saveMany(collect($tags)->map(function ($tagValue, $tagName) {
$tag = Tag::firstOrCreate(['name' => $tagName]);
$tagValue = new ProcessRecordTagValue(['value' => $tagValue]);
$tagValue->tag_id = $tag->id;
return $tagValue;
}));
}
public function getTagsAssocArray(): array
{
return $this->processRecordTagValues->pluck('value', 'tag.name')->toArray();
}
public function getValuesArray(): array {
return $this->processRecordValues->pluck('value')->toArray();
}
public function scopeBelongsToUser($query, $user)
{
return $query->where($this->table . '.user_id', $user->id);
}
public function scopeBelongsToProcess($query, $process)
{
return $query->where($this->table . '.process_id', $process->id);
}
} |
import { inject } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { CalculadoraService } from './calculadora.service';
describe('CalculadoraService', () => {
let service: CalculadoraService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(CalculadoraService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('deve garantir que 1 + 4 = 5', () => {
let sum = service.calcular(1, 4, CalculadoraService.sum);
expect(sum).toEqual(5);
});
it('deve garantir que 1 - 4 = -3', () => {
let sub = service.calcular(1, 4, CalculadoraService.subtraction);
expect(sub).toEqual(-3);
});
it('deve garantir que 1 / 4 = 2', () => {
let div = service.calcular(1, 4, CalculadoraService.division);
expect(div).toEqual(0.25);
});
it('deve garantir que 4 * 2 = 8', () => {
let mult = service.calcular(4, 2, CalculadoraService.multiplication);
expect(mult).toEqual(8);
});
it('deve retornar 0 para operação inválida', () => {
let operacaoInvalida = service.calcular(1, 4, '$');
expect(operacaoInvalida).toEqual(0);
});
}); |
import React, { useState, useEffect } from 'react';
import Header from './components/Header'
import Formulario from './components/Formulario'
import Error from './components/Error'
import Clima from './components/Clima'
function App() {
//state Principal (en lugar de 1 state grande, lo divido en varias piezas)
const [ciudad, guardarCiudad] = useState('');
const [pais, guardarPais] = useState('');
const [error, guardarError] = useState(false);
const [resultado, guardarResultado] = useState({})
//lo que va entre corchetes en useEffect es que parte del state tiene que escuchar
//el use effect para ejecutarse (se ejecuta cuando el comp esta listo o cuando hay cambios)
useEffect(() => {
//prevenir la ejecucion automatica
if(ciudad === ''){
return;
}else{
const consultarAPI = async () => {
const appId = '82e3357b7cf4d402f4251d3b3de7c28d';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${ciudad},${pais}&appid=${appId}`;
//consultar la url
const respuesta = await fetch(url);
const resultado = await respuesta.json();
guardarResultado(resultado);
}
consultarAPI();
}
}, [ ciudad, pais ]);
//funcion a pasar a formulario para tomar los datos
const datosConsulta = datos => {
//validar que ambos campos esten
if(datos.ciudad === '' || datos.pais === '') {
//un error
guardarError(true);
return;
}
//ciudad y pais existen, agregarlos al state
guardarCiudad(datos.ciudad);
guardarPais(datos.pais);
guardarError(false);
}
//cargar un componente condicionalmente
let componente;
if(error){
//hay un error, mostrarlo
componente = <Error mensaje="Ambos campos son obligatorios" />
} else if (resultado.cod === '404'){
componente = <Error mensaje="La ciudad no existe en nuestro registro" />
} else {
//mostrar el clima
componente = <Clima
resultado={resultado}
/>;
}
return (
<div className="App">
<Header
titulo='Clima React App'
/>
<div className="contenedor-form">
<div className="container">
<div className="row">
<div className="col s12 m6">
<Formulario
datosConsulta={datosConsulta}
/>
</div>
<div className="col s12 m6">
{componente}
</div>
</div>
</div>
</div>
</div>
);
}
export default App; |
import { IsEmail, IsNotEmpty, IsOptional, IsString } from 'class-validator';
import { ERole } from 'src/core/enum/default.enum';
export class VUserRegisterDto {
@IsString()
@IsNotEmpty()
name: string;
@IsEmail()
@IsNotEmpty()
email: string;
@IsString()
@IsNotEmpty()
password: string;
@IsString()
@IsOptional()
role: ERole;
} |
import BaseService from '@/core/api/BaseService';
import moment from 'moment';
import GamesService from '@/app/services/gameService';
class HomeService extends BaseService {
request: any;
BASE_URL = process.env.BASE_URL;
constructor(params?: any) {
super(params);
this.setRequest();
}
getTagsPopular = () => {
const api = '/tags';
return this.request.get(api);
};
getHotGame = () => {
const api = '/games/hot?populate=*';
return this.request.get(api);
};
getRandomGames = (slug: string) => {
const api = `/games/random?filters[slug][$ne]=${slug}&populate=*`;
return this.request.get(api);
}
getRecommendedGames = () => {
let api: string;
const playedCategoriesGames = GamesService.getPlayedCategoriesGames();
if (playedCategoriesGames && playedCategoriesGames.length > 0) {
api = '/games?populate=*&' + GamesService.getRandomPlayedCategoryGame();
} else {
api =
'/games?sort[1]=play_count:desc&sort[0]=publishedAt:desc&populate=*';
}
return this.request.get(api);
};
getRecentlyPlayedGames = () => {
let api: string = '';
const playedGames = GamesService.getIdPlayedGames();
if (playedGames && playedGames.length > 0) {
api = '/games?populate=*&' + GamesService.getRecentlyPlayedGame();
}
return this.request.get(api);
};
getPopularGame = () => {
const api =
'/games?sort[1]=play_count%3Adesc&pagination[pageSize]=56&populate=*';
return this.request.get(api);
};
getPopularGameWeek = () => {
const api = '/games?sort[0]=play_count:desc&populate=*';
return this.request.get(api);
};
getNewGame = () => {
const api = `/games?sort[1]=updatedAt:desc&populate=*`;
return this.request.get(api);
};
getDetailGameById = (id: string) => {
const api = `/games/${id}?populate=*`;
return this.request.get(api);
};
getDetailGameBySlug = (slug: string) => {
const api = `/games?populate=*&filters[slug]=${slug}`;
return this.request.get(api);
};
getCategories = () => {
const api = '/categories?populate=*';
return this.request.get(api);
};
getGameByCategorySlug = (slug: string) => {
const api = `/games?populate=*&filters[categories][slug]=${slug}`;
return this.request.get(api);
};
getCategoryBySlug = (slug: string) => {
const api = `/categories?filters[slug]=${slug}`;
return this.request.get(api);
};
getGamesByTag = (slug: string) => {
const api = `/games?filters[tags][slug][$eq]=${slug}&populate=*`;
return this.request.get(api);
};
getBannerHotGame = () => {
const api =
'/games/featured?populate=*&sort%5B0%5D=createdAt:desc&pagination%5Blimit%5D=1';
return this.request.get(api);
};
}
export const homeService = new HomeService(); |
import { createContext, useReducer } from "react";
import Cookies from "js-cookie";
export const Store = createContext();
const initialState = {
cart: Cookies.get('cart')
? JSON.parse(Cookies.get('cart'))
: { cartItems: [], shippingAddress: {} },
};
function reducer(state, action) {
switch (action.type) {
case "CART_ADD_ITEM": {
const newItem = action.payload;
const existItem = state.cart.cartItems.find(
(item) => item.slug === newItem.slug
);
const cartItems = existItem
? state.cart.cartItems.map((item) =>
item.name === existItem.name ? newItem : item
)
: [...state.cart.cartItems, newItem];
Cookies.set('cart', JSON.stringify({ ...state.cart, cartItems }));
return { ...state, cart: { ...state.cart, cartItems } };
}
case "CART_REMOVE_ITEM": {
const cartItems = state.cart.cartItems.filter(
(item) => item.slug !== action.payload.slug ///
);
Cookies.set('cart', JSON.stringify({ ...state.cart, cartItems }));
return { ...state, cart: { ...state.cart, cartItems } };
}
case 'CART_RESET':
return {
...state,
cart: {
cartItems: [],
shippingAddress: { location: {}},
paymentMethod: '',
},
}
case 'CART_CLEAR_ITEMS':
return {...state, cart: { ...state.cart, cartItems: []}}
case 'SAVE_SHIPPING_ADDRESS':
return {
...state,
cart: {
...state.cart,
shippingAddress: {
...state.cart.shippingAddress,
...action.payload,
},
},
}
case 'SAVE_PAYMENT_METHOD':
return {
...state,
cart: {
...state.cart,
paymentMethod: action.payload
},
}
default:
return state;
}
}
export function StoreProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
const value = { state, dispatch };
return <Store.Provider value={value}>{children}</Store.Provider>;
}
// This code creates a React context called "Store" and a "StoreProvider" component that provides the state and a dispatch function to its children components. The state is initialized with an object containing a "cart" property that is either an empty cart or the cart stored in a browser cookie, and this state can be updated by dispatching actions to a reducer function. The reducer function handles different types of actions that can be dispatched, such as adding or removing an item from the cart, resetting the cart, saving shipping address and payment method. The updated state is then stored back into the cookie and returned as a new state. |
'use client';
import React, { useState } from 'react';
import { useAppDispatch } from '@/lib/hooks';
import { fetchGeo } from '@/lib/features/geoSlice';
import Formulario from './_components/Formulario';
import Resultados from './_components/Resultados';
import dynamic from 'next/dynamic';
const MapaComponent = dynamic(() => import('./_components/Mapa'), { ssr: false });
const Home: React.FC = () => {
const [coordinates, setCoordinates] = useState({ lat: 34.04915, lng: -118.09462 });
const dispatch = useAppDispatch();
const handleSubmit = (inputValue: string) => {
fetch(`https://geo.ipify.org/api/v2/country,city?apiKey=${process.env.NEXT_PUBLIC_API_KEY}&ipAddress=${inputValue}`)
.then(response => response.json())
.then(data => {
const { lat, lng } = data.location;
setCoordinates({ lat, lng });
// Dispatch action to update geo data in Redux store
dispatch(fetchGeo(inputValue));
})
.catch(error => console.error('Error fetching geo data:', error));
};
return (
<main className="flex flex-col items-center justify-between">
<header className="flex flex-col items-center justify-center gap-4 w-full pt-10 px-10 pb-32">
<h1 className="font-bold text-white text-xl">IP Address Tracker</h1>
<Formulario onSubmit={handleSubmit} />
</header>
<section className="relative flex items-center justify-center w-full">
<Resultados />
</section>
<MapaComponent lat={coordinates.lat} lng={coordinates.lng} />
</main>
);
};
export default Home; |
import Segment from "./Segment";
export default interface FareCalculator {
next?: FareCalculator;
calculate (segment: Segment): number;
}
export class NormalFareCalculator implements FareCalculator {
FARE = 2.1;
constructor (readonly next?: FareCalculator) {
}
calculate(segment: Segment): number {
if (!segment.isOvernight() && !segment.isSunday()) {
return segment.distance * this.FARE;
}
if (!this.next) throw new Error();
return this.next.calculate(segment);
}
}
export class OvernightFareCalculator implements FareCalculator {
FARE = 3.9;
constructor (readonly next?: FareCalculator) {
}
calculate(segment: Segment): number {
if (segment.isOvernight() && !segment.isSunday()) {
return segment.distance * this.FARE;
}
if (!this.next) throw new Error();
return this.next.calculate(segment);
}
}
export class SundayFareCalculator implements FareCalculator {
FARE = 2.9;
constructor (readonly next?: FareCalculator) {
}
calculate(segment: Segment): number {
if (!segment.isOvernight() && segment.isSunday()) {
return segment.distance * this.FARE;
}
if (!this.next) throw new Error();
return this.next.calculate(segment);
}
}
export class OvernightSundayFareCalculator implements FareCalculator {
FARE = 5;
constructor (readonly next?: FareCalculator) {
}
calculate(segment: Segment): number {
if (segment.isOvernight() && segment.isSunday()) {
return segment.distance * this.FARE;
}
if (!this.next) throw new Error();
return this.next.calculate(segment);
}
} |
/*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), an agency of the Federal Government.
* Pursuant to title 15 Untied States Code Section 105, works of NIST
* employees are not subject to copyright protection in the United States
* and are considered to be in the public domain. As a result, a formal
* license is not needed to use the software.
*
* This software is provided by NIST as a service and is expressly
* provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement
*
* .
*
*/
/*****************************************************************************
* PRODUCT OF PT INOVACAO - EST DEPARTMENT and Aveiro University - Portugal) *
*****************************************************************************/
package gov.nist.javax.sdp.fields;
import java.util.Vector;
import javax.sdp.SdpException;
import javax.sdp.SdpParseException;
import gov.nist.core.NameValue;
/**
* Precondition fields (segmented / end-to-end).
*
* <p>For one media description, precondition attributes should
* be only of one type (segmented or end-to-end) </p>
* <p>3GPP TS 24.299, </p>
* IETF RFC3312 + RFC4032 (Precondition Mechanism).
*
* @author Miguel Freitas (IT) PT-Inovacao
*/
public class PreconditionFields
{
// Media Description attributes for precondition
protected Vector preconditionAttributes;
/**
* Constructor
*
*/
public PreconditionFields()
{
preconditionAttributes = new Vector();
}
/**
* Get the number of Precondition attributes
*
* @return int size of segmented precondition vector of attribute fields
*/
public int getPreconditionSize()
{
if (preconditionAttributes != null)
return preconditionAttributes.size();
else // TODO treat this exception well
return -1;
}
/**
* Get Precondition
*
* @return Vector of attribute fields (segmented precondition)
*/
public Vector getPreconditions()
{
return preconditionAttributes;
}
/**
* Set Preconditions
*
* @param preconditions - vector with precondition attributes
* @throws SdpException -- if precondition attributes is null
*/
public void setPreconditions(Vector preconditions) throws SdpException
{
if (preconditions == null)
throw new SdpException("Precondition attributes are null");
else
preconditionAttributes = preconditions;
}
/**
* <p>Set attribute line for current precondition state, given
* a string value encoded like the "curr" attribute value</p>
*
* @param precondCurrValue - a string with the value for a "curr" attribute
* @throws SdpException
*/
public void setPreconditionCurr(String precondCurrValue) throws SdpException
{
if (precondCurrValue == null)
throw new SdpException("The Precondition \"curr\" attribute value is null");
else if (preconditionAttributes == null)
throw new SdpException("The Precondition Attributes is null");
else
{
try
{
/* split the "curr" attribute value into words
* attributes[0] = "qos"
* attributes[1] = status-type (e2e/local/remote)
* attributes[2] = direction-tag (none/send/recv/sendrecv)
*
* split() - regular expression:
* \s -> a whitespace character [ \t\n\x0B\f\r]
* \b -> a word boundary
*/
String[] attributes = precondCurrValue.split(" ");
// which is this length?! of the string or the []?
/*
if (attributes.length < 3)
{
throw new SdpException
("The Precondition \"curr\" attribute value mal-formed (<3words)");
}*/
setPreconditionCurr(attributes[1], // status-type
attributes[2] // direction-tag
);
}
catch (ArrayIndexOutOfBoundsException ex)
{
throw new SdpException
("Error spliting the \"curr\" attribute into words", ex);
}
}
}
/**
* <p>Set the value of the attributes with the name "curr"
* for current precondition.</p>
* <p>- eg: a=curr:qos local none</p>
*
* <p>If there is an attribute "curr" for the same status-type,
* the direction-tag is updated with the one supplied.</p>
*
* @param status - (local, remote, e2e)
* @param directionTag - (none, send, recv, sendrecv)
* @throws SdpParseException
*/
public void setPreconditionCurr(String status, String directionTag)
throws SdpException
{
if (status == null)
throw new SdpException("The status-type is null");
if (directionTag == null)
throw new SdpException("The direction-tag is null");
if (preconditionAttributes == null)
throw new SdpException("Precondition Attributes is null");
int i = 0;
// search for attributes "curr"
for (i = 0; i < preconditionAttributes.size(); i++)
{
AttributeField af =
(AttributeField) this.preconditionAttributes.elementAt(i);
// go to next attribute if this is not "curr"
if (!af.getAttribute().getName().equals("curr"))
continue;
// if it is "curr" attribute, check the status-type
// if it matches the value supplied, update the direction-tag
// with the value supplied
if (af.getValue().indexOf(status) != -1)
{
if (af.getValue().indexOf(directionTag) == -1)
{
// attribute exists with same status, directionTag updated
af.setValue("qos " + status + " " + directionTag);
preconditionAttributes.setElementAt(af,i);
}
// else, exit and do nothing (attribute already exists)
else
break;
}
}
// attribute "curr" not found
if (i == preconditionAttributes.size())
{
// create attribute for the status-type supplied
NameValue nv = new NameValue("curr", "qos " + status + " " + directionTag);
AttributeField newAF = new AttributeField();
newAF.setAttribute(nv);
preconditionAttributes.add(newAF);
}
}
/**
* <p>Set attribute line for desired precondition state, given
* a string value encoded like the "des" attribute value</p>
*
* @param precondDesValue - a string with the value for a "des" attribute
* @throws SdpException
*/
public void setPreconditionDes(String precondDesValue) throws SdpException
{
if (precondDesValue == null)
throw new SdpException("The Precondition \"des\" attribute value is null");
else if (preconditionAttributes == null)
throw new SdpException("The Precondition Attributes is null");
else
{
/* split the "des" attribute value into words
* attributes[0] = "qos"
* attributes[1] = strength-tag (unknown/failure/none/optional/mandatory)
* attributes[2] = status-type (e2e/local/remote)
* attributes[3] = direction-tag (none/send/recv/sendrecv)
*
* split() - regular expression:
* \s -> a whitespace character [ \t\n\x0B\f\r]
* \b -> a word boundary
*/
try
{
String[] attributes = precondDesValue.split(" ");
// which is this length?! of the string or the []?
/*
if (attributes.length < 4)
{
throw new SdpException
("The Precondition \"des\" attribute value mal-formed (<4words)");
}*/
setPreconditionDes( attributes[1], // strength-tag
attributes[2], // status-type
attributes[3] // direction-tag
);
}
catch (ArrayIndexOutOfBoundsException ex)
{
throw new SdpException
("Error spliting the \"des\" attribute into words", ex);
}
}
}
/**
* <p>Set the value of the attributes with the name "des"
* for desired precondition. </p>
* <p>- eg: a=des:qos mandatory remote sendrecv</p>
*
* <p>There can be more than one desired precondition line
* for a status-type, specially if strength-tag is different.</p>
*
* <p>If there is an attribute "des" for the same status-type,
* the strength-tag and direction-tag are updated with the
* ones supplied.<p>
*
* <p>IETF RFC4032: strength should only be downgraded within SDP offers</p>
*
*
* @param strength - (none, optional,
* @param status - (local, remote, e2e)
* @param direction - (none, send, recv, sendrecv)
* @throws SdpParseException
*/
public void setPreconditionDes(String strength, String status, String direction)
throws SdpException
{
if (strength == null)
throw new SdpException("The strength-tag is null");
if (status == null)
throw new SdpException("The status-type is null");
if (direction == null)
throw new SdpException("The direction-tag is null");
if (preconditionAttributes == null)
throw new SdpException("Precondition Attributes is null");
int i = 0;
// search for attributes "des"
for (i = 0; i < preconditionAttributes.size(); i++)
{
AttributeField af =
(AttributeField) this.preconditionAttributes.elementAt(i);
// go to next attribute if this is not "des"
if (!af.getAttribute().getName().equals("des"))
continue;
// if it is "des" attribute, check the status-type
// if it match, update the strength-tag and direction-tag
if (af.getValue().indexOf(status) != -1)
{
// attribute exists with same status-type,
// strength-tag and direction-tag updated
af.setValue("qos " + strength + " " + status + " " + direction);
preconditionAttributes.setElementAt(af,i);
}
}
// attribute "des" not found
if (i == preconditionAttributes.size())
{
// create attribute for the status-type supplied
// with the values strength-tag and direction-tag
NameValue nv =
new NameValue("des", "qos " + strength + " " + status + " " + direction);
AttributeField newAF = new AttributeField();
newAF.setAttribute(nv);
preconditionAttributes.add(newAF);
}
}
/**
* <p>Set attribute line for confirmation precondition request, given
* a string value encoded like the "conf" attribute value</p>
*
* @param precondConfValue - a string with the value for a "conf" attribute
* @throws SdpException
*/
public void setPreconditionConfirmStatus(String precondConfValue)
throws SdpException
{
if (precondConfValue == null || precondConfValue.length()==0)
throw new SdpException("The Precondition \"conf\" attribute value is null");
else if (preconditionAttributes == null)
throw new SdpException("The Precondition Attributes is null");
else
{
/* split the "conf" attribute value into words
* attributes[0] = "qos"
* attributes[1] = status-type (e2e/local/remote)
* attributes[2] = direction-tag (none/send/recv/sendrecv)
*/
try
{
String[] attributes = precondConfValue.split(" ");
setPreconditionConfirmStatus(
attributes[1], // status-type
attributes[2] // direction-tag
);
}
catch (ArrayIndexOutOfBoundsException ex)
{
throw new SdpException
("Error spliting the \"conf\" attribute into words", ex);
}
}
}
/**
* <p>IETF RFC3312</p>
* <p>"The confirmation status attribute carries threshold conditions
* for a media stream. When the status of network resources reach
* these conditions, the peer UA will send an update of the
* session description".</p>
*
* <p>- eg: a=conf:qos remote sendrecv</p>
*
* @param status - (e2e, local, remote)
* @param direction - (none, send, recv, sendrecv)
* @throws SdpException -- if param are null
*/
public void setPreconditionConfirmStatus(String status, String direction)
throws SdpException
{
if (status == null || direction.length()==0)
throw new SdpException("The status-type is null");
if (direction == null || direction.length()==0)
throw new SdpException("The direction-tag is null");
if (preconditionAttributes == null)
throw new SdpException("Precondition Attributes is null");
int i = 0;
// search for attributes "conf"
for (i = 0; i < preconditionAttributes.size(); i++)
{
AttributeField af =
(AttributeField) this.preconditionAttributes.elementAt(i);
//System.out.println("--> PreconditionField -> (i="+i+") > attribute field: " + af.toString());
// go to next attribute if this is not "conf"
if (!af.getAttribute().getName().equals("conf"))
continue;
// if it is "conf" attribute, check the status-type
// if it matches, update the direction-tag
// with the value supplied
if (af.getValue().indexOf(status) != -1)
{
if (af.getValue().indexOf(direction) == -1)
{
// attribute exists with same status, directionTag updated
af.setValue("qos " + status + " " + direction);
preconditionAttributes.setElementAt(af,i);
}
// else, exit and do nothing (attribute already exists)
break;
}
}
// attribute "conf" not found
if (i == preconditionAttributes.size())
{
// create attribute for the status-type supplied
// with the values strength-tag and direction-tag
NameValue nv =
new NameValue("conf", "qos " + status + " " + direction);
AttributeField newAF = new AttributeField();
newAF.setAttribute(nv);
preconditionAttributes.add(newAF);
//System.out.println("--> PreconditionField -> new \"conf\" attribute created: " + newAF.toString() );
}
}
/**
* <p>Get the attribute fields with the name "curr"
* for current precondition.</p>
* <p>One attribute field per status-type.
* (eg: a=curr:qos local none)</p>
*
* @param status - (local, remote, e2e)
* @return a vector with the attribute field that match status-type
* (with only one element or null if none exists)
* @throws SdpParseException
*/
public Vector getPreconditionCurr(String status)
throws SdpException, SdpParseException
{
if (status == null)
throw new SdpException("The status-type is null");
if (preconditionAttributes == null)
return null;
else
{
Vector vCurr = new Vector();
for (int i=0; i < preconditionAttributes.size(); i++)
{
AttributeField af =
(AttributeField) this.preconditionAttributes.elementAt(i);
// go to next attribute if this is not "curr"
if (!af.getAttribute().getName().equals("curr"))
continue;
// if it is "curr" attribute, check the status-type
// and add the attribute value to the vector if it
// matches the status desired
if (af.getValue().indexOf(status) != -1)
vCurr.addElement(af);
}
// if none "curr" attribute found
if (vCurr.size() == 0)
return null;
else
return vCurr;
}
}
/**
* <p>Get the attribute fields with the name "des"
* for desired precondition</p>
*
* <p>There can be more than one current precondition line
* for a status-type (with different direction-tag values),
* specially if strength-tag is different</p>
*
* @param status - (local, remote, e2e)
* @return a vector with the attribute fields that match location-tag
* @throws SdpParseException
*/
public Vector getPreconditionDes(String status)
throws SdpException, SdpParseException
{
if (status == null)
throw new SdpException("The status-type is null");
if (preconditionAttributes == null)
return null;
else
{
Vector vCurr = new Vector();
for (int i=0; i < preconditionAttributes.size(); i++)
{
AttributeField af =
(AttributeField) this.preconditionAttributes.elementAt(i);
// go to next attribute if this is not "des"
if (!af.getAttribute().getName().equals("des"))
continue;
// if it is "des" attribute, check the status-type
// and add the attribute value to the vector if it
// matches the status desired
if (af.getValue().indexOf(status) != -1)
vCurr.addElement(af);
}
// if none "des" attribute found
if (vCurr.size() == 0)
return null;
else
return vCurr;
}
}
/**
* <p>Get the attribute fields with the name "conf"
* for confirmation precondition.</p>
*
* <p>IETF RFC3312</p>
* <p>"The confirmation status attribute carries threshold conditions
* for a media stream. When the status of network resources reach
* these conditions, the peer UA will send an update of the
* session description".</p>
*
* <p>(eg: a=conf:qos remote sendrecv)</p>
*
* @return a vector with the "conf" attribute fields
* @throws SdpException
*/
public Vector getPreconditionConfirmStatus() throws SdpException
{
if (preconditionAttributes == null)
return null; // ignore or send SdpException?
else
{
Vector vCurr = new Vector();
for (int i=0; i < preconditionAttributes.size(); i++)
{
AttributeField af =
(AttributeField) this.preconditionAttributes.elementAt(i);
// go to next attribute if this is not "conf"
if (!af.getAttribute().getName().equals("conf"))
continue;
else
// add the attribute value to the vector
vCurr.addElement(af);
}
// if none "conf" attribute found
if (vCurr.size() == 0)
return null;
else
return vCurr;
}
}
/* strength-tag */
public static final int STRENGTH_UNKNOWN = 0;
public static final int STRENGTH_FAILURE = 1;
public static final int STRENGTH_NONE = 2;
public static final int STRENGTH_OPTIONAL = 3;
public static final int STRENGTH_MANDATORY = 4;
public static final String[] STRENGTH = { "unknown",
"failure",
"none",
"optional",
"mandatory"
};
/* direction-tag */
public static final int DIRECTION_NONE = 0;
public static final int DIRECTION_SEND = 1;
public static final int DIRECTION_RECV = 2;
public static final int DIRECTION_SENDRECV = 3;
public static final String[] DIRECTION = { "none",
"send",
"recv",
"sendrecv"
};
/* status-tag */
public static final int STATUS_E2E = 0;
public static final int STATUS_LOCAL = 1;
public static final int STATUS_REMOTE = 2;
public static final String[] STATUS = { "e2e",
"local",
"remote"
};
/* precondition type */
public static final int PRECONDITION_QOS = 0;
public static final String[] PRECONDITION = { "qos"
};
} |
import { useState, useEffect } from "react";
import { Button, Form } from "react-bootstrap";
const Login = ({ setShowForm, setUser }) => {
const [admins, setAdmins] = useState([]);
const [error, setError] = useState();
const [userInfo, setUserInfo] = useState({
username: "",
password: "",
});
const handlePassword = (event) => {
const password = event.target.value;
setUserInfo((userInfo) => ({ ...userInfo, password }));
};
const handleUsername = (event) => {
const username = event.target.value;
setUserInfo((userInfo) => ({ ...userInfo, username }));
};
const handleSubmit = (e) => {
e.preventDefault();
if (verifyLogin()) {
setError(false);
setShowForm(true);
setUser(userInfo.username);
} else {
setError(true);
}
};
const verifyLogin = () => {
let flag = false;
for (let admin of admins) {
console.log(admin["username"] === userInfo.username);
console.log(admin["password"] === userInfo.password);
if (
admin["username"] === userInfo.username &&
admin["password"] === userInfo.password
) {
flag = true;
}
}
return flag;
};
useEffect(() => {
getAdmins();
}, []);
// get request to get existing admins
async function getAdmins() {
await fetch("http://localhost:8080/admins")
.then((response) => response.json())
.then((reviews) => {
setAdmins(reviews);
});
}
return (
<>
<div className="LoginFormDiv">
<h1 className="CreateFormTitle">Login to Create Post</h1>
<div className="LoginForm">
<Form className="loginformForm" onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Username</Form.Label>
<input
type="text"
id="username"
placeholder="Username"
required
value={userInfo.username || ""}
onChange={handleUsername}
/>
</Form.Group>
<Form.Group>
<Form.Label>Password</Form.Label>
<br></br>
<input
type="password"
id="password"
placeholder="Password"
required
value={userInfo.password || ""}
onChange={handlePassword}
/>
</Form.Group>
<Form.Group>
<Button
type="submit"
variant="outline-success"
style={{ marginTop: "10px" }}
>
Login
</Button>
</Form.Group>
</Form>
</div>
{error ? (
<div>
<p style={{ color: "red", marginTop: "10px" }}>
Incorrect password or username
</p>
</div>
) : null}
</div>
</>
);
};
export default Login; |
/**
* @ (#) HospitalFeedbackAction.javaSep 20, 2005
* Project : TTK HealthCare Services
* File : HospitalFeedbackAction.java
* Author : Chandrasekaran J
* Company : Span Systems Corporation
* Date Created : Sep 20, 2005
*
* @author : Chandrasekaran J
* Modified by : Nagaraj D V
* Modified date : Jan 19, 2006
* Reason : To reduce the table data related code in action class
*/
package com.ttk.action.empanelment;
import java.util.ArrayList;
import java.util.HashMap;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.validator.DynaValidatorForm;
import com.ttk.action.TTKAction;
import com.ttk.action.table.TableData;
import com.ttk.business.empanelment.HospitalManager;
import com.ttk.common.TTKCommon;
import com.ttk.common.exception.TTKException;
import com.ttk.common.security.Cache;
import com.ttk.dto.common.SearchCriteria;
import com.ttk.dto.empanelment.FeedbackDetailVO;
import com.ttk.dto.empanelment.StatusVO;
import formdef.plugin.util.FormUtils;
/**
* This action class is used to search,insert/update and delete hospital feedback information
*/
public class HospitalFeedbackAction extends TTKAction
{
private static Logger log = Logger.getLogger( HospitalFeedbackAction.class );
private static final String strForward="Forward";
private static final String strBackward="Backward";
//forward links
private static final String strFeedback="feedbacks";
private static final String strEditFeedbacks="editfeedbacks";
//Exception Message Identifier
private static final String strHospFeedbackError="feedback";
private static final String strHospitalStatus="feedbacks";
/**
* This method is used to initialize the search grid.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doDefault(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception{
try{
log.debug("Inside the doDefault method of HospitalFeedbackAction");
setLinks(request);
if(TTKCommon.getWebBoardId(request)==null)
{
TTKException expTTK = new TTKException();
expTTK.setMessage("error.hospital.required");
throw expTTK;
}//end of if(TTKCommon.getWebBoardId(request)==null)
TableData tableData=TTKCommon.getTableData(request);
//create new table data object
tableData = new TableData();
//create the required grid table
tableData.createTableInfo("HospitalFeedbackTable",new ArrayList());
request.getSession().setAttribute("tableData",tableData);
((DynaActionForm)form).initialize(mapping);//reset the form data
TTKCommon.documentViewer(request);
HospitalManager hospitalObject=this.getHospitalManagerObject();
HashMap hmReasonInfo = null;
ArrayList alReasonInfo = null;
StatusVO statusVO=null;
//clear the dynaform if visiting from left links for the first time
//else get the dynaform data from session
if(TTKCommon.checkNull(request.getParameter("Entry")).equals("Y")){
((DynaValidatorForm)form).initialize(mapping);//reset the form data
}//end of if(TTKCommon.checkNull(request.getParameter("Entry")).equals("Y")
//call the business layer to get the Status
statusVO=hospitalObject.getStatus(TTKCommon.getWebBoardId(request));
//set the form bean
DynaActionForm frmSearchFeedback = (DynaActionForm)FormUtils.setFormValues("frmSearchFeedback",statusVO, this, mapping, request);
hmReasonInfo=(HashMap)statusVO.getReasonInfo();
alReasonInfo=(ArrayList)hmReasonInfo.get(frmSearchFeedback.get("emplStatusTypeId"));
//setting the ReasonInfo into the request
request.getSession().setAttribute("alReasonInfo",alReasonInfo);
request.getSession().setAttribute("reasonInfo",hmReasonInfo);
request.getSession().setAttribute("frmSearchFeedback",frmSearchFeedback);
//finally return to the grid screen
return this.getForward(strFeedback, mapping, request);
}//end of try
catch(TTKException expTTK)
{
return this.processExceptions(request, mapping, expTTK);
}//end of catch(TTKException expTTK)
catch(Exception exp)
{
return this.processExceptions(request, mapping, new TTKException(exp,strHospFeedbackError));
}//end of catch(Exception exp)
}//end of doDefault(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
/**
* This method is used to search the data with the given search criteria.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doSearch(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception{
try{
setLinks(request);
log.debug("Inside the doSearch method of HospitalFeedbackAction");
HospitalManager hospitalObject=this.getHospitalManagerObject();
TableData tableData=TTKCommon.getTableData(request);
//GET THE HOSPITAL INFORMATION FROM THE SESSION
Long lHospitalSeqId= new Long(TTKCommon.getWebBoardId(request));//get the web board id
//clear the dynaform if visting from left links for the first time
//else get the dynaform data from session
if(TTKCommon.checkNull(request.getParameter("Entry")).equals("Y")){
((DynaActionForm)form).initialize(mapping);//reset the form data
}//end of if(TTKCommon.checkNull(request.getParameter("Entry")).equals("Y"))
String strPageID = TTKCommon.checkNull(request.getParameter("pageId"));
String strSortID = TTKCommon.checkNull(request.getParameter("sortId"));
//if the page number or sort id is clicked
if(!strPageID.equals("") || !strSortID.equals(""))
{
if(!strPageID.equals(""))
{
tableData.setCurrentPage(Integer.parseInt(TTKCommon.checkNull(request.getParameter("pageId"))));
return this.getForward(strFeedback, mapping, request);
}///end of if(!strPageID.equals(""))
else
{
tableData.setSortData(TTKCommon.checkNull(request.getParameter("sortId")));
tableData.modifySearchData("sort");//modify the search data
}//end of else
}//end of if(!strPageID.equals("") || !strSortID.equals(""))
else
{
//create the required grid table
tableData.createTableInfo("HospitalFeedbackTable",null);
tableData.setSearchData(this.populateSearchCriteria((DynaActionForm)form,lHospitalSeqId));
tableData.modifySearchData("search");
}//end of else
ArrayList alFeedback= hospitalObject.getFeedbackList(tableData.getSearchData());
tableData.setData(alFeedback, "search");
//set the table data object to session
request.getSession().setAttribute("tableData",tableData);
//finally return to the grid screen
return this.getForward(strFeedback, mapping, request);
}//end of try
catch(TTKException expTTK)
{
return this.processExceptions(request, mapping, expTTK);
}//end of catch(TTKException expTTK)
catch(Exception exp)
{
return this.processExceptions(request, mapping, new TTKException(exp,strHospFeedbackError));
}//end of catch(Exception exp)
}//end of doSearch(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
/**
* This method is used to get the previous set of records with the given search criteria.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doBackward(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception{
try{
setLinks(request);
log.debug("Inside the doBackward method of HospitalFeedbackAction");
HospitalManager hospitalObject=this.getHospitalManagerObject();
TableData tableData=TTKCommon.getTableData(request);
tableData.modifySearchData(strBackward);//modify the search data
ArrayList alFeedback = hospitalObject.getFeedbackList(tableData.getSearchData());
tableData.setData(alFeedback, strBackward);//set the table data
request.getSession().setAttribute("tableData",tableData);//set the table data object to session
TTKCommon.documentViewer(request);
return this.getForward(strFeedback, mapping, request);//finally return to the grid screen
}//end of try
catch(TTKException expTTK)
{
return this.processExceptions(request, mapping, expTTK);
}//end of catch(TTKException expTTK)
catch(Exception exp)
{
return this.processExceptions(request, mapping, new TTKException(exp,strHospFeedbackError));
}//end of catch(Exception exp)
}//end of doBackward(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
/**
* This method is used to get the next set of records with the given search criteria.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doForward(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception{
try{
setLinks(request);
log.debug("Inside the doForward method of HospitalFeedbackAction");
HospitalManager hospitalObject=this.getHospitalManagerObject();
TableData tableData=TTKCommon.getTableData(request);
tableData.modifySearchData(strForward);//modify the search data
ArrayList alFeedback = hospitalObject.getFeedbackList(tableData.getSearchData());
tableData.setData(alFeedback, strForward);//set the table data
request.getSession().setAttribute("tableData",tableData);//set the table data object to session
TTKCommon.documentViewer(request);
return this.getForward(strFeedback, mapping, request);//finally return to the grid screen
}//end of try
catch(TTKException expTTK)
{
return this.processExceptions(request, mapping, expTTK);
}//end of catch(TTKException expTTK)
catch(Exception exp)
{
return this.processExceptions(request, mapping, new TTKException(exp,strHospFeedbackError));
}//end of catch(Exception exp)
}//end of doForward(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
/**
* This method is used to get the details of the selected record from web-board.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doChangeWebBoard(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception{
log.debug("Inside the doChangeWebBoard method of HospitalFeedbackAction");
//ChangeWebBoard method will call doDefault() method internally.
return doDefault(mapping,form,request,response);
}//end of doChangeWebBoard(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
/**
* This method is used to navigate to detail screen to edit selected record.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doAdd(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception{
try{
setLinks(request);
log.debug("Inside the doAdd method of HospitalFeedbackAction");
HospitalManager hospitalObject=this.getHospitalManagerObject();
StringBuffer sbfCaption= new StringBuffer();
sbfCaption.append("Feedback Details -");
DynaActionForm hospitalFeedbackForm = (DynaActionForm)form;
ArrayList alFeedbackList= hospitalObject.getQAList();
request.setAttribute("alFeedbackList", alFeedbackList);
sbfCaption.append("Add ").append("[").append(TTKCommon.getWebBoardDesc(request)).append("]");
hospitalFeedbackForm.set("caption",String.valueOf(sbfCaption));
return (mapping.findForward(strEditFeedbacks));
}//end of try
catch(TTKException expTTK)
{
return this.processExceptions(request, mapping, expTTK);
}//end of catch(TTKException expTTK)
catch(Exception exp)
{
return this.processExceptions(request, mapping, new TTKException(exp,strHospFeedbackError));
}//end of catch(Exception exp)
}//end of doAdd(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
/**
* This method is used to navigate to detail screen to edit selected record.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doView(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception{
try{
setLinks(request);
log.debug("Inside the doView method of HospitalFeedbackAction");
HospitalManager hospitalObject=this.getHospitalManagerObject();
StringBuffer sbfCaption= new StringBuffer();
sbfCaption.append("Feedback Details -");
DynaActionForm hospitalFeedbackForm = (DynaActionForm)form;
//if rownumber is found populate the form object
if(!((String)(hospitalFeedbackForm).get("rownum")).equals(""))
{
FeedbackDetailVO feedbackVO = (FeedbackDetailVO)((TableData)request.getSession().
getAttribute("tableData")).getData().get(Integer.parseInt((String)hospitalFeedbackForm.get("rownum")));
ArrayList alFeedback=(ArrayList)hospitalObject.getFeedback(feedbackVO.getFeedbackSeqId());
hospitalFeedbackForm.set("feedBackSeqId", feedbackVO.getFeedbackSeqId().toString());
hospitalFeedbackForm.set("feedbackdate", feedbackVO.getFeedbackDate());
hospitalFeedbackForm.set("suggestions",feedbackVO.getSuggestions());
request.setAttribute("alFeedbackList", alFeedback);
sbfCaption.append("Edit ").append("[").append(TTKCommon.getWebBoardDesc(request)).append("]");
}//end if(!((String)(hospitalFeedbackForm).get("rownum")).equals(""))
hospitalFeedbackForm.set("caption",String.valueOf(sbfCaption));
return (mapping.findForward(strEditFeedbacks));
}//end of try
catch(TTKException expTTK)
{
return this.processExceptions(request, mapping, expTTK);
}//end of catch(TTKException expTTK)
catch(Exception exp)
{
return this.processExceptions(request, mapping, new TTKException(exp,strHospFeedbackError));
}//end of catch(Exception exp)
}//end of doView(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
/**
* This method is used to add/update the record.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doSave(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception{
try{
setLinks(request);
log.debug("Inside the doSave method of HospitalFeedbackAction");
HospitalManager hospitalObject=this.getHospitalManagerObject();
StringBuffer sbfCaption= new StringBuffer();
sbfCaption.append("Feedback Details -");
DynaActionForm hospitalFeedbackForm = (DynaActionForm)form;
//GET THE HOSPITAL INFORMATION FROM THE SESSION
Long lHospitalSeqId= new Long(TTKCommon.getWebBoardId(request));//get the web board id
FeedbackDetailVO feedbackVO = new FeedbackDetailVO();
ArrayList alFeedback=null;
Long lFeedBackSeqId=null;
if((String)hospitalFeedbackForm.get("feedBackSeqId")!=null
&& (String)hospitalFeedbackForm.get("feedBackSeqId")!="")
{
lFeedBackSeqId=new Long(Long.parseLong((String)hospitalFeedbackForm.get("feedBackSeqId")));
feedbackVO.setFeedbackSeqId(lFeedBackSeqId);
}//end of if((String)hospitalFeedbackForm.get("feedBackSeqId")!=null
//&& (String)hospitalFeedbackForm.get("feedBackSeqId")!="")
feedbackVO.setHospSeqId(lHospitalSeqId);
feedbackVO.setUpdatedBy(TTKCommon.getUserSeqId(request));// User ID
feedbackVO.setFeedbackDate(TTKCommon.getUtilDate((String)hospitalFeedbackForm.get("feedbackdate")));
feedbackVO.setSuggestions((String)hospitalFeedbackForm.get("suggestions"));
feedbackVO.setQuestions((String[])hospitalFeedbackForm.get("questions"));
feedbackVO.setAnswers((String[])hospitalFeedbackForm.get("answers"));
Long lngCount=hospitalObject.addUpdateFeedback(feedbackVO);
if(lngCount>0)
{
if(lFeedBackSeqId!=null)
{
//set the appropriate message
request.setAttribute("updated","message.savedSuccessfully");
}//end of if(lFeedBackSeqId!=null)
else
{
//set the appropriate message
request.setAttribute("updated","message.addedSuccessfully");
}//end of else
}//end of if(lngCount>0)
alFeedback=(ArrayList)hospitalObject.getFeedback(lngCount);
log.debug("in edit mode list size.....="+alFeedback.size());
hospitalFeedbackForm.set("feedBackSeqId",(lngCount.toString()));
hospitalFeedbackForm.set("feedbackdate", feedbackVO.getFeedbackDate());
hospitalFeedbackForm.set("suggestions",feedbackVO.getSuggestions());
request.setAttribute("alFeedbackList", alFeedback);
sbfCaption.append("Edit ").append("[").append(TTKCommon.getWebBoardDesc(request)).append("]");
hospitalFeedbackForm.set("caption",String.valueOf(sbfCaption));
return this.getForward(strEditFeedbacks, mapping, request);
}//end of try
catch(TTKException expTTK)
{
return this.processExceptions(request, mapping, expTTK);
}//end of catch(TTKException expTTK)
catch(Exception exp)
{
return this.processExceptions(request, mapping, new TTKException(exp,strHospFeedbackError));
}//end of catch(Exception exp)
}//end of doSave(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
/**
* This method is used to navigate to previous screen when closed button is clicked.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doClose(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception{
try{
setLinks(request);
log.debug("Inside the doClose method of HospitalFeedbackAction");
TableData tableData=TTKCommon.getTableData(request);
HospitalManager hospitalObject=this.getHospitalManagerObject();
if(tableData.getSearchData() != null && tableData.getSearchData().size() > 0)
{
//refresh the data in cancel mode, in order to get the new records if any.
ArrayList alFeedback = hospitalObject.getFeedbackList(tableData.getSearchData());
tableData.setData(alFeedback,"search");
request.getSession().setAttribute("tableData",tableData);
//reset the forward links after adding the records if any
}//end of if(tableData.getSearchData() != null && tableData.getSearchData().size() > 0)
return this.getForward(strFeedback, mapping, request);
}//end of try
catch(TTKException expTTK)
{
return this.processExceptions(request, mapping, expTTK);
}//end of catch(TTKException expTTK)
catch(Exception exp)
{
return this.processExceptions(request, mapping, new TTKException(exp,strHospFeedbackError));
}//end of catch(Exception exp)
}//end of doClose(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
/**
* This method is used to delete the selected record(s) in Search Grid.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doDeleteList(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception{
try{
setLinks(request);
log.debug("Inside the doDeleteList method of HospitalFeedbackAction");
HospitalManager hospitalObject=this.getHospitalManagerObject();
TableData tableData=TTKCommon.getTableData(request);
StringBuffer sbfDeleteId = new StringBuffer("|");
//populate the delete string which contains the sequence id's to be deleted
sbfDeleteId.append(populateDeleteId(request, (TableData)request.getSession().getAttribute("tableData")));
//delete the feedback Details
int iCount = hospitalObject.deleteFeedback(sbfDeleteId.append("|").toString());
//refresh the grid with search data in session
ArrayList alFeedback = null;//hospitalObject.getFeedbackList(tableData.getSearchData());
//fetch the data from previous set of rowcounts, if all the records are deleted for the current set of search criteria
if(iCount == tableData.getData().size())
{
tableData.modifySearchData("DeleteList");//modify the search data
int iStartRowCount = Integer.parseInt((String)tableData.getSearchData().get(tableData.
getSearchData().size()-2));
if(iStartRowCount > 0)
{
alFeedback = hospitalObject.getFeedbackList(tableData.getSearchData());
}//end of if(iStartRowCount > 0)
}//end if(iCount == tableData.getData().size())
else
{
alFeedback = hospitalObject.getFeedbackList(tableData.getSearchData());
}//end of else
tableData.setData(alFeedback, "DeleteList");
request.getSession().setAttribute("tableData",tableData);
return this.getForward(strFeedback, mapping, request);
}//end of try
catch(TTKException expTTK)
{
return this.processExceptions(request, mapping, expTTK);
}//end of catch(TTKException expTTK)
catch(Exception exp)
{
return this.processExceptions(request, mapping, new TTKException(exp,strHospFeedbackError));
}//end of catch(Exception exp)
}//end of doDeleteList(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
/**
* This method is used to delete the selected record.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doDelete(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception{
try{
setLinks(request);
log.debug("Inside the doDelete method of HospitalFeedbackAction");
HospitalManager hospitalObject=this.getHospitalManagerObject();
TableData tableData=TTKCommon.getTableData(request);
DynaActionForm hospitalFeedbackForm = (DynaActionForm)form;
StringBuffer sbfDeleteId = new StringBuffer("|");
//populate the delete string which contains the sequence id's to be deleted
if(!(request.getParameter("rownum")).equals(""))
{
sbfDeleteId.append(String.valueOf(((FeedbackDetailVO)((TableData)request.getSession().
getAttribute("tableData")).getData().get(Integer.parseInt(request.getParameter("rownum")))).getFeedbackSeqId()));
}//end of if(!(request.getParameter("rownum")).equals(""))
else //After adding a record and deleting the record this else block is used
{
sbfDeleteId.append(hospitalFeedbackForm.get("feedBackSeqId"));
//this is used if there is only one record
int iCount = hospitalObject.deleteFeedback(sbfDeleteId.append("|").toString());
log.debug("iCount value is :"+iCount);
return this.getForward(strFeedback, mapping, request);
}// end of else
//delete the feedback Details
int iCount = hospitalObject.deleteFeedback(sbfDeleteId.append("|").toString());
//refresh the grid with search data in session
ArrayList alFeedback = null;//hospitalObject.getFeedbackList(tableData.getSearchData());
//fetch the data from previous set of rowcounts, if all the records are deleted for the current set of search criteria
if(iCount == tableData.getData().size())
{
tableData.modifySearchData("Delete");//modify the search data
int iStartRowCount = Integer.parseInt((String)tableData.getSearchData().
get(tableData.getSearchData().size()-2));
if(iStartRowCount > 0)
{
alFeedback = hospitalObject.getFeedbackList(tableData.getSearchData());
}//end of if(iStartRowCount > 0)
}//end if(iCount == tableData.getData().size())
else
{
alFeedback = hospitalObject.getFeedbackList(tableData.getSearchData());
}//end of else
tableData.setData(alFeedback,"Delete");
request.getSession().setAttribute("tableData",tableData);
return this.getForward(strFeedback, mapping, request);
}//end of try
catch(TTKException expTTK)
{
return this.processExceptions(request, mapping, expTTK);
}//end of catch(TTKException expTTK)
catch(Exception exp)
{
return this.processExceptions(request, mapping, new TTKException(exp,strHospFeedbackError));
}//end of catch(Exception exp)
}//end of doDelete(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
/**
* Returns a string which contains the comma separated sequence id's to be deleted
* @param request HttpServletRequest object which contains information about the selected check boxes
* @param tableData TableData object which contains the value objects
* @return String which contains the comma separated sequence id's to be deleted
*/
private String populateDeleteId(HttpServletRequest request, TableData tableData)
{
String[] strChk = request.getParameterValues("chkopt");
StringBuffer sbfDeleteId = new StringBuffer();
if(strChk!=null&&strChk.length!=0)
{
//loop through to populate delete sequence id's and get the value from session for the matching check box value
for(int i=0; i<strChk.length;i++)
{
if(strChk[i]!=null)
{
//extract the sequence id to be deleted from the value object
if(i == 0)
{
sbfDeleteId.append(String.valueOf(((FeedbackDetailVO)tableData.getData().
get(Integer.parseInt(strChk[i]))).getFeedbackSeqId().intValue()));
}//end of if(i == 0)
else
{
sbfDeleteId = sbfDeleteId.append("|").append(String.valueOf(((FeedbackDetailVO)tableData.
getData().get(Integer.parseInt(strChk[i]))).getFeedbackSeqId().intValue()));
}//end of else
}//end of if(strChk[i]!=null)
}//end of for(int i=0; i<strChk.length;i++)
}//end of if(strChk!=null&&strChk.length!=0)
return sbfDeleteId.toString();
}//end of populateDeleteId(HttpServletRequest request, TableData tableData)
/**
* This method builds all the search parameters to ArrayList and places them in session
* @param searchFeedbackForm DynaActionForm
* @param request HttpServletRequest
* @param lHospitalSeqId which will have long value
* @return alSearchParams ArrayList
*/
private ArrayList<Object> populateSearchCriteria(DynaActionForm searchFeedbackForm,Long lHospitalSeqId)
{
//build the column names along with their values to be searched
ArrayList<Object> alSearchParams = new ArrayList<Object>();
alSearchParams.add(new SearchCriteria("HOSP_SEQ_ID",lHospitalSeqId.toString()));
alSearchParams.add(new SearchCriteria("FEEDBACK_DATE", (String)searchFeedbackForm.get("startdate")));
alSearchParams.add(new SearchCriteria("FEEDBACK_DATE", (String)searchFeedbackForm.get("enddate")));
return alSearchParams;
}//end of populateSearchCriteria(DynaActionForm searchFeedbackForm,HttpServletRequest request,Long lHospitalSeqId)
/**
* Returns the HospitalManager session object for invoking methods on it.
* @return HospitalManager session object which can be used for method invokation
* @exception throws TTKException
*/
private HospitalManager getHospitalManagerObject() throws TTKException
{
HospitalManager hospitalManager = null;
try
{
if(hospitalManager == null)
{
InitialContext ctx = new InitialContext();
hospitalManager = (HospitalManager) ctx.lookup("java:global/TTKServices/business.ejb3/HospitalManagerBean!com.ttk.business.empanelment.HospitalManager");
}//end if(hospitalManager == null)
}//end of try
catch(Exception exp)
{
throw new TTKException(exp, strHospFeedbackError);
}//end of catch
return hospitalManager;
}//end getHospitalManagerObject()
/**
* This method is used to load the sub status based on the selected status.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doStatusChange(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception{
try{
setLinks(request);
log.debug("Inside doStatusChange method of HospitalStatusAction");
HashMap hmReasonInfo = null;
ArrayList alReasonInfo = null;
StatusVO statusVO=new StatusVO();
DynaValidatorForm frmStatus=(DynaValidatorForm)request.getSession().getAttribute("frmSearchFeedback");
DynaActionForm frmSearchFeedback = (DynaActionForm)FormUtils.setFormValues("frmSearchFeedback",statusVO, this, mapping, request);
//set the form bean
frmSearchFeedback.set("empanelSeqId",(String)frmStatus.get("empanelSeqId"));
frmSearchFeedback.set("emplStatusTypeId",frmStatus.get("emplStatusTypeId"));
frmSearchFeedback.set("fromDate","");
frmSearchFeedback.set("toDate","");
frmSearchFeedback.set("frmChanged","changed");
frmSearchFeedback.set("gradeTypeId",(String)frmStatus.get("gradeTypeId"));
hmReasonInfo=(HashMap)request.getSession().getAttribute("reasonInfo");
alReasonInfo=(ArrayList)hmReasonInfo.get(frmStatus.get("emplStatusTypeId"));
//setting the ReasonInfo into the request
request.getSession().setAttribute("alReasonInfo",alReasonInfo);
request.getSession().setAttribute("reasonInfo",hmReasonInfo);
request.getSession().setAttribute("frmSearchFeedback",frmSearchFeedback);
return this.getForward(strHospitalStatus,mapping,request);
}//end of try
catch(TTKException expTTK)
{
return this.processExceptions(request, mapping, expTTK);
}//end of catch(TTKException expTTK)
catch(Exception exp)
{
return this.processExceptions(request, mapping, new TTKException(exp,strHospFeedbackError));
}//end of catch(Exception exp)
}//end of doStatusChange(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
/**
* This method is used to add/update the record.
* Finally it forwards to the appropriate view based on the specified forward mappings
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return ActionForward Where the control will be forwarded, after this request is processed
* @throws Exception if any error occurs
*/
public ActionForward doSaveStatus(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception{
try{
setLinks(request);
log.debug("Inside doSave method of HospitalStatusAction");
HospitalManager hospitalObject=this.getHospitalManagerObject();
HashMap hmReasonInfo = null;
ArrayList alReasonInfo = null;
DynaValidatorForm frmStatus=(DynaValidatorForm)request.getSession().getAttribute("frmSearchFeedback");
StatusVO statusVO= null;
statusVO=(StatusVO)FormUtils.getFormValues(frmStatus, "frmSearchFeedback",this, mapping, request);
statusVO.setUpdatedBy(TTKCommon.getUserSeqId(request));// User Id
if(statusVO.getEmplStatusTypeId().equalsIgnoreCase("EMP")){
statusVO.setSubStatusCode("EMP");
}//end of if(statusVO.getEmplStatusTypeId().equalsIgnoreCase("EMP"))
else{
statusVO.setSubStatusCode((String)frmStatus.get("subStatusCode"));
}//end of else
if(statusVO.getEmplStatusTypeId().equalsIgnoreCase("EMP"))
{
statusVO.setFromDate(TTKCommon.getUtilDate((String)frmStatus.get("fromDate")));
statusVO.setToDate(TTKCommon.getUtilDate((String)frmStatus.get("toDate")));
}//end of if(statusVO.getEmplStatusTypeId().equalsIgnoreCase("EMP"))
else if((statusVO.getEmplStatusTypeId().equalsIgnoreCase("DFC"))||(statusVO.getEmplStatusTypeId().equalsIgnoreCase("DEM"))||(statusVO.getEmplStatusTypeId().equalsIgnoreCase("DNC"))||(statusVO.getEmplStatusTypeId().equalsIgnoreCase("DPW"))||(statusVO.getEmplStatusTypeId().equalsIgnoreCase("DOR"))||(statusVO.getEmplStatusTypeId().equalsIgnoreCase("TDE"))||(statusVO.getEmplStatusTypeId().equalsIgnoreCase("TDO")))
{
statusVO.setFromDate(TTKCommon.getUtilDate((String)frmStatus.get("fromDate")));
statusVO.setToDate(null);
}//end of else if(statusVO.getEmplStatusTypeId().equalsIgnoreCase("DFC"))
else if(statusVO.getEmplStatusTypeId().equalsIgnoreCase("CLS"))
{
statusVO.setFromDate(TTKCommon.getUtilDate((String)frmStatus.get("fromDate")));
statusVO.setToDate(null);
}//end of else if(statusVO.getEmplStatusTypeId().equalsIgnoreCase("CLS"))
else
{
statusVO.setFromDate(null);
statusVO.setToDate(null);
}//end of else
//call the business method here for updating the status
int result=hospitalObject.updateStatus(statusVO);
//Set the appropriate message
if(result!=0)
{
//requery to get the new status information
statusVO=hospitalObject.getStatus(TTKCommon.getWebBoardId(request));
request.setAttribute("updated","message.savedSuccessfully");
}//end of if(result!=0)
//set the form bean
DynaActionForm frmSearchFeedback = (DynaActionForm)FormUtils.setFormValues("frmSearchFeedback",statusVO, this, mapping, request);
hmReasonInfo=(HashMap)request.getSession().getAttribute("reasonInfo");
alReasonInfo=(ArrayList)hmReasonInfo.get(frmStatus.get("emplStatusTypeId"));
request.getSession().setAttribute("alReasonInfo",alReasonInfo);
request.getSession().setAttribute("reasonInfo",hmReasonInfo);
request.getSession().setAttribute("frmSearchFeedback",frmSearchFeedback);
Cache.refresh("providerCodeSearch");
Cache.refresh("providerCode");
Cache.refresh("ProviderList");
return this.getForward(strHospitalStatus, mapping, request);
}//end of try
catch(TTKException expTTK)
{
return this.processExceptions(request, mapping, expTTK);
}//end of catch(TTKException expTTK)
catch(Exception exp)
{
return this.processExceptions(request, mapping, new TTKException(exp,strHospFeedbackError));
}//end of catch(Exception exp)
}//end of doSave(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
}// end of HospitalFeedbackAction class |
//
// File.swift
//
//
// Created by Murph on 2022/9/1.
//
import Foundation
extension Algorithm {
///Di jkstra 算法,没有权值为负的边
/// 从一个点出发,计算从该点到所有点的路径最小值
public static func DIJkstra(head: GNode) -> [GNode: Int] {
var distanceMap = [GNode: Int]()
var lockedSet = Set<GNode>()
var result = [GNode: Int]()
func getMinDistanceNoLock() -> (key: GNode, value: Int)? {
let min = distanceMap.min(by: { $0.value < $1.value} )
return min
}
distanceMap[head] = 0;
for edge in head.edge {
distanceMap.removeValue(forKey: edge.to)
}
result[head] = distanceMap[head]
distanceMap[head] = 0
while !distanceMap.isEmpty {
let min = getMinDistanceNoLock()!
let curNode = min.key
let curDistance = min.value
for edge in curNode.edge {
let toNode = edge.to
if !lockedSet.contains(toNode) {
let newDistance = curDistance + edge.weight
if let distance = distanceMap[toNode], distance < newDistance {} else {
distanceMap[toNode] = newDistance
}
}
}
result[min.key] = min.value
lockedSet.insert(min.key)
distanceMap.removeValue(forKey: min.key)
}
return result
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.