text
stringlengths 184
4.48M
|
|---|
#include "main.h"
#include <stdlib.h>
/**
* _realloc - reallocates a block of memory
* @ptr: pointer previously allocated memory
* @old_size: allocated space for ptr
* @new_size: size of new memory block
* Return: void
*/
void *_realloc(void *ptr, unsigned int old_size, unsigned int new_size)
{
void *mem;
char *temp, *p2;
unsigned int i;
if (new_size == old_size)
return (ptr);
if (ptr == NULL)
{
mem = malloc(new_size);
if (mem == NULL)
return (NULL);
return (mem);
}
if (new_size == 0 && ptr != NULL)
{
free(ptr);
return (NULL);
}
p2 = ptr;
mem = malloc(sizeof(*p2) * new_size);
if (mem == NULL)
{
free(ptr);
return (NULL);
}
temp = mem;
for (i = 0; i < old_size && i < new_size; i++)
temp[i] = *p2++;
free(ptr);
return (mem);
}
|
import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import { GenresMoods } from "../types";
const initial_state: GenresMoods = {
genres: [],
moods: [],
};
const genres_moods_slice = createSlice({
name: "genres_moods",
initialState: initial_state,
reducers: {
set_genres: (state: GenresMoods, action: PayloadAction<string[]>) => {
state.genres = action.payload;
},
set_moods: (state: GenresMoods, action: PayloadAction<string[]>) => {
state.moods = action.payload;
},
},
});
export const { set_genres, set_moods } = genres_moods_slice.actions;
export default genres_moods_slice.reducer;
|
# Hypothetical Interview Scenario: Memory Management in JavaScript
**Interviewer**: Welcome, thank you for taking the time to meet with us today. Given your 10 years of experience, I’m sure you have a strong grasp of JavaScript fundamentals. Let’s dive into memory management. Can you explain what garbage collection means in JavaScript?
**Candidate**: Garbage collection in JavaScript refers to the automatic process of deallocating memory that is no longer in use or reachable by the program. It helps prevent memory leaks and ensures efficient memory usage.
**Interviewer**: That’s correct. How does garbage collection work in JavaScript?
**Candidate**: JavaScript uses a technique called automatic garbage collection. It tracks references to objects and removes objects from memory when they are no longer reachable.
**Interviewer**: Good. Now, what is a memory leak, and how can it occur in JavaScript?
**Candidate**: A memory leak happens when a program continues to hold references to objects that are no longer needed, preventing them from being garbage collected. This can occur due to unintended global variables, closures that retain unnecessary references, or circular references.
**Interviewer**: Can you provide an example of how a memory leak might occur?
**Candidate**: Sure. One common example is when event listeners are not properly removed:
```javascript
function addEventListener() {
var element = document.getElementById('button');
element.addEventListener('click', function() {
// Some functionality
});
}
```
If `addEventListener` is called multiple times without removing the previous event listeners, it creates a memory leak because each function created inside the event listener keeps a reference to the `element`.
**Interviewer:** Correct. How would you prevent such memory leaks in your code?
**Candidate:** You should always remember to remove event listeners when they are no longer needed, using `removeEventListener`.
**Interviewer:** What other techniques or tools can be used to detect and mitigate memory leaks in JavaScript applications?
**Candidate:** You can use browser developer tools like Chrome DevTools to analyze memory usage and track down potential memory leaks. Also, tools like `heap snapshots` can help identify objects that are consuming excessive memory.
**Interviewer:** Those are good practices. Let’s discuss the impact of memory leaks on application performance. How can memory leaks affect JavaScript applications?
**Candidate:** Memory leaks can lead to increased memory consumption over time, causing the application to become slower and less responsive. In extreme cases, it can lead to crashes or instability.
**Interviewer:** What strategies would you employ to optimize memory usage in a JavaScript application?
**Candidate:** I would focus on minimizing global variables, avoiding unnecessary object references, and using efficient data structures. Also, ensuring proper cleanup of resources like event listeners and intervals.
**Interviewer:** Those are solid strategies. However, given your experience, I expected you to mention more advanced techniques like using weak references or optimizing algorithm complexity. Can you elaborate on those?
**Candidate:** Um, weak references and algorithm optimizations are certainly important, but I haven’t had much practical experience with them.
**Interviewer:** Understanding these advanced techniques is crucial for senior roles. It seems your knowledge in this area may need further depth. Is there anything else you’d like to add?
**Candidate:** No, I think that covers it.
Interviewer: Thank you for your time. We’ll be in touch.
|
import { ETimeout } from '../constants';
/**
* Class representing various actions on elements.
*/
export declare class EcommWebElementActions {
/**
* Navigate to a URL.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_S).
*/
static navigateToUrl(url: any, waitTimeOut?: ETimeout): Promise<void>;
/**
* Maximize the Window
*/
static maximizeWindow(): Promise<void>;
/**
* Refresh the Browser
*/
static refreshBrowser(): Promise<void>;
/**
* Get the URL of the current session
*/
static getUrl(): Promise<any>;
/**
* Go back in the browser
*/
static backBrowser(): Promise<void>;
/**
* Close the browser
*/
closeBrowser(): Promise<void>;
/**
* Get the url of the current page and compare it with the partial expected url.
* @param expectedPartialUrl - The expected partial URL to compare.
*/
static getUrlAndVerifyPartialUrl(expectedPartialUrl: string): Promise<void>;
/**
* Click on an element.
* @param elementPath - The element to click on.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_S).
*/
static clickElement(elementPath: any, waitTimeOut?: ETimeout): Promise<void>;
/**
* Double click on an element.
* @param elementPath - The element to click on.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_S).
*/
static doubleClickElement(elementPath: WebdriverIO.CucumberOpts, waitTimeOut?: ETimeout): Promise<void>;
/**
* Clear a textbox input.
* @param elementPath - The element representing the textbox.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_S).
*/
static clearInputText(elementPath: any, waitTimeOut?: ETimeout): Promise<void>;
/**
* Clear a textbox input in javascript.
* @param elementPath - The element representing the textbox.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_S).
*/
static clearInputTextJS(elementPath: any, waitTimeOut?: ETimeout): Promise<void>;
/**
* Input text into a textbox.
* @param elementPath - The element representing the textbox.
* @param inputText - The text to input.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_L).
*/
static inputText(elementPath: any, inputText: string, waitTimeOut?: ETimeout): Promise<void>;
/**
* Select value from a dropdown list.
* @param elementPath - The element representing the textbox.
* @param attributeName - The attribute name.
* @param attributeName - The attribute value to select.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_L).
*/
static selectFromDropdown(elementPath: WebdriverIO.CucumberOpts, attributeName: any, attributeValue: any, waitTimeOut?: number): Promise<void>;
/**
* Select a text felementPath: WebdriverIO.CucumberOpts,rom a dropdown list .
* @param elementPath - The element representing the textbox.
* @param attributeName - The attribute name.
* @param attributeName - The attribute value to select.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_L).
*/
static selectVisibleTextFromDropdown(elementPath: any, visibleText: any, waitTimeOut?: number): Promise<void>;
/**
* Get the text of an element.
* @param elementPath - The element to get the text from.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_S).
* @returns The text of the element.
*/
static getText(elementPath: any, waitTimeOut?: ETimeout): Promise<string>;
/**
* Compare two exact values.
* @param expectedText - The expected text.
* @param actualText - The actual text.
*/
static compareTwoValues(expectedText: any, actualText: any): Promise<void>;
/**
* Get the text of an element and compare it with the exact expected text.
* @param elementPath - The element to get the text from.
* @param expectedText - The expected text to compare.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_S).
*/
static getTextAndCompareExactText(elementPath: any, expectedText: string, waitTimeOut?: ETimeout): Promise<void>;
/**
* Compare two partial values.
* @param expectedText - The expected text.
* @param actualText - The actual text.
*/
static compareTwoPartialValues(expectedText: any, actualText: any): Promise<void>;
/**
* Get the text of an element and compare it with the partial expected text.
* @param elementPath - The element to get the text from.
* @param expectedText - The expected partial text to compare.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_S).
*/
static getTextAndComparePartialText(elementPath: any, expectedText: string, waitTimeOut?: ETimeout): Promise<void>;
/**
* Get the attribute value of a textbox and verify it against the expected exact text.
* @param elementPath - The element representing the textbox.
* @param expectedText - The expected exact text of the attribute value.
* @param attributeValue - The attribute to get the value from.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_S).
*/
static getAttributeAndVerifyExactText(elementPath: any, expectedText: string, attributeValue: string, waitTimeOut?: ETimeout): Promise<void>;
/**
* Verify the attribute and value of an element.
* @param elementPath - The element to verify.
* @param elementAttribute - The attribute to verify.
* @param expectedValue - The expected value of the attribute.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_S).
*/
static verifyElementAttributeAndValue(elementPath: any, elementAttribute: string, expectedValue: string, waitTimeOut?: ETimeout): Promise<void>;
verifyGreaterThan(smallNumber: string, largeNumber: string): Promise<void>;
verifyGreaterThanOrEqual(smallNumber: string, largeNumber: string): Promise<void>;
verifyLessThan(smallNumber: string, largeNumber: string): Promise<void>;
verifyLessThanOrEqual(smallNumber: string, largeNumber: string): Promise<void>;
/**
* Wait until an element is displayed.
* @param elementPath - The element to wait for.
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_S).
*/
static waitUntilElementIsDisplayed(elementPath: WebdriverIO.CucumberOpts, waitTimeOut?: ETimeout): Promise<void>;
/**
* Verify if an element is displayed.
* @param elementPath - The element to verify.
*/
static verifyElementIsDisplayed(elementPath: any): Promise<void>;
/**
* Verify if an element is not displayed.
* @param elementPath - The element to verify.
*/
static verifyElementIsNotDisplayed(elementPath: any): Promise<void>;
/**
* Get the boolean value indicating whether an element is displayed.
* @param elementPath - The element to check.
* @returns The boolean value indicating whether the element is displayed.
*/
static booleanElementIsDisplayed(elementPath: WebdriverIO.CucumberOpts): Promise<boolean>;
/**
* Get the boolean value indicating whether an element is selected.
* @param elementPath - The element to check.
* @returns The boolean value indicating whether the element is selected.
*/
static booleanElementIsSelected(elementPath: WebdriverIO.CucumberOpts): Promise<boolean>;
/**
* Pause on a specific element.
* @param elementPath - The element to pause on.
* @param waitTimeOut - The timeout for pausing (default: ETimeout.TIMEOUT_XXS).
*/
static pauseOnElement(elementPath: WebdriverIO.CucumberOpts, waitTimeOut?: ETimeout): Promise<void>;
/**
* Generate a random email address.
* @returns The generated random email address.
*/
static randomEmailGenerator(): Promise<string>;
/**
* Generate a random email with only numbers of given length.
* @returns The generated random email generated with numbers of given length.
*/
static randomEmailGeneratorNumbersOnly(length?: number): Promise<string>;
/**
* Generate a random numbers of given length.
* @returns The generated random numbers of given length.
*/
static randomNumberGenerator(length?: number): Promise<number>;
/**
* Get css property color of an element and verify exact Hex color.
* @param elementPath - The element to get the css property color.
* @param colorHexCode - The expected Hex code to verify
* @param waitTimeOut - The timeout for element display (default: ETimeout.TIMEOUT_S).
*/
static getCSSPropertyColorAndVerifyHexColor(elementPath: WebdriverIO.CucumberOpts, colorHexCode: string, waitTimeOut?: ETimeout): Promise<void>;
}
export default EcommWebElementActions;
|
package main
import (
"html/template"
"io"
"net/http"
"strconv"
"time"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
type Templates struct {
templates *template.Template
}
func (t *Templates) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
func NewTemplates() *Templates {
return &Templates{
templates: template.Must(template.ParseGlob("views/*.html")),
}
}
var id = 0
type Contact struct {
Name string
Email string
Id int
}
type Contacts = []Contact
func createNewContact (name, email string) Contact {
id++
return Contact{
Name: name,
Email: email,
Id: id,
}
}
func (d *Data) hasEmail (email string) bool {
for _, contact := range d.Contacts {
if contact.Email == email {
return true
}
}
return false
}
type Data struct {
Contacts Contacts
}
func (d *Data) indexOf(id int) int {
for i, contact := range d.Contacts {
if id == contact.Id {
return i
}
}
return -1
}
func newData () Data {
return Data{
Contacts: []Contact{
createNewContact("John Doe", "lol@gmila.com"),
createNewContact("clara", "clara@gmila.com"),
},
}
}
type FromData struct {
Values map[string]string
Errors map[string]string
}
func newFormData() FromData {
return FromData{
Values: make(map[string]string),
Errors: make(map[string]string),
}
}
type Page struct {
Data Data
Form FromData
}
func newPage() Page {
return Page{
Data: newData(),
Form: newFormData(),
}
}
func main() {
e := echo.New()
e.Renderer = NewTemplates()
e.Use(middleware.Logger())
page := newPage()
e.Static("/images", "images")
e.Static("/css", "css")
e.GET("/", func(c echo.Context) error {
return c.Render(http.StatusOK, "index", page)
});
e.POST("/contacts", func(c echo.Context) error {
name := c.FormValue("name")
email := c.FormValue("email")
if (page.Data.hasEmail(email)) {
formData := newFormData()
formData.Values["name"] = name
formData.Values["email"] = email
formData.Errors["email"] = "Email already exists"
return c.Render(http.StatusUnprocessableEntity, "form", formData)
}
contact := createNewContact(name, email)
page.Data.Contacts = append(page.Data.Contacts, contact)
c.Render(http.StatusOK, "form", newFormData())
return c.Render(http.StatusOK, "oob-contact", contact)
});
e.DELETE("/contacts/:id", func(c echo.Context) error {
time.Sleep(5 * time.Second)
idStr := c.Param("id")
id, err := strconv.Atoi(idStr)
if err != nil {
return c.String(http.StatusBadRequest, "Invalid id")
}
index := page.Data.indexOf(id)
if index == -1 {
return c.String(http.StatusNotFound, "Contact not found")
}
page.Data.Contacts = append(page.Data.Contacts[:index], page.Data.Contacts[index+1:]...)
return c.NoContent(http.StatusOK)
});
e.Logger.Fatal(e.Start(":42069"))
}
|
package ch.ffhs.customer.controller;
import ch.ffhs.library.library.model.Category;
import ch.ffhs.library.library.repository.CategoryRepository;
import ch.ffhs.library.library.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* CategoryController, which is responsible for processing requests related to categories
*/
@RestController
public class CategoryController {
@Autowired
private CategoryService categoryService;
// injects CategoryRepository
@Autowired
private CategoryRepository categoryRepository;
/**
* method is called when an HTTP GET request is sent to the /categories URL
*
* @return ResponseEntity with categories and 200
*/
@GetMapping("/categories")
public ResponseEntity<List<Category>> categories() {
return new ResponseEntity<>(categoryService.findAll(), HttpStatus.OK);
}
/**
* method is called when an HTTP GET request is sent to the /categories/{id} URL
* and is searching for a category by its ID
*
* @param id of the category
* @return ResponseEntity with category by id and Http Status
*/
@GetMapping("/categories/{id}")
public ResponseEntity<?> findCategoryById(@PathVariable("id") Long id) {
try {
return new ResponseEntity<>(categoryService.findById(id), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e.toString(), HttpStatus.CONFLICT);
}
}
}
|
import "../Styles/Navbar.css"
import "../Styles/MobileStyling/Navbar.css"
import { useState } from "react"
import { AiFillPhone, AiFillMail, AiOutlineMenu } from "react-icons/ai"
import { BsBag, BsPerson, BsCaretDown, BsSearch, BsX } from "react-icons/bs"
import { useDispatch, useSelector } from "react-redux"
import { useNavigate } from "react-router-dom"
import { toggle } from "../Features/Logger.js"
import { sliderToggle } from "../Features/Slider.js"
import MobileSearch from "./MobileSearch"
import Cart from "./Cart/Cart.jsx"
import { toggleCart } from "../Features/CartSlider.js"
function SearchBar() {
const [ search, setSearch ] = useState('')
function searchHandler(e){
setSearch(e.target.value)
}
return (
<div className="searchbar">
<input type="text" value={search} onChange={searchHandler} placeholder="Search Product..." />
<div className="categories">
<span>All Categories</span>
<span> <BsCaretDown /> </span>
</div>
<button>Search</button>
</div>
)
}
function Navbar () {
const [ mobileSearch, setMobileSearch ] = useState(false)
const dispatch = useDispatch()
const logger = useSelector((state) => state.logger.value)
const slider = useSelector((state) => state.slider.value)
const navigate = useNavigate()
function toggleState () {
if (logger.opened == false ) {
dispatch(toggle({ opened: true, page: "login" }))
} else {
dispatch(toggle({ opened: false, page: "login" }))
}
}
function toggleSearch () {
if (mobileSearch) {
setMobileSearch(false)
} else {
setMobileSearch(true)
}
}
function openSlider () {
dispatch(sliderToggle({ open:true }))
}
function switchPage (page) {
navigate(page)
}
return (
<div className="navbar">
<Cart />
<div className="nav-top">
<div>
<span>Visit our online Store</span>
<div>
<span className="nav-icon"> <AiFillMail /> </span>
<span>Email DezStore@gmail.com</span>
</div>
<div>
<span className="nav-icon"> <AiFillPhone /> </span>
<span>Hotline (+234) 805 674 3237</span>
</div>
</div>
<div>
<div>NGN</div>
<div>English</div>
</div>
</div>
<div className="nav-mid">
<div>Logo Placeholder</div>
<> <SearchBar /> </>
<div>
<div className="nav-profile">
<span> <BsPerson /> </span>
<div>
<span>Hello</span>
<span onClick={toggleState}>Login/Register</span>
</div>
</div>
<div className="nav-cart" onClick={() => dispatch(toggleCart({ opened: true }))}>
<span> <BsBag /> </span>
<div>
<span>Your Cart</span>
<span>$0.00</span>
</div>
</div>
</div>
</div>
<div className="nav-bottom">
<MobileSearch opened={mobileSearch} />
<div className="nav-list">
<span onClick={() => switchPage('/')}>Home</span>
<span>Collections</span>
<span onClick={() => switchPage('/products')}>Products</span>
<span onClick={() => switchPage('/contact')}>Contact Us</span>
<span onClick={() => switchPage('/favorites')}>Favorites</span>
</div>
<div>
<span>Special Offer</span>
<span>Purchase Theme</span>
</div>
<div>
<span onClick={toggleSearch}>
{
mobileSearch
?
<BsX />
:
<BsSearch />
}
</span>
<span onClick={openSlider}> <AiOutlineMenu /> </span>
</div>
</div>
</div>
)
}
export default Navbar;
|
import { NextResponse } from "next/server";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
BigInt.prototype.toJSON = function () {
return this.toString();
};
export async function POST(req, res) {
// Insert New Data
try {
const reqBody = await req.json();
//multiple data: createMany
let result = await prisma.post_comment.create({
data: reqBody,
});
return NextResponse.json({ status: "success", data: result });
} catch (err) {
return NextResponse.json({ status: "error", message: err.toString() });
}
}
export async function GET(req, res) {
try {
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
//findMany() for multiple data
let result = await prisma.post_comment.findUnique({
where: { id: parseInt(id) },
});
return NextResponse.json({ status: "success", data: result });
} catch (err) {
return NextResponse.json({ status: "error", message: err.toString() });
}
}
export async function PUT(req, res) {
try {
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
const reqBody = await req.json();
//multiple data: createMany
let result = await prisma.post_comment.update({
where: { id: parseInt(id) },
data: reqBody,
});
return NextResponse.json({ status: "success", data: result });
} catch (err) {
return NextResponse.json({ status: "error", message: err.toString() });
}
}
export async function DELETE(req, res) {
try {
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
let result = await prisma.post_comment.delete({
where: { id: parseInt(id) },
});
return NextResponse.json({ status: "success", data: result });
} catch (err) {
return NextResponse.json({ status: "error", message: err.toString() });
}
}
|
<script setup>
import { ref, computed } from 'vue';
import usePermission from '@/Composables/usePermission';
import TheLogo from '@/Components/Layout/TheLogo.vue';
import NavLink from '@/Components/Shared/NavLink.vue';
import Dropdown from '@/Components/Shared/Dropdown.vue';
import DropdownLink from '@/Components/Shared/DropdownLink.vue';
import ResponsiveNavLink from '@/Components/Shared/ResponsiveNavLink.vue';
import { usePage } from '@inertiajs/vue3';
const navigationLinks = [
{ name: 'Dashboard', route: 'dashboard', permission: 'view-dashboard' },
{ name: 'Users', route: 'users.index', permission: 'view-users' },
{ name: 'Labels', route: 'labels.index', permission: 'view-labels' },
{ name: 'Categories', route: 'categories.index', permission: 'view-categories' },
{ name: 'Tickets', route: 'tickets.index', permission: 'view-tickets' },
// { name: 'Tickets logs', route: 'tickets.logs' },
];
const roles = computed(() => usePage().props.auth.roles);
const permissions = computed(() => usePage().props.auth.permissions);
const { hasPermission } = usePermission({ roles: roles.value, permissions: permissions.value });
const computedNavigationLinks = computed(() => {
return navigationLinks.filter((link) => hasPermission.value(link.permission));
});
const showingNavigationDropdown = ref(false);
</script>
<template>
<nav class="bg-white border-b border-gray-100">
<!-- Primary Navigation Menu -->
<div class="px-4 mx-auto max-w-7xl sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex">
<!-- Logo -->
<div class="flex items-center shrink-0">
<Link :href="route('dashboard')">
<TheLogo class="w-12 h-12" />
</Link>
</div>
<!-- Navigation Links -->
<div class="hidden space-x-4 sm:-my-px sm:ms-10 sm:flex lg:space-x-6">
<NavLink v-for="link in computedNavigationLinks" :key="link.name" :href="route(link.route)"
:active="route().current(link.route)">
{{ link.name }}
</NavLink>
</div>
</div>
<div class="hidden sm:flex sm:items-center sm:ms-6">
<!-- Settings Dropdown -->
<div class="relative ms-3">
<Dropdown align="right" width="48">
<template #trigger>
<span class="inline-flex rounded-md">
<button type="button"
class="inline-flex items-center px-3 py-2 text-sm font-medium leading-4 text-gray-500 transition duration-150 ease-in-out bg-white border border-transparent rounded-md hover:text-gray-700 focus:outline-none">
{{ $page.props.auth.user.name }}
<svg class="ms-2 -me-0.5 h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"
fill="currentColor">
<path fill-rule="evenodd"
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
clip-rule="evenodd" />
</svg>
</button>
</span>
</template>
<template #content>
<DropdownLink :href="route('profile.edit')"> Profile </DropdownLink>
<DropdownLink :href="route('logout')" method="post" as="button">
Log Out
</DropdownLink>
</template>
</Dropdown>
</div>
</div>
<!-- Hamburger -->
<div class="flex items-center -me-2 sm:hidden">
<button @click="showingNavigationDropdown = !showingNavigationDropdown"
class="inline-flex items-center justify-center p-2 text-gray-400 transition duration-150 ease-in-out rounded-md hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500">
<svg class="w-6 h-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path :class="{
hidden: showingNavigationDropdown,
'inline-flex': !showingNavigationDropdown,
}" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
<path :class="{
hidden: !showingNavigationDropdown,
'inline-flex': showingNavigationDropdown,
}" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
</div>
<!-- Responsive Navigation Menu -->
<div :class="{ block: showingNavigationDropdown, hidden: !showingNavigationDropdown }" class="sm:hidden">
<div class="pt-2 pb-3 space-y-1">
<ResponsiveNavLink v-for="link in navigationLinks" :key="link.name" :href="route(link.route)"
:active="route().current(link.route)">
{{ link.name }}
</ResponsiveNavLink>
</div>
<!-- Responsive Settings Options -->
<div class="pt-4 pb-1 border-t border-gray-200">
<div class="px-4">
<div class="text-base font-medium text-gray-800">
{{ $page.props.auth.user.name }}
</div>
<div class="text-sm font-medium text-gray-500">{{ $page.props.auth.user.email }}</div>
</div>
<div class="mt-3 space-y-1">
<ResponsiveNavLink :href="route('profile.edit')"> Profile </ResponsiveNavLink>
<ResponsiveNavLink :href="route('logout')" method="post" as="button">
Log Out
</ResponsiveNavLink>
</div>
</div>
</div>
</nav>
</template>
<style scoped></style>
|
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import './App.css'
import quotes from './json/quotes.json'
import QuoteBox from './components/QuoteBox'
import color from './utils/color'
function App() {
const getIndexRandom = arr => Math.floor(Math.random() * arr.length)
//llama funcion para optener Indice Random por primera vez
const firstQuote = quotes[getIndexRandom(quotes)]
const firstColor = color[getIndexRandom(color)]
//Se guarda el estado de cada dato
const [randomQuote, setRandomQuote] = useState(firstQuote)
const [randomColor, setRandomColor] = useState(firstColor)
const backgroundObject = {
backgroundColor: randomColor
}
//Calculo de Quote y Color Aleatorio 1:32:19
const getRandomAll = () => {
setRandomQuote(quotes[getIndexRandom(quotes)])
setRandomColor(color[getIndexRandom(color)])
}
return (
<div style={backgroundObject} className="App">
<QuoteBox
randomQuote={randomQuote}
randomColor={randomColor}
getRandomAll={getRandomAll} />
</div>
)
}
export default App
|
<?php
class DL_WC_CustomFields
{
private static $instance = null;
public static function getInstance()
{
if (null === self::$instance) {
self::$instance = new self;
}
return self::$instance;
}
public function init()
{
add_action('woocommerce_product_options_general_product_data', array($this, 'addFields'));
add_action('woocommerce_process_product_meta', array($this, 'saveFields'));
add_action('add_meta_boxes', array($this, 'apiPostMetabox'), 10, 2);
}
/**
* @param $pt
* @param WP_Post $post
*/
public function apiPostMetabox($pt, $post)
{
if ($pt != 'product' || empty($post)) {
return;
}
$product = DL_Product::load($post);
if (empty($product) || !$product->isAPI()) {
return;
}
add_meta_box(
'api-prodocut-meta-box',
'API Product',
array($this, 'renderAPIPostMetabox'),
'product',
'normal',
'high'
);
}
public function renderAPIPostMetabox()
{
echo '<strong id="dl_api_product">Product added by API. You can\'t edit it.</strong>'.
'<script type="text/javascript">
jQuery(function($) {$("#dl_api_product").closest("form").submit(function(e){e.preventDefault(); alert("Product added by API. You can\'t edit it.");});});</script>';
}
private function getLocations()
{
return array(
"Arkansas",
"Kentucky",
"New Jersey",
"Oklahoma",
);
}
private function getConditions() {
return array(
'Brand New',
'Refurbished GRADE-A',
'Refurbished GRADE-B',
'Refurbished GRADE-C',
'Refurbished GRADE-A&B',
'Refurbished GRADE-A&B&C',
'Untested Customer Returns',
'Tested Not Working',
'Refurbished Incomplete',
'Salvage Cracked Display'
);
}
public function addFields()
{
echo '<div class="options_group">';
$locations = $this->getLocations();
woocommerce_wp_select(
array(
'id' => '_dl_location',
'label' => "Location",
'options' => array_combine($locations, $locations)
)
);
$conditions = $this->getConditions();
woocommerce_wp_select(
array(
'id' => '_dl_condition',
'label' => "Grade",
'options' => array_combine($conditions, $conditions),
'class' => 'select'
)
);
woocommerce_wp_text_input(
array(
'id' => '_dl_quantity',
'label' => "Quantity",
'type' => 'number',
'custom_attributes' => array(
'step' => '1',
'min' => '0'
)
)
);
woocommerce_wp_text_input(
array(
'id' => '_dl_msrp',
'label' => "MSRP",
'type' => 'number',
'custom_attributes' => array(
'step' => 'Any',
'min' => '0'
)
)
);
woocommerce_wp_checkbox(
array(
'id' => '_dl_private',
'wrapper_class' => 'show_if_simple',
'label' => "Private",
'cbvalue' => '1'
)
);
global $post;
$product = DL_Product::load($post);
if ($product->isPrivate()) {
printf('<p class="form-field show_if_simple" style="display: block;">
<label>Private url</label><a href="%1$s">%1$s</a></p>', get_permalink($post));
}
woocommerce_wp_select(
array(
'id' => '_dl_status',
'label' => "Status",
'options' => array(
"active" => "Active",
"sold" => "Sold",
"cancelled" => "Cancelled"
),
'class' => 'select'
)
);
echo '</div>';
$allOptions = get_option("dl_product_options", array());
if (count($allOptions)) {
echo '<div class="options_group">';
foreach ($allOptions as $option) {
$type = isset($option['type']) ? $option['type'] : 'string';
switch ($type) {
case 'bool':
woocommerce_wp_checkbox(
array(
'id' => '_dl_option_'.$option['id'],
'wrapper_class' => 'show_if_simple',
'label' => $option['name'],
'cbvalue' => '1'
)
);
break;
case 'enum':
woocommerce_wp_select(
array(
'id' => '_dl_option_'.$option['id'],
'label' => $option['name'],
'options' => array_combine($option['values'], $option['values']),
'class' => 'select'
)
);
break;
default:
woocommerce_wp_text_input(
array(
'id' => '_dl_option_'.$option['id'],
'label' => $option['name'],
'class' => ''
)
);
}
}
echo '</div>';
}
}
public function saveFields($post_id) {
if (isset($_POST['_dl_status'])) {
if (in_array($_POST['_dl_status'], array('active', 'sold', 'cancelled'))) {
update_post_meta($post_id, '_dl_status', $_POST['_dl_status']);
}
}
if (isset($_POST['_dl_location'])) {
if (in_array($_POST['_dl_location'], $this->getLocations())) {
update_post_meta($post_id, '_dl_location', $_POST['_dl_location']);
}
}
if (isset($_POST['_dl_condition'])) {
if (in_array($_POST['_dl_condition'], $this->getConditions())) {
update_post_meta($post_id, '_dl_condition', $_POST['_dl_condition']);
}
}
if (isset($_POST['_dl_quantity'])) {
update_post_meta($post_id, '_dl_quantity', $_POST['_dl_quantity']);
}
if (isset($_POST['_dl_msrp'])) {
update_post_meta($post_id, '_dl_msrp', $_POST['_dl_msrp']);
}
update_post_meta($post_id, '_dl_private', isset($_POST['_dl_private']) ? '1' : '0');
$allOptions = get_option("dl_product_options", array());
foreach ($allOptions as $option) {
$name = '_dl_option_'.$option['id'];
$type = isset($option['type']) ? $option['type'] : 'string';
switch ($type) {
case 'bool':
$value = isset($_POST[$name]) && $_POST[$name] == '1' ? '1' : '0';
update_post_meta($post_id, $name, $value);
break;
case 'int':
if (isset($_POST[$name])) {
update_post_meta($post_id, $name, intval($_POST[$name]));
}
break;
case 'double':
if (isset($_POST[$name])) {
update_post_meta($post_id, $name, floatval($_POST[$name]));
}
break;
default:
if (isset($_POST[$name])) {
update_post_meta($post_id, $name, $_POST[$name]);
}
}
}
}
}
|
import { useState } from 'react';
function Register(props) {
const [userName, setUserName] = useState('');
const [password, setPassword] = useState('');
const [email, setEmail] = useState('');
function handleUserNameChange(e) {
const { value } = e.target;
setUserName(value);
}
function handleEmailChange(e) {
const { value } = e.target;
setEmail(value);
}
function handlePasswordChange(e) {
const { value } = e.target;
setPassword(value);
}
const handleSubmit = async (e) => {
e.preventDefault();
props.onRegister();
try {
const res = await fetch(
'https://cipherschools-server.cyclic.app/register',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify([
{
username: userName,
email: email,
password: password,
},
]),
}
)
.then((res) => res.json())
.then((data) => console.log(data));
} catch (err) {
console.log(err);
}
setUserName('');
setEmail('');
setPassword('');
props.onGoToLogin();
};
return (
<div className="font-fira bg-slate-100 pb-8 md:p-[3%] w-full h-screen">
<div className="bg-gray-200 text-slate-600 mx-8 md:mx-72 rounded-xl">
<div className="registerDiv px-8">
<p className="authenticateText text-xl md:text-3xl my-4 py-4">
Register and start your selling journey!{' '}
</p>
<form onSubmit={handleSubmit}>
<label className="text-lg my-4" htmlFor="userName">
Setup Username <span style={{ color: 'red' }}>*</span>
</label>
<input
className="block bg-gray-300 text-slate-600 border-none rounded w-[100%] md:w-[90%] h-8 my-4 md:my-6 focus:outline-none"
type="text"
value={userName}
onChange={handleUserNameChange}
id="userName"
/>
<label className="text-lg my-4" htmlFor="email">
Email <span style={{ color: 'red' }}>*</span>
</label>
<input
className="block bg-gray-300 text-slate-600 border-none rounded w-[100%] md:w-[90%] h-8 my-4 md:my-6 focus:outline-none"
type="text"
value={email}
onChange={handleEmailChange}
id="email"
/>
<label className=" text-lg my-4" htmlFor="password">
Create Password <span style={{ color: 'red' }}>*</span>
</label>
<input
className="block bg-gray-300 text-slate-600 border-none rounded w-[100%] md:w-[90%] h-8 my-4 md:my-6 focus:outline-none"
type="password"
value={password}
onChange={handlePasswordChange}
id="password"
/>
<button
className="bg-orange-500 hover:bg-orange-400 active:translate-y-0.5 text-white text-2xl my-4 md:my-6 p-[1%] rounded-lg w-[100%] hover:cursor-pointer"
type={userName && email && password ? 'submit' : 'button'}
>
Register
</button>
</form>
<p className="authenticateText text-xl text-orange-600 mt-4 md:mt-12 py-2">
{' '}
Already have an account? Login!
</p>
<button
type="button"
className="bg-orange-500 hover:bg-orange-400 active:translate-y-0.5 text-white text-2xl my-6 p-[1%] rounded-lg w-[100%] hover:cursor-pointer"
onClick={props.onGoToLogin}
>
Login
</button>
</div>
</div>
</div>
);
}
export default Register;
|
import React from 'react';
import { Input, Button } from 'react-materialize';
import { Link } from 'react-router';
import PropTypes from 'prop-types';
import toastr from 'toastr';
/**
* @class Form
* @extends {React.Component}
*/
class Form extends React.Component {
/**
* Creates an instance of Form.
* @param {Object} props
* @memberOf Form
*/
constructor(props) {
super(props);
this.state = {
user: {
firstName: '',
lastName: '',
email: '',
password: ''
}
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
/**
* Function to handle onchange event on text input
* @param {Object} e: browser onchange event
* @memberOf Form
* @returns {none} Updates state
*/
onChange(e) {
const field = e.target.name;
const user = this.state.user;
user[field] = e.target.value;
this.setState({ user });
}
/**
* Function to handle signup form onSubmit event
* @param {Object} e: browser event
* @memberOf Form
* @returns {none} handles form onChange event
*/
onSubmit(e) {
e.preventDefault();
this.props.signup(this.state.user)
.then(() => {
toastr.success(`Welcome, ${this.state.user.firstName}!`);
this.context.router.push('/');
}).catch(() => {
toastr.error(
'* Email Address Already Exists!'
);
});
}
/**
* @returns {Object} Jsx
* @memberOf Form
*/
render() {
return (
<div
className="container login-form"
style={{ paddingTop: '5em' }}
>
<form>
<h3 style={{ textAlign: 'center' }}> SIGN UP</h3>
<Input
id="firstName"
type="text"
onChange={this.onChange}
name="firstName"
icon="person_outline"
label="FirstName"
value={this.state.user.firstName}
s={12}
/>
<Input
id="lastname"
type="text"
onChange={this.onChange}
name="lastName"
icon="person"
label="Lastname"
value={this.state.user.lastName}
s={12}
/>
<Input
id="email"
onChange={this.onChange}
name="email"
type="email"
icon="email"
label="Email"
value={this.state.user.email}
s={12}
/>
<Input
id="password"
type="password"
onChange={this.onChange}
name="password"
value={this.state.user.password}
icon="lock"
label="Password"
s={12}
/>
<p style={{ textAlign: 'center' }}>
<Button
type="submit"
value="Sign In"
onClick={this.onSubmit}
>REGISTER
</Button>
</p>
<div className="input-field col s12" >
<p className="margin center medium-small sign-up">
Already have an account?
<Link to="/login">
Login
</Link>
</p>
</div>
</form>
</div>
);
}
}
Form.contextTypes = {
router: PropTypes.object
};
Form.propTypes = {
signup: PropTypes.func.isRequired
};
export default Form;
|
%% Simulator Launcher File
% launches open street map scenario with dynamic spectrumm sharing and 1024-QAM
% Simulation scenario details are defined in +scenarios by handing the
% defined scenario and simulation type to simulate. After the simulation
% the simulation results can be displayed with the functions in
% simulation.results.
%
% initial author: Christoph Buchner
%
% see also scenarios.openStreetMapScenario
% clear working space and close all figures
close all
clear
clc
% launch simulation
result = simulate(@scenarios.openStreetMap, parameters.setting.SimulationType.local);
%% display results
result.showAllPlots;
% show user technologies and cell association
figure(1);
hold on;
for iBaseStation = result.networkResults.baseStationList
for iAntenna = iBaseStation.antennaList
posAnt = iAntenna.positionList(:,1);
for iUser = iBaseStation.attachedUsers
posUe = iUser.positionList(:,1);
if iUser.technology == parameters.setting.NetworkElementTechnology.LTE
pLTE = iUser.plot(1, tools.myColors.matlabBlue);
hold on;
else
p5G = iUser.plot(1, tools.myColors.matlabGreen);
hold on;
end
plot3([posUe(1),posAnt(1)],[posUe(2),posAnt(2)],[posUe(3),posAnt(3)], 'Color', tools.myColors.lightGray);
end
end
end
legend([pLTE, p5G], {'LTE user', '5G user'});
xlim([result.params.regionOfInterest.xMin, result.params.regionOfInterest.xMax]);
ylim([result.params.regionOfInterest.yMin, result.params.regionOfInterest.yMax]);
xlabel('x position in m');
ylabel('y position in m');
zlabel('height in m');
% plot throughput by numerology/technology
numerologies = unique([result.networkResults.userList.numerology]);
f = figure("Name", "Throughput");
set(f,'Position', [50 50 1000 500]);
p1 = subplot(1,2,1);
hold on;
title('user throughput');
xlabel('throughput (Mbit/s)');
ylabel('ECDF');
grid on;
p2 = subplot(1,2,2);
hold on;
title('best CQI user throughput');
xlabel('throughput (Mbit/s)');
ylabel('ECDF');
grid on;
for num = numerologies
userMask = [result.networkResults.userList.numerology] == num;
dl = result.userThroughputMBitPerSec.DL(userMask, :);
dlBestCqi = result.userThroughputMBitPerSec.DLBestCQI(userMask, :);
axes(p1);
tools.myEcdf(mean(dl,2,'omitnan'));
axes(p2);
tools.myEcdf(mean(dlBestCqi,2,'omitnan'));
end
plotLegend = "Numerology " + numerologies;
legend(plotLegend);
axes(p1);
legend(plotLegend);
|
package ptr
import "github.com/jpfourny/papaya/pkg/opt"
// Nil returns a nil pointer to the type parameter V.
func Nil[V any]() *V {
return nil
}
// Ref returns a pointer to a copy of the given value (on the heap).
func Ref[V any](v V) *V {
return &v
}
// DerefOptional returns the value from de-referencing the given pointer wrapped in an opt.Optional, or an empty opt.Optional if the pointer is nil.
func DerefOptional[V any](v *V) opt.Optional[V] {
if v == (*V)(nil) {
return opt.Empty[V]()
}
return opt.Of[V](*v)
}
// DerefOrDefault returns the value from de-referencing the given pointer, or the provided defaultValue if the pointer is nil.
func DerefOrDefault[V any](v *V, defaultValue V) V {
return DerefOptional(v).GetOrDefault(defaultValue)
}
// DerefOrZero returns the value after de-referencing the given pointer, or the zero value of the type parameter V if the pointer is nil.
func DerefOrZero[V any](v *V) V {
return DerefOptional(v).GetOrZero()
}
// DerefOrFunc returns the value after de-referencing the provided ptr, or the result of calling the provided function if the ptr is nil.
func DerefOrFunc[V any](v *V, f func() V) V {
return DerefOptional(v).GetOrFunc(f)
}
|
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { Acerca } from '../clases/Acerca/acerca';
import { Educacion } from '../clases/Edu/educacion';
import { Experiencia } from '../clases/Experiencia/experiencia';
import { Imagen } from '../clases/Imagen/imagen';
import { Perfil } from '../clases/Perfil/perfil';
import { Redes } from '../clases/Personal/redes';
import { Proyecto } from '../clases/Proyecto/proyecto';
import { Skill } from '../clases/Skill/skill';
@Injectable({
providedIn: 'root'
})
export class PortafolioService {
url:string=environment.api
constructor(private http:HttpClient) { }
obtenerDatos():Observable<Perfil>{
return this.http.get<Perfil>(`${this.url}/perfil/get`);
}
// Acerca
actualizarAcerca(acer:Acerca):Observable<Perfil>{
return this.http.put<Perfil>(`${this.url}/acerca`,acer)
}
//Informacio
editarInfoP(per:Perfil):Observable<Perfil>{
return this.http.put<Perfil>(`${this.url}/info/editar/infoP`,per)
}
editarRedes(red:Redes):Observable<Perfil>{
return this.http.put<Perfil>(`${this.url}/info/editar/redes`,red)
}
editarFoto(foto:Imagen):Observable<Perfil>{
return this.http.put<Perfil>(`${this.url}/info/editar/fotos`,foto)
}
//Experiencia
crearExp(exp:Experiencia):Observable<Perfil>{
return this.http.post<Perfil>(`${this.url}/exp/crear`,exp)
}
editarExp(exp:Experiencia):Observable<Perfil>{
return this.http.put<Perfil>(`${this.url}/exp/editar/${exp.id_Exp}`,exp)
}
borrarExp(exp:Experiencia):Observable<Perfil>{
return this.http.delete<Perfil>(`${this.url}/exp/eliminar/${exp.id_Exp}`)
}
//Educacion
crearEdu(edu:Educacion):Observable<Perfil>{
return this.http.post<Perfil>(`${this.url}/edu/crear`,edu)
}
editarEdu(edu:Educacion):Observable<Perfil>{
return this.http.put<Perfil>(`${this.url}/edu/editar/${edu.id_Edu}`,edu)
}
borrarEdu(edu:Educacion):Observable<Perfil>{
return this.http.delete<Perfil>(`${this.url}/edu/eliminar/${edu.id_Edu}`)
}
// Skill
crearSkill(skill:Skill):Observable<Perfil>{
return this.http.post<Perfil>(`${this.url}/skill`,skill)
}
editarSkill(skill:Skill):Observable<Perfil>{
return this.http.put<Perfil>(`${this.url}/skill/editar/${skill.id_Skill}`,skill);
}
borrarSkillId(skill:Skill):Observable<Perfil>{
return this.http.delete<Perfil>(`${this.url}/skill/borrar/${skill.id_Skill}`)
}
//Proyecto
crearProy(proy:Proyecto):Observable<Perfil>{
return this.http.post<Perfil>(`${this.url}/proy/crear`,proy)
}
editarProy(proy:Proyecto):Observable<Perfil>{
return this.http.put<Perfil>(`${this.url}/proy/editar/${proy.id_proyecto}`,proy)
}
borrarProy(proy:Proyecto):Observable<Perfil>{
return this.http.delete<Perfil>(`${this.url}/proy/eliminar/${proy.id_proyecto}`)
}
}
|
/*
Action sheets-- similar to alerts
*/
import SwiftUI
struct ActionSheetsBootcamp: View {
@State var isPresented: Bool = false
@State var actionSheetOption: ActionSheetOptions = .isOtherPost
enum ActionSheetOptions {
case isMyPost
case isOtherPost
}
var body: some View {
VStack {
HStack {
Circle()
.frame(width: 30, height: 30)
Text("@username")
Spacer()
Button(action: {
actionSheetOption = .isMyPost
isPresented.toggle()
}, label: {
Image(systemName:"ellipsis")
})
.accentColor(.primary)
}
.padding(.horizontal)
Rectangle()
.aspectRatio(1.0, contentMode: .fit)
}
.actionSheet(isPresented: $isPresented, content: getActionSheet)
}
func getActionSheet() -> ActionSheet {
let shareButton: ActionSheet.Button = .default(Text("Share")) {
// Add code to share post
}
let reportButton: ActionSheet.Button = .destructive(Text("Report")) {
// Add code to report post
}
let deleteButton: ActionSheet.Button = .destructive(Text("Delete")) {
// Add code to delete post
}
let cancelButton: ActionSheet.Button = .cancel()
let title = Text("What would you like to do?")
switch actionSheetOption {
case.isOtherPost:
return ActionSheet(
title: title,
message: nil,
buttons: [shareButton, reportButton, cancelButton]
)
case.isMyPost:
return ActionSheet(
title: title,
message: nil,
buttons: [shareButton, reportButton, deleteButton, cancelButton]
)
}
// ActionSheet(title: Text("This is the title!"))
// let button1: ActionSheet.Button = .default(Text("Default"))
// let button2: ActionSheet.Button = .destructive(Text("Destructive"))
// let button3: ActionSheet.Button = .cancel(Text("Cancel"))
//
// return ActionSheet(
// title: Text("This is the title!"),
// message: Text("This is the message."),
// buttons: [button1, button1, button1, button2, button3]
// )
}
}
struct ActionSheetsBootcamp_Previews: PreviewProvider {
static var previews: some View {
ActionSheetsBootcamp()
}
}
|
import React, { FC } from "react";
import { Navigate, RouteObject, useRoutes } from "react-router-dom";
import { CATALOG, HOME, REVIEWS, CONTACT } from "./config";
import { CatalogPage, HomePage, ReviewsPage, ContactPage } from "../../pages/";
import RequiredAuth from "../../components/RequiredAuth";
const MainRouter: FC = () => {
const resultPaths: RouteObject[] = [
{ path: HOME, element: <HomePage /> },
{ path: CATALOG, element: <CatalogPage /> },
{
path: REVIEWS,
element: (
<RequiredAuth>
<ReviewsPage />
</RequiredAuth>
),
},
{
path: CONTACT,
element: (
<RequiredAuth>
<ContactPage />
</RequiredAuth>
),
},
{ path: "*", element: <Navigate to={"/"} replace /> },
];
return useRoutes(resultPaths);
};
export default MainRouter;
|
package com.minbio.erp.accounting.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.minbio.erp.R
import com.minbio.erp.cashier_desk.models.CDBalanceData
class AccountingBalanceCLAdapter(
_balanceList: MutableList<CDBalanceData?>
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val balanceList = _balanceList
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == 0) Items(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_cashier_desk_balance, parent, false)
) else
Progress(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_pagination_progress, parent, false)
)
}
override fun getItemCount(): Int = balanceList.size
override fun getItemViewType(position: Int): Int {
return if (balanceList[position] == null) 1 else 0
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is Items)
holder.bind(position)
}
inner class Items(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val customerId: TextView = itemView.findViewById(R.id.customerId)
private val invoiceNo: TextView = itemView.findViewById(R.id.invoiceNo)
private val invoiceDate: TextView = itemView.findViewById(R.id.invoiceDate)
private val payMethod: TextView = itemView.findViewById(R.id.payMethod)
private val debit: TextView = itemView.findViewById(R.id.debit)
private val credit: TextView = itemView.findViewById(R.id.credit)
private val status: TextView = itemView.findViewById(R.id.status)
private val overdue: TextView = itemView.findViewById(R.id.overdue)
private val orderNo: TextView = itemView.findViewById(R.id.orderNo)
fun bind(position: Int) {
customerId.text = balanceList[position]?.customer_id
invoiceNo.text = balanceList[position]?.order_no.toString()
invoiceDate.text = balanceList[position]?.date
payMethod.text = balanceList[position]?.payment_method
debit.text = balanceList[position]?.debit
credit.text = balanceList[position]?.credit
status.text = balanceList[position]?.status
overdue.text = balanceList[position]?.overdue
orderNo.text = balanceList[position]?.order_no
}
}
inner class Progress(itemView: View) : RecyclerView.ViewHolder(itemView)
}
|
import { useState, FC } from "react";
import { MdKeyboardArrowDown, MdKeyboardArrowUp } from "react-icons/md";
import MultiSelectFilter from "../MultiSelectFilter/MultiSelectFilter";
import NumberFilter from "../NumberFilter/NumberFilter";
import styles from "./Filters.module.scss";
interface FiltersProps {
filters: {
location: string[];
species: string[];
diet: string[];
lifestyle: string[];
min_weight: number | null;
max_weight: number | null;
min_length: number | null;
max_length: number | null;
};
dispatch: (action: { type: string; payload: string | number }) => void;
}
const Filters: FC<FiltersProps> = ({ filters, dispatch }) => {
const [filtersOpen, setFiltersOpen] = useState(false);
const toggleOpen = () => {
setFiltersOpen((prevState) => !prevState);
};
return (
<div className={styles.filters}>
<div className={styles.title} onClick={toggleOpen}>
<h3>Filtrowanie</h3>
{filtersOpen ? <MdKeyboardArrowUp /> : <MdKeyboardArrowDown />}
</div>
{filtersOpen && (
<div className={styles.wrapper}>
<div className={styles.filtersList}>
<MultiSelectFilter
label={"Lokalizacja"}
options={[
{
label: "Europa",
value: "europa",
},
{
label: "Azja",
value: "azja",
},
{
label: "Afryka",
value: "afryka",
},
{
label: "Ameryka Północna",
value: "ameryka północna",
},
{
label: "Ameryka Południowa",
value: "ameryka południowa",
},
{
label: "Ameryka Środkowa",
value: "ameryka środkowa",
},
{
label: "Australia",
value: "australia",
},
{
label: "Antarktyda",
value: "antarktyda",
},
{
label: "Arktyka",
value: "arktyka",
},
]}
dispatch={dispatch}
checked={filters.location}
addType="SET_LOCATION"
removeType="DELETE_LOCATION"
clearType="CLEAR_LOCATION"
/>
<MultiSelectFilter
label={"Gatunek"}
options={[
{
label: "Ssaki",
value: "ssak",
},
{
label: "Gady",
value: "gad",
},
{
label: "Ptaki",
value: "ptak",
},
{
label: "Ryby",
value: "ryba",
},
{
label: "Płazy",
value: "płaz",
},
{
label: "Owad",
value: "owad",
},
{
label: "Pająki",
value: "pająk",
},
{
label: "Inne",
value: "inny",
},
]}
dispatch={dispatch}
checked={filters.species}
addType="SET_SPECIES"
removeType="DELETE_SPECIES"
clearType="CLEAR_SPECIES"
/>
<MultiSelectFilter
label={"Dieta"}
options={[
{
label: "Mięsożerne",
value: "mięsożerne",
},
{
label: "Roślinożerne",
value: "roślinożerne",
},
{
label: "Wszystkożerne",
value: "wszystkożerne",
},
{
label: "Pasożyt",
value: "pasożyt",
},
{
label: "Nektarożerne",
value: "nektarożerne",
},
{
label: "Padlinożerne",
value: "padlinożerne",
},
{
label: "Owadożerne",
value: "owadożerne",
},
{
label: "Rybożerne",
value: "rybożerne",
},
{
label: "Glonożerne",
value: "glonożerne",
},
{
label: "Algożerne",
value: "algożerne",
},
{
label: "Miodożerne",
value: "miodożerne",
},
]}
dispatch={dispatch}
checked={filters.diet}
addType="SET_DIET"
removeType="DELETE_DIET"
clearType="CLEAR_DIET"
/>
<MultiSelectFilter
label={"Tryb życia"}
options={[
{
label: "W stadzie",
value: "w stadzie",
},
{
label: "Samotnik",
value: "samotnik",
},
{
label: "W grupie",
value: "w grupie",
},
{
label: "W parach",
value: "w parach",
},
{
label: "W rodzinie",
value: "w rodzinie",
},
]}
dispatch={dispatch}
checked={filters.lifestyle}
addType="SET_LIFESTYLE"
removeType="DELETE_LIFESTYLE"
clearType="CLEAR_LIFESTYLE"
/>
<NumberFilter
label={"Waga od (kg)"}
min={0}
max={10000}
dispatch={dispatch}
currentValue={filters.min_weight}
addType="SET_MIN_WEIGHT"
removeType="DELETE_MIN_WEIGHT"
/>
<NumberFilter
label={"Waga do (kg)"}
min={20}
max={10000}
dispatch={dispatch}
currentValue={filters.max_weight}
addType="SET_MAX_WEIGHT"
removeType="DELETE_MAX_WEIGHT"
/>
<NumberFilter
label={"Długość od (cm)"}
min={0}
max={10000}
dispatch={dispatch}
currentValue={filters.min_length}
addType="SET_MIN_LENGTH"
removeType="DELETE_MIN_LENGTH"
/>
<NumberFilter
label={"Długość do (cm)"}
min={20}
max={10000}
dispatch={dispatch}
currentValue={filters.max_length}
addType="SET_MAX_LENGTH"
removeType="DELETE_MAX_LENGTH"
/>
</div>
<button
className={styles.resetBtn}
onClick={() => {
dispatch({ type: "CLEAR_FILTERS", payload: "" });
}}
>
Wyczyść wszystkie filtry{" "}
</button>
</div>
)}
</div>
);
};
export default Filters;
|
(*Jelena Glišić, MA2-EN, 89191008*)
(*Lights Out*)
let flip mat i j= let r= Array.length mat in let c= Array.length mat.(0) in
for a=1 to r do
for b=1 to c do
if (a=i && b=j) || (a=i && b=(j-1)) || (a=i && b=(j+1)) || (a=(i-1) && b=j) || (a=(i+1) && b=j) then
mat.(a-1).(b-1)<-(not (Array.get (Array.get mat (a-1)) (b-1)));done;done;
mat;;
let print_matrix mat= let r= Array.length mat in let c= Array.length mat.(0) in
for a=1 to r do
for b=1 to c do
if (Array.get (Array.get mat (a-1)) (b-1)) then
print_string("T")
else print_string("F");done;
print_string("\n");done;;
let matrix= [|[|false; true; true; false|];[|true; false; false; true|];[|false; false; true; true|]|];;
print_matrix matrix;;
flip matrix 1 4;;
print_matrix matrix;;
(*Sliding Tiles*)
type slidingTile= {mutable table:char array array; mutable x:int; mutable y:int};;
let slide tile a b= let dim1=Array.length tile.table in let dim2=Array.length tile.table.(0) in let x=tile.x in let y=tile.y in
if a>=1 && a<=dim1 && b>=1 && b<=dim2 && ((a=(x-1) && b=y) || (a=(x-1) && b=y) || (a=x && b=(y-1)) || (a=x && b=(y+1))) then
((tile.x<-a;tile.y<-b);
let c=tile.table.(a-1).(b-1) in
tile.table.(a-1).(b-1)<-' '; tile.table.(x-1).(y-1)<-c);
tile;;
let print_tile tile= let dim1=Array.length tile.table in let dim2=Array.length tile.table.(0) in let x=tile.x in let y=tile.y in
for i=1 to dim1 do
for j=1 to dim2 do
if (i=x) && (j=y) then
print_char(' ')
else print_char(tile.table.(i-1).(j-1));done;
print_string("\n");done;;
let a= {table=[|[|'1';'2';'3'|];[|'4';'5';'6'|];[|'7';'8';' '|]|];x=3;y=3};;
print_tile a;;
slide a 2 2;;
print_tile a;;
slide a 3 2;;
print_tile a;;
slide a 2 2;;
print_tile a;;
(*Briscola*)
type suit = Sword | Cup | Club | Coin;;
type briscola = King of suit | Rider of suit | Jack of suit | Number of int*suit;;
let points card= match card with
|Number (1,_) -> 11
|Number (3,_) -> 10
|King _ -> 4
|Rider _ -> 3
|Jack _ -> 2
|_ -> 0;;
let color card= match card with
|Number (n,s) -> s
|King s -> s
|Rider s -> s
|Jack s -> s;;
let higherfigure c1 c2= let p1=points c1 in let p2= points c2 in match (c1,c2) with
|(Number (a,s),Number (b,t)) when p1=0 && p2=0 -> a>=b
|_ -> p1>=p2;;
let highercard trumpsuit card1 card2=
if (color card2)=trumpsuit && (color card1)<>trumpsuit then false
else if (color card2)=(color card1) then (higherfigure card1 card2)
else true;;
points (Number (1,Club));;
points (Jack Sword);;
color (Jack Sword);;
higherfigure (King Coin) (Rider Cup);;
highercard Cup (King Coin) (Rider Cup);;
highercard Sword (Number (7,Club)) (Number (3,Club));;
highercard Club (Number (1,Club)) (Number (6,Club)) ;;
(*Challenge*)
let play trumpsuit player1card player2card player3card player4card =
let higherfigure2 c1 c2 = let p1= points c1 in let p2= points c2 in match (c1,c2) with
|(Number (a,s), Number (b,t)) when p1=0 && p2=0 && a>=b -> c1
|(Number (a,s), Number (b,t)) when p1=0 && p2=0 -> c2
|_ when p1>=p2 ->c1
|_ -> c2 in
let highestofsuit suit lst =
let new_lst= List.filter (fun a->(color a)=suit) lst in
List.fold_right higherfigure2 new_lst (Number (2,suit)) in
let index_of e l =
let rec index_rec i lst= match lst with
| [] -> 0
| hd::tl -> if hd = e then i else index_rec (i+1) tl in
index_rec 0 l in
let cards= [player1card; player2card; player3card; player4card] in
let suits= List.map color cards in
if List.mem trumpsuit suits then
let winner= index_of (highestofsuit trumpsuit cards) cards in
if (winner mod 2)=0 then ("Team1",(points player1card)+(points player3card))
else ("Team2",(points player2card)+(points player4card));
else let winner= index_of (highestofsuit (List.hd suits) cards) cards in
if (winner mod 2)=0 then ("Team1",(points player1card)+(points player3card))
else ("Team2",(points player2card)+(points player4card));;
play Cup (Number (4,Club)) (Rider Club) (Number (7,Coin)) (Number (1, Cup));;
play Sword (Number (4,Club)) (Number (3,Club)) (Number (7,Coin)) (Number (1, Cup));;
play Sword (Number (4,Club)) (Number (7,Coin)) (Rider Club) (Number (1, Cup));;
play Club (Number (2,Coin)) (Number (4,Club)) (Jack Club) (Number (6, Cup));;
|
/**
* @file frame.c
* @brief Gerencia frames de execução para métodos de classes Java. Cada frame contém o estado
* de execução de um método, incluindo seu contador de programa (PC), operandos, variáveis locais,
* e uma referência ao pool de constantes. Este arquivo oferece funcionalidades para manipular a pilha
* de frames durante a execução dos métodos.
*/
#include "includes/frame.h"
#include <stdlib.h>
PilhaFrame *pilha_frame;
/**
* @brief Inicializa a pilha de frames da JVM.
* Aloca memória para a pilha e define seus valores iniciais.
*/
void inicializa_pilha_frames()
{
pilha_frame = calloc(1, sizeof(pilha_frame));
pilha_frame->frames = NULL;
pilha_frame->length = 0;
}
/**
* @brief Empilha um novo frame na pilha de frames.
*
* @param constant_pool O pool de constantes utilizado pelo método.
* @param metodo O método que será executado no frame empilhado.
*/
void push_frame(ConstantPool *constant_pool, Method *metodo)
{
CodeAttribute *code = metodo->code_attribute;
pilha_frame->frames = realloc(pilha_frame->frames, (pilha_frame->length + 1) * sizeof(Frame));
pilha_frame->frames[pilha_frame->length].pc = 0;
pilha_frame->frames[pilha_frame->length].constant_pool = constant_pool;
pilha_frame->frames[pilha_frame->length].max_stack = code->max_stack;
pilha_frame->frames[pilha_frame->length].max_locals = code->max_locals;
pilha_frame->frames[pilha_frame->length].code_length = code->code_length;
pilha_frame->frames[pilha_frame->length].code = code->code;
pilha_frame->frames[pilha_frame->length].fields = calloc(pilha_frame->frames[pilha_frame->length].max_locals, sizeof(int32_t));
pilha_frame->frames[pilha_frame->length].operandos = calloc(pilha_frame->frames[pilha_frame->length].max_stack, sizeof(int32_t));
pilha_frame->frames[pilha_frame->length].operandos_length = 0;
pilha_frame->length++;
}
/**
* @brief Desempilha o frame atual da pilha de frames.
* Libera a memória alocada para os campos locais e operandos do frame.
*/
void pop_frame()
{
Frame *frame_atual = get_frame_atual();
pilha_frame->frames = realloc(pilha_frame->frames, pilha_frame->length * sizeof(Frame));
pilha_frame->length--;
}
/**
* @brief Retorna o frame atual no topo da pilha de frames.
*
* @return Frame* O frame atual.
*/
Frame *get_frame_atual()
{
if (!pilha_frame->length)
{
printf("ERRO: Pilha de frames vazia!");
exit(0);
}
return &(pilha_frame->frames[pilha_frame->length - 1]);
}
/**
* @brief Executa o frame atual até que o PC (program counter) alcance o final do código.
* Executa cada instrução conforme definido pelo PC até que o frame seja completamente executado.
*/
void executa_frame_atual()
{
Frame *frame_atual;
do
{
frame_atual = get_frame_atual();
// printf("--------------------------\n");
// printf("PC: %d\n", frame_atual->pc);
// printf("Instrucao: %s\n", instrucoes[frame_atual->code[frame_atual->pc]].nome);
// printf("Pilha de operandos: %d\n", frame_atual->operandos_length);
// printf("Operandos: [");
// for (int i = 0; i < frame_atual->operandos_length; i++)
// {
// printf("%d%s", frame_atual->operandos[i], i == frame_atual->operandos_length - 1 ? "" : ", ");
// }
// printf("]\n");
// printf("Pilha de frames: %d\n", pilha_frame->length);
// printf("--------------------------\n\n");
instrucoes[frame_atual->code[frame_atual->pc]].exec();
} while (frame_atual->pc < frame_atual->code_length);
pop_frame();
}
/**
* @brief Empilha um valor de retorno no frame anterior ao atual.
*
* @param retorno O valor a ser retornado.
*/
void push_retorno(int32_t retorno)
{
Frame *proximo_frame = &(pilha_frame->frames[pilha_frame->length - 2]);
if (proximo_frame->operandos_length >= proximo_frame->max_stack)
{
printf("ERRO: Pilha de operandos excedida!\n");
exit(0);
}
proximo_frame->operandos[proximo_frame->operandos_length] = retorno;
proximo_frame->operandos_length++;
}
/**
* @brief Empilha um operando no stack do frame atual.
*
* @param valor O valor do operando a ser empilhado.
*/
void push_operando(int32_t valor)
{
Frame *frame_atual = get_frame_atual();
if (frame_atual->operandos_length >= frame_atual->max_stack)
{
printf("ERRO: Pilha de operandos excedida!\n");
exit(0);
}
frame_atual->operandos[frame_atual->operandos_length] = valor;
frame_atual->operandos_length++;
}
/**
* @brief Desempilha um operando do stack do frame atual.
*
* @return int32_t O valor do operando desempilhado.
*/
int32_t pop_operando()
{
Frame *frame_atual = get_frame_atual();
if (frame_atual->operandos_length == 0)
{
printf("ERRO: Pilha de operandos vazia\n");
exit(1);
}
frame_atual->operandos_length--;
return frame_atual->operandos[frame_atual->operandos_length];
}
/**
* @brief Atualiza o PC (program counter) do frame atual para apontar para a próxima instrução.
* Incrementa o PC com base no número de bytes da instrução atual.
*/
void atualiza_pc()
{
Frame *frame_atual = get_frame_atual();
frame_atual->pc += instrucoes[frame_atual->code[frame_atual->pc]].bytes + 1;
}
|
import { useEffect, useRef, useCallback } from "react";
import { getAuth, onAuthStateChanged } from "firebase/auth";
const useLogoutTimer = ({ isLoggedIn, setIsLoggedIn, handleLogout }) => {
const logoutTimerRef = useRef(null);
const resetTimer = useCallback(() => {
if (logoutTimerRef.current) {
clearTimeout(logoutTimerRef.current);
}
logoutTimerRef.current = setTimeout(handleLogout, 5 * 60 * 1000);
}, [handleLogout]);
useEffect(() => {
const auth = getAuth();
const unsubscribeFromAuth = onAuthStateChanged(auth, (user) => {
if (user) {
setIsLoggedIn(true);
resetTimer();
} else {
setIsLoggedIn(false);
}
});
window.addEventListener("mousemove", resetTimer);
window.addEventListener("keypress", resetTimer);
return () => {
unsubscribeFromAuth();
window.removeEventListener("mousemove", resetTimer);
window.removeEventListener("keypress", resetTimer);
if (logoutTimerRef.current) {
clearTimeout(logoutTimerRef.current);
}
};
}, [isLoggedIn, setIsLoggedIn, resetTimer]);
};
export default useLogoutTimer;
|
using System.Collections.Generic;
using Microsoft.AspNetCore.Components;
using MudBlazor.Interfaces;
using MudBlazor.Utilities;
namespace MudBlazor
{
#nullable enable
/// <summary>
/// Represents a grouping of multiple <see cref="MudAvatar"/> components.
/// </summary>
partial class MudAvatarGroup : MudComponentBase
{
private bool _childrenNeedUpdates = false;
protected string Classname => new CssBuilder("mud-avatar-group")
.AddClass($"mud-avatar-group-outlined", Outlined)
.AddClass($"mud-avatar-group-outlined-{OutlineColor.ToDescriptionString()}", Outlined)
.AddClass(Class)
.Build();
protected string MaxAvatarClassname => new CssBuilder("mud-avatar-group-max-avatar")
.AddClass($"ms-n{Spacing}")
.AddClass(MaxAvatarClass)
.Build();
/// <summary>
/// Gets or sets the amount of space between avatars, between <c>0</c> and <c>16</c>.
/// </summary>
/// <remarks>
/// Defaults to <c>3</c>.
/// </remarks>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Behavior)]
public int Spacing { get; set; } = 3;
/// <summary>
/// Gets or sets whether an outline is displayed for the group.
/// </summary>
/// <remarks>
/// Defaults to <c>true</c>. This property is useful to differentiate avatars which are the same color or use images.
/// </remarks>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Appearance)]
public bool Outlined { get; set; } = true;
/// <summary>
/// Gets or sets the color of the outline when <see cref="Outlined"/> is <c>true</c>.
/// </summary>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Appearance)]
public Color OutlineColor { get; set; } = Color.Surface;
/// <summary>
/// Gets or sets the size of the drop shadow when the number of avatars exceeds <see cref="Max"/>.
/// </summary>
/// <remarks>
/// Defaults to <c>0</c>.
/// </remarks>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Appearance)]
public int MaxElevation { set; get; } = 0;
/// <summary>
/// Gets or sets whether rounded corners are disabled when the number of avatars exceeds <see cref="Max"/>.
/// </summary>
/// <remarks>
/// Defaults to <c>false</c>. When <c>true</c>, the <c>border-radius</c> CSS style is set to <c>0</c>.
/// </remarks>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Appearance)]
public bool MaxSquare { get; set; }
/// <summary>
/// Gets or sets whether corners are rounded when the number of avatars exceeds <see cref="Max"/>.
/// </summary>
/// <remarks>
/// Defaults to <c>false</c>. When <c>true</c>, the <c>border-radius</c> style is set to the theme's default value.
/// </remarks>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Appearance)]
public bool MaxRounded { get; set; }
/// <summary>
/// Gets or sets the color of the avatar when the number of avatars exceeds <see cref="Max"/>.
/// </summary>
/// <remarks>
/// Defaults to <see cref="Color.Default"/>. Theme colors are supported.
/// </remarks>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Appearance)]
public Color MaxColor { get; set; } = Color.Default;
/// <summary>
/// Gets or sets the size of the avatar when the number of avatars exceeds <see cref="Max"/>.
/// </summary>
/// <remarks>
/// Defaults to <see cref="Size.Medium"/>.
/// </remarks>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Appearance)]
public Size MaxSize { get; set; } = Size.Medium;
/// <summary>
/// Gets or sets the display variant to use when the number of avatars exceeds <see cref="Max"/>.
/// </summary>
/// <remarks>
/// Defaults to <see cref="Variant.Filled" />. The variant changes the appearance of the avatar, such as <c>Text</c>, <c>Outlined</c>, or <c>Filled</c>.
/// </remarks>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Appearance)]
public Variant MaxVariant { get; set; } = Variant.Filled;
/// <summary>
/// Gets or sets the maximum allowed avatars to display.
/// </summary>
/// <remarks>
/// Defaults to <c>0</c>. When <c>0</c>, no maximum is enforced. Otherwise, a "+#" avatar is shown for the number of avatars exceeding this number.
/// </remarks>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Behavior)]
public int Max { get; set; }
/// <summary>
/// Gets or sets the CSS class applied when the number of avatars exceeds <see cref="Max"/>.
/// </summary>
/// <remarks>
/// Defaults to <c>null</c>.
/// </remarks>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Appearance)]
public string? MaxAvatarClass { get; set; }
/// <summary>
/// Gets or sets a template used to render avatars when the number of avatars exceeds <see cref="Max"/>.
/// </summary>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Appearance)]
public RenderFragment<int>? MaxAvatarsTemplate { get; set; }
/// <summary>
/// Gets or sets the content within this component.
/// </summary>
[Parameter]
[Category(CategoryTypes.AvatarGroup.Behavior)]
public RenderFragment? ChildContent { get; set; }
internal List<MudAvatar> _avatars = new();
public MudAvatarGroup()
{
using var registerScope = CreateRegisterScope();
registerScope.RegisterParameter<int>(nameof(Spacing))
.WithParameter(() => Spacing)
.WithChangeHandler(() => _childrenNeedUpdates = true)
.Attach();
registerScope.RegisterParameter<int>(nameof(Max))
.WithParameter(() => Max)
.WithChangeHandler(() => _childrenNeedUpdates = true)
.Attach();
}
internal void AddAvatar(MudAvatar avatar)
{
_avatars.Add(avatar);
StateHasChanged();
}
internal void RemoveAvatar(MudAvatar avatar)
{
_avatars.Remove(avatar);
}
internal CssBuilder GetAvatarSpacing() => new CssBuilder()
.AddClass($"ms-n{Spacing}");
internal StyleBuilder GetAvatarZindex(MudAvatar avatar) => new StyleBuilder()
.AddStyle("z-index", $"{_avatars.Count - _avatars.IndexOf(avatar)}");
internal bool MaxGroupReached(MudAvatar avatar)
{
return _avatars.IndexOf(avatar) < Max;
}
/// <inheritdoc />
protected override void OnParametersSet()
{
base.OnParametersSet();
if (_childrenNeedUpdates)
{
foreach (IMudStateHasChanged avatar in _avatars)
{
avatar.StateHasChanged();
}
_childrenNeedUpdates = false;
}
}
}
}
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SignupComponent } from './component/signup/signup.component';
import { LoginComponent } from './component/login/login.component';
import { ForgotpasswordComponent } from './component/forgotpassword/forgotpassword.component';
import { DashboardComponent } from './component/dashboard/dashboard.component';
import { GetallbooksComponent } from './component/getallbooks/getallbooks.component';
import { SingleBookDetailsComponent } from './component/single-book-details/single-book-details.component';
import { CartComponent } from './component/cart/cart.component';
import { WishlistComponent } from './component/wishlist/wishlist.component';
import { OrderComponent } from './component/order/order.component';
import { ProfileComponent } from './component/profile/profile.component';
const routes: Routes = [
{path:'',redirectTo:"/login",pathMatch:'full'},
{path:'login',component:LoginComponent},
{path:'signup',component:SignupComponent},
{path:'forgot-password',component:ForgotpasswordComponent},
{path:'dashboard', component:DashboardComponent,
children:[
{path:'books', component:GetallbooksComponent},
{path:'book/:data', component:SingleBookDetailsComponent},
{path:'cart', component:CartComponent},
{path:'wishlist', component:WishlistComponent},
{path:'order', component:OrderComponent},
{path:'profile', component:ProfileComponent}
]},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
from typing import BinaryIO
from cognee.infrastructure.data.utils.extract_keywords import extract_keywords
from .IngestionData import IngestionData
def create_text_data(data: str):
return TextData(data)
class TextData(IngestionData):
data: str = None
metadata = None
def __init__(self, data: BinaryIO):
self.data = data
def get_identifier(self):
keywords = self.get_metadata()["keywords"]
return "text/plain" + "_" + "|".join(keywords)
def get_metadata(self):
self.ensure_metadata()
return self.metadata
def ensure_metadata(self):
if self.metadata is None:
self.metadata = dict(keywords = extract_keywords(self.data))
def get_data(self):
return self.data
|
import { ErrorMessage } from "../../components/ErrorMessage";
import React from "react";
import PropTypes from "prop-types";
const variants = {
FillBlueA400: "bg-blue_A400",
OutlineBluegray200: "bg-gray_52 border border-bluegray_200 border-solid",
};
const shapes = {
CustomBorderTL8:
"rounded-bl-[0] rounded-br-[0] rounded-tl-[8px] rounded-tr-[8px]",
RoundedBorder8: "rounded-radius8",
};
const sizes = {
sm: "lg:pb-[10px] xl:pb-[13px] pb-[15px] 3xl:pb-[17px] lg:pt-[14px] xl:pt-[17px] pt-[20px] 3xl:pt-[23px] lg:px-[10px] xl:px-[13px] px-[15px] 3xl:px-[17px]",
};
const Input = React.forwardRef(
(
{
wrapClassName = "",
className = "",
name,
placeholder,
type = "text",
children,
errors = [],
label = "",
prefix,
suffix,
shape,
variant,
size,
...restProps
},
ref
) => {
return (
<>
<div
className={`${wrapClassName} ${shapes[shape] || ""} ${
variants[variant] || ""
} ${sizes[size] || ""}`}
>
{!!label && label}
{!!prefix && prefix}
<input
ref={ref}
className={`${className} bg-transparent border-0`}
type={type}
name={name}
placeholder={placeholder}
{...restProps}
/>
{!!suffix && suffix}
</div>
{!!errors && <ErrorMessage errors={errors} />}
</>
);
}
);
Input.propTypes = {
wrapClassName: PropTypes.string,
className: PropTypes.string,
name: PropTypes.string,
placeholder: PropTypes.string,
type: PropTypes.string,
shape: PropTypes.oneOf(["CustomBorderTL8", "RoundedBorder8"]),
variant: PropTypes.oneOf(["FillBlueA400", "OutlineBluegray200"]),
size: PropTypes.oneOf(["sm"]),
};
Input.defaultProps = {
wrapClassName: "",
className: "",
name: "",
placeholder: "",
type: "text",
shape: "RoundedBorder8",
variant: "OutlineBluegray200",
size: "",
};
export { Input };
|
import { React, useState, useEffect } from 'react'
import axiosClient from '../../../../../axios/axios';
import { ArrowLeftStartOnRectangleIcon, TrashIcon } from '@heroicons/react/24/solid';
import ReactModal from 'react-modal';
import RestoreUserModal from '../../ManageUser/Modals/RestoreUserModal';
import DeleteUserModal from '../../ManageUser/Modals/DeleteUserModal';
import RestorePdf from './RestorePdf';
import DeletePdf from './DeletePdfModal';
import DeletePdfModal from './DeletePdfModal';
export default function ArchivedPdfs() {
const [filterText, setFilterText] = useState(''); //for search
const [pdfs, setPdfs] = useState([]);
const [selectedPDF, setSelectedPDF] = useState('')
const [isRestorePdfModalOpen, setIsRestorePdfModalOpen] = useState(false);
const [isDeleteUserModalOpen, setIsDeleteUserModalOpen] = useState(false);
useEffect(() => {
fetchCurriculum();
}, []);
const fetchCurriculum = async () => {
try {
const response = await axiosClient.get('/showarchivedpdfs');
if (Array.isArray(response.data.message)) {
setPdfs(response.data.message);
} else {
console.error('Invalid response format:', response.data);
}
} catch (error) {
console.error(error);
}
};
// for search function
const filteredData = pdfs.filter(
(pdf) =>
pdf && pdf.toString().includes(filterText)
);
// For User RESTOREUSER
const handleRestoreUserClick = (selected_pdfs) => {
setIsRestorePdfModalOpen(true)
setSelectedPDF(selected_pdfs)
}
// For User RESTOREUSER
const handleDeleteUserClick = (selected_user) => {
setIsDeleteUserModalOpen(true)
setSelectedPDF(selected_user)
}
return (
<>
<div className="h-full">
<div className='bg-white flex h-full overflow-y-auto rounded-xl'>
<table className='w-screen text-center h-fit'>
<thead className='bg-secondary sticky top-0'>
<tr>
<th className="text-left bg-secondary p-2 ">Pdf Name</th>
<th className="w-fit text-left bg-secondary p-2 ">Actions</th>
</tr>
</thead>
<tbody>
{filteredData.map((pdfs, index) => (
<tr
key={index}
className='border-b-2 border-secondary hover:bg-accent hover:drop-shadow-gs'
>
<td className="text-center p-2">{pdfs}</td>
<td className= "flex items-center p-3">
<button title="Restore User" onClick={() => handleRestoreUserClick(pdfs)}>
<ArrowLeftStartOnRectangleIcon className='h-5 w-5 mx-1 cursor-pointer transform transition-transform hover:scale-125' />
</button>
<button title="Delete User" onClick={() => handleDeleteUserClick(pdfs)}>
<TrashIcon className='h-5 w-5 mx-1 cursor-pointer transform transition-transform hover:scale-125' />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{/** Modal For User ARCHIVE */}
<ReactModal
isOpen={isRestorePdfModalOpen}
onRequestClose={() => setIsRestoreUserModalOpen(false)}
className="w-full md:w-[30%] h-fit bg-[#FFFFFF] rounded-3xl ring-1 ring-black shadow-2xl mt-[10%] mx-auto p-5"
>
<div>
<RestorePdf
closeModal={() => setIsRestoreUserModalOpen(false)}
selectedPDF={selectedPDF}
/>
</div>
</ReactModal>
{/** Modal For User ARCHIVE */}
<ReactModal
isOpen={isDeleteUserModalOpen}
onRequestClose={() => setIsDeleteUserModalOpen(false)}
className="w-full md:w-[30%] h-fit bg-[#FFFFFF] rounded-3xl ring-1 ring-black shadow-2xl mt-[10%] mx-auto p-5"
>
<div>
<DeletePdfModal
closeModal={() => setIsDeleteUserModalOpen(false)}
selectedPDF={selectedPDF}
/>
</div>
</ReactModal>
</>
)
}
|
/*
* HttpRequestEventArgs.cs
*
* The MIT License
*
* Copyright (c) 2012-2017 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace AppneuronUnity.Core.Libraries.WebSocketSharp.Server
{
using System;
using System.IO;
using System.Security.Principal;
using System.Text;
using AppneuronUnity.Core.Libraries.WebSocketSharp.Net;
/// <summary>
/// Represents the event data for the HTTP request events of
/// the <see cref="HttpServer"/>.
/// </summary>
public class HttpRequestEventArgs : EventArgs
{
/// <summary>
/// Defines the _context.
/// </summary>
private HttpListenerContext _context;
/// <summary>
/// Defines the _docRootPath.
/// </summary>
private string _docRootPath;
/// <summary>
/// Initializes a new instance of the <see cref="HttpRequestEventArgs"/> class.
/// </summary>
/// <param name="context">The context<see cref="HttpListenerContext"/>.</param>
/// <param name="documentRootPath">The documentRootPath<see cref="string"/>.</param>
internal HttpRequestEventArgs(
HttpListenerContext context, string documentRootPath
)
{
_context = context;
_docRootPath = documentRootPath;
}
/// <summary>
/// Gets the request data sent from a client....
/// </summary>
public HttpListenerRequest Request
{
get
{
return _context.Request;
}
}
/// <summary>
/// Gets the response data to return to the client....
/// </summary>
public HttpListenerResponse Response
{
get
{
return _context.Response;
}
}
/// <summary>
/// Gets the information for the client....
/// </summary>
public IPrincipal User
{
get
{
return _context.User;
}
}
/// <summary>
/// The createFilePath.
/// </summary>
/// <param name="childPath">The childPath<see cref="string"/>.</param>
/// <returns>The <see cref="string"/>.</returns>
private string createFilePath(string childPath)
{
childPath = childPath.TrimStart('/', '\\');
return new StringBuilder(_docRootPath, 32)
.AppendFormat("/{0}", childPath)
.ToString()
.Replace('\\', '/');
}
/// <summary>
/// The tryReadFile.
/// </summary>
/// <param name="path">The path<see cref="string"/>.</param>
/// <param name="contents">The contents<see cref="byte[]"/>.</param>
/// <returns>The <see cref="bool"/>.</returns>
private static bool tryReadFile(string path, out byte[] contents)
{
contents = null;
if (!File.Exists(path))
return false;
try
{
contents = File.ReadAllBytes(path);
}
catch
{
return false;
}
return true;
}
/// <summary>
/// Reads the specified file from the document folder of
/// the <see cref="HttpServer"/>.
/// </summary>
/// <param name="path">The path<see cref="string"/>.</param>
/// <returns>The <see cref="byte[]"/>.</returns>
public byte[] ReadFile(string path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException("An empty string.", "path");
if (path.IndexOf("..") > -1)
throw new ArgumentException("It contains '..'.", "path");
byte[] contents;
tryReadFile(createFilePath(path), out contents);
return contents;
}
/// <summary>
/// Tries to read the specified file from the document folder of
/// the <see cref="HttpServer"/>.
/// </summary>
/// <param name="path">The path<see cref="string"/>.</param>
/// <param name="contents">The contents<see cref="byte[]"/>.</param>
/// <returns>The <see cref="bool"/>.</returns>
public bool TryReadFile(string path, out byte[] contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException("An empty string.", "path");
if (path.IndexOf("..") > -1)
throw new ArgumentException("It contains '..'.", "path");
return tryReadFile(createFilePath(path), out contents);
}
}
}
|
const express = require("express");
const router = express.Router();
const pool = require("../database");
router.post("/", (req, res) => {
const { jour, heureOuverture, heureFermeture } = req.body;
if (!jour || !heureOuverture || !heureFermeture) {
return res.status(400).send("Tous les champs sont requis.");
}
const query =
"INSERT INTO HorairesOuverture (Jour, Heure_Ouverture, Heure_Fermeture) VALUES (?, ?, ?)";
pool.query(
query,
[jour, heureOuverture, heureFermeture],
(error, results) => {
if (error) {
console.error(error);
return res
.status(500)
.send("Erreur lors de l'ajout de l'horaire d'ouverture.");
}
res
.status(201)
.send(`Horaire d'ouverture créé avec l'ID: ${results.insertId}`);
}
);
});
router.get("/", (req, res) => {
const query = "SELECT * FROM HorairesOuverture";
pool.query(query, (error, results) => {
if (error) {
console.error(error);
return res
.status(500)
.send("Erreur lors de la récupération des horaires.");
}
res.status(200).json(results);
});
});
router.get("/:id", (req, res) => {
const { id } = req.params;
const query = "SELECT * FROM HorairesOuverture WHERE ID_Horaire = ?";
pool.query(query, [id], (error, results) => {
if (error) {
console.error(error);
return res
.status(500)
.send("Erreur lors de la récupération de l'horaire d'ouverture.");
}
if (results.length === 0) {
return res.status(404).send("Horaire d'ouverture non trouvé.");
}
res.status(200).json(results[0]);
});
});
router.put("/:id", (req, res) => {
const { id } = req.params;
const { jour, heureOuverture, heureFermeture } = req.body;
if (!jour || !heureOuverture || !heureFermeture) {
return res.status(400).send("Tous les champs sont requis.");
}
const query =
"UPDATE HorairesOuverture SET Jour = ?, Heure_Ouverture = ?, Heure_Fermeture = ? WHERE ID_Horaire = ?";
pool.query(
query,
[jour, heureOuverture, heureFermeture, id],
(error, results) => {
if (error) {
console.error(error);
return res
.status(500)
.send("Erreur lors de la mise à jour de l'horaire d'ouverture.");
}
if (results.affectedRows === 0) {
return res.status(404).send("Horaire d'ouverture non trouvé.");
}
res.send("Horaire d'ouverture mis à jour avec succès.");
}
);
});
router.delete("/:id", (req, res) => {
const { id } = req.params;
const query = "DELETE FROM HorairesOuverture WHERE ID_Horaire = ?";
pool.query(query, [id], (error, results) => {
if (error) {
console.error(error);
return res
.status(500)
.send("Erreur lors de la suppression de l'horaire d'ouverture.");
}
if (results.affectedRows === 0) {
return res.status(404).send("Horaire d'ouverture non trouvé.");
}
res.send("Horaire d'ouverture supprimé avec succès.");
});
});
module.exports = router;
|
package ao.space;
import ao.space.LoadInflationService.Inflation;
import io.smallrye.common.annotation.RunOnVirtualThread;
import io.smallrye.mutiny.Uni;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
@Path("/inflation")
public class LoadInflationResource {
@Inject
LoadInflationService service;
@Path("/reactive/{id}")
@GET
public Uni<Inflation> getInflationReactively(@PathParam("id") long id) {
return service.findAsync(id)
.onItem().ifNull().failWith(
new NotFoundException("no inflation for id: " + id));
}
@Path("/virtual/{id}")
@GET
@RunOnVirtualThread
public Inflation getInflationWithVirtualThread(@PathParam("id") long id) {
return getInflationImperatively(id);
}
@Path("/imperative/{id}")
@GET
public Inflation getInflationImperatively(@PathParam("id") long id) {
var r = service.find(id);
if (r == null)
throw new NotFoundException("no inflation for id: " + id);
return r;
}
}
|
---
layout: post
title: "[파이썬] mpmath 통계 분포 및 밀도 함수"
description: " "
date: 2023-09-08
tags: [python,mpmath]
comments: true
share: true
---
mpmath is a Python library that provides arbitrary-precision arithmetic and mathematical functions. In this blog post, we will explore how to use mpmath to calculate various statistical distributions and their probability density functions (PDFs).
## Installing mpmath
Before we begin, make sure you have mpmath installed. You can install it using pip:
```
$ pip install mpmath
```
Once installed, we can import mpmath in our Python script or notebook:
```python
import mpmath
```
## Normal Distribution
The normal distribution, also known as the Gaussian distribution, is a continuous probability distribution defined by its mean and standard deviation. The PDF of the normal distribution is defined as:
```
f(x) = (1 / (sqrt(2π) * σ)) * exp(-(x - μ)^2 / (2σ^2))
```
where μ is the mean and σ is the standard deviation.
To calculate the PDF of the normal distribution using mpmath, we can use the `mpmath.normpdf` function:
```python
import mpmath
x = 1.5
mu = 0.0
sigma = 1.0
pdf = mpmath.normpdf(x, mu, sigma)
```
## Uniform Distribution
The uniform distribution is a continuous probability distribution where all values within a specified interval are equally likely. The PDF of the uniform distribution is defined as:
```
f(x) = 1 / (b - a) if a <= x <= b
```
where a and b are the lower and upper bounds of the interval.
To calculate the PDF of the uniform distribution using mpmath, we can use the `mpmath.uniformpdf` function:
```python
import mpmath
x = 0.5
a = 0.0
b = 1.0
pdf = mpmath.uniformpdf(x, a, b)
```
## Exponential Distribution
The exponential distribution is a continuous probability distribution that models the time between events in a Poisson process. The PDF of the exponential distribution is defined as:
```
f(x) = λ * exp(-λ * x)
```
where λ is the rate parameter.
To calculate the PDF of the exponential distribution using mpmath, we can use the `mpmath.exppdf` function:
```python
import mpmath
x = 1.5
rate = 2.0
pdf = mpmath.exppdf(x, rate)
```
---
In this blog post, we explored how to use mpmath to calculate the PDFs of various statistical distributions. mpmath provides a convenient and accurate way to perform arbitrary-precision arithmetic and can be a valuable tool for statistical calculations.
|
import React, { useState } from "react";
import GoogleRegistration from "./GoogleRegistration";
import FacebookRegistrationButton from "./FacebookRegistration";
const RegistrationPage = () => {
const [username, setUserName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [genre, setGenre] = useState([]);
const handleSubmit = (e) => {
e.preventDefault();
// Handle form submission here, e.g., send data to server or perform client-side validation
fetch('/users/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"username": username,
"email": email,
"genreSet": genre,
"password": password
})
})
.then(response => response.json())
.then(data => {
// Handle the response data
console.log(data);
})
.catch(error => {
// Handle any errors
console.error(error);
});
console.log("Form submitted!");
console.log("Username:", username);
console.log("Email:", email);
console.log("Password:", password);
console.log("Genres:", genre);
};
return (
<div>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="userName">Username:</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUserName(e.target.value)}
required
/>
</div>
<div>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div>
<label htmlFor="password">Password:</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<label for="cars">Choose your favorite genres:</label>
<select name="genres" id="genres" multiple>
<option value="pop">Pop</option>
<option value="rock">Rock</option>
<option value="techno">Techno</option>
</select>
<button type="submit">Register</button>
</form>
<div className="registerWithGoogle">
<GoogleRegistration />
</div>
<div>
<FacebookRegistrationButton />
</div>
</div>
);
};
export default RegistrationPage;
|
<script>
import { ref, onMounted, getCurrentInstance, defineComponent } from "vue";
import baseDetail from "../baseDetail";
import { ContractGroupDetailData } from "./ContractGroupDetailData";
import { comboboxColumns } from "../../common/comboboxColumns";
import { comboboxLoadData } from "../../common/comboboxLoadData";
import popupUtil from "../../components/base/DynamicModal/popupUtil";
import { confirmYes } from "../../common/dialogFn";
import commonFn from "../../common/commonFn";
export default defineComponent({
extends: baseDetail,
name: "ContractGroupDetail",
props: {},
setup() {
const { proxy } = getCurrentInstance();
const module = "ContractGroup";
const isDetailMaster = true;
const { columns } = ContractGroupDetailData();
const { apartmentColumns } = comboboxColumns();
const { loadApartmentData } = comboboxLoadData();
// Ấn từ các button thêm hợp đồng
const isAddContract = ref(false);
// Loại hợp đồng
const contractType = ref(0);
/**
* Gán thông tin chủ nhà
* @param {*} param
*/
const selectApartment = (param) => {
proxy.model.owner_name = param.obj.owner_name;
proxy.model.owner_id = param.obj.owner_id;
};
/**
* Thêm hợp đồng chi tiết
* @param {*} value
*/
const addContract = (value) => {
if (
proxy.mode == proxy.$constants.formMode.Add ||
(proxy.mode == proxy.$constants.formMode.Edit &&
commonFn.checkDiff(proxy.model, proxy.oldData))
) {
confirmYes(
"Thông báo",
"Thông tin Bộ hồ sơ đã thay đổi. Chương trình sẽ lưu lại trước khi tại mới các hợp đồng liên quan"
).then((answer) => {
if (answer) {
proxy.beforeShowContractForm(value);
}
});
} else {
proxy.beforeShowContractForm(value);
}
};
/**
* Trước khi show thì thêm mói/sủa master
* @param {*} value
*/
const beforeShowContractForm = (value) => {
isAddContract.value = true;
contractType.value = value;
// Nếu là form thêm mới thì cất trc khi thêm
if (
proxy.mode == proxy.$constants.formMode.Add ||
(proxy.mode == proxy.$constants.formMode.Edit &&
commonFn.checkDiff(proxy.model, proxy.oldData))
) {
// Cất/sửa master trước khi mở form thêm hợp đồng
proxy.saveAction();
} else {
// Nếu là form view thì mở form luôn
proxy.showContractForm();
}
};
// Overide hàm validate trc khi save
const validateBeforeSave = () => {
const me = proxy;
// validate control
if (!me.validateComponents()) {
// Hiển thị Alert
let title = "Cất không thành công";
let message = me.buildMes();
confirmYes(title, message).then((answer) => {
if (answer) {
// Tắt alert thì focus sau
me.$nextTick(() => {
me.focusFirstError();
});
}
});
return false;
}
return true;
};
// Build câu thông báo
const buildMes = () => {
let mes =
'Bạn cần nhập các thông tin <span class="strong-text">{0}</span> của Bộ hồ sơ';
let input = [];
if (!proxy.model.contract_group_name) {
input.push("Tên bộ hồ sơ");
}
if (!proxy.model.apartment_id) {
input.push("Căn hộ");
}
mes = commonFn.replaceTextWithHTML(mes, input.join(", "));
return mes;
};
// Sau khi thêm thành công thì chuyển sang mode sửa
const customAfterSaveSuccess = () => {
if (isAddContract.value) {
// Cất thành công thì mở form
proxy.showContractForm();
}
proxy.binđData(proxy.model, proxy.dataDetail);
};
// Mở form thêm hợp đồng
const showContractForm = () => {
proxy.mode = proxy.$constants.formMode.View;
let param = {
data: proxy.model,
mode: proxy.$constants.formMode.Add,
reloadDetail: proxy.reloadDetail,
};
switch (contractType.value) {
case 0:
popupUtil.show("ContractDetail", param);
break;
case 1:
break;
case 2:
break;
}
};
// Thực hiện sau khi save cho dù thành công hay không
const afterSave = () => {
isAddContract.value = false;
};
// Hiển thị form chi tiết hợp đồng
const editDetail = (row) => {
commonFn.mask();
const param = {
mode: proxy.$constants.formMode.View,
id: row.contract_id,
};
popupUtil.show("ContractDetail", param);
};
// Load lại trang
const reloadDetail = async () => {
try {
const res = await proxy.$axios.get(
`${proxy.module}/${proxy.model.contract_group_id}`
);
proxy.data = res.data.master;
proxy.dataDetail = res.data.details;
proxy.beforeBinđData(proxy.data, proxy.dataDetail);
proxy.binđData(proxy.data, proxy.dataDetail);
window._listDetail = proxy;
} catch (error) {
console.log(error);
}
};
return {
module,
columns,
apartmentColumns,
isAddContract,
contractType,
isDetailMaster,
selectApartment,
loadApartmentData,
addContract,
validateBeforeSave,
buildMes,
showContractForm,
customAfterSaveSuccess,
beforeShowContractForm,
afterSave,
editDetail,
reloadDetail,
};
},
});
</script>
<template>
<DynamicModal
ref="ContactDetail"
:title="`Hợp đồng ${model.contract_name || ''}`"
class="contact-group-detail"
position="full"
@beforeOpen="beforeOpen($event, close)"
@beforeClose="beforeClose($event)"
@opened="opened"
>
<template #content>
<div class="container-above">
<!-- Trái -->
<div class="container-left flex1">
<div class="grids-tab-header">
<div class="item-tabs item-tabs-active">Bộ hồ sơ</div>
</div>
<div class="grids-tab-content">
<div class="grids-tab-container">
<div class="modal-row">
<div class="m-label-text">Tên bộ hồ sơ</div>
<TheTextArea
class="flex1"
:disabled="isView"
v-model="model.contract_group_name"
:rules="[{ name: 'required' }]"
></TheTextArea>
</div>
</div>
</div>
</div>
<!-- Giữa -->
<div class="container-center flex1">
<div class="grids-tab-header">
<div class="item-tabs item-tabs-active">Các bên liên quan</div>
</div>
<div class="grids-tab-content">
<div class="grids-tab-container">
<div class="modal-row">
<div class="m-label-text">Căn hộ</div>
<TheComboBox
class="flex1"
valueField="apartment_id"
displayField="apartment_name"
:queryMode="'remote'"
v-model="model.apartment_id"
v-model:display="model.apartment_name"
:initValue="model.apartment_name"
:columns="apartmentColumns"
:loadComboboxData="loadApartmentData"
@selectItem="selectApartment"
:disabled="isView"
:rules="[{ name: 'required' }]"
></TheComboBox>
</div>
<div class="modal-row">
<div class="m-label-text">Chủ nhà</div>
<TheInput
:disabled="true"
class="flex1"
v-model="model.owner_name"
></TheInput>
</div>
</div>
</div>
</div>
<!-- Phải -->
<div class="container-right flex1"></div>
</div>
<div class="container-under">
<div class="grids-tab-header">
<div class="header-left">
<div class="item-tabs item-tabs-active">Chi tiết</div>
</div>
<div class="header-right">
<TheButton class="mr-10" @click="addContract(0)"
>+ HĐ thuê chủ - khách</TheButton
>
<TheButton class="mr-10" @click="addContract(1)"
>+ HĐ thuê chủ - công ty</TheButton
>
<TheButton @click="addContract(2)"
>+ HĐ thuê công ty - khách</TheButton
>
</div>
</div>
<div class="grids-tab-content">
<div class="grids-tab-container">
<GridViewer
:data="modelDetail"
@onDbClick="editDetail"
:columns="columns"
></GridViewer>
</div>
</div>
</div>
</template>
<template #footer>
<TheButton class="outline-button" @click="hide()">Đóng</TheButton>
<TheButton @click="setModeEdit()" v-if="isView">Sửa</TheButton>
<TheButton @click="saveAction()" v-else>Cất</TheButton>
</template>
</DynamicModal>
</template>
<style lang="scss">
.contact-group-detail {
.m-modal-header {
background-color: #f4f5f8;
}
.m-modal-content {
padding: 0;
.modal-row {
gap: unset;
.pl-10 {
padding-left: 10px;
}
}
}
.container-above {
padding: 0 16px;
background-color: #f4f5f8;
display: flex;
.container-left {
display: flex;
flex-direction: column;
padding-right: 8px;
border-right: 1px solid #c1c4cc;
}
.container-center {
display: flex;
flex-direction: column;
padding: 0 8px;
// border-right: 1px solid #c1c4cc;
}
.container-right {
display: flex;
flex-direction: column;
padding-left: 8px;
}
.m-label-text {
font-size: 13px;
font-weight: 700;
line-height: 15px;
height: 30px;
display: flex;
align-items: center;
min-width: 90px;
}
.input-money {
max-width: 150px;
}
}
.container-under {
overflow: hidden;
display: flex;
flex-direction: column;
flex: 1;
padding: 0 16px;
.mb10 {
margin-top: 10px;
}
.grids-tab-header {
border: none;
justify-content: space-between;
.mr-10 {
margin-right: 10px;
}
.header-right {
padding: 10px 0;
}
.header-left {
display: flex;
.item-tabs-active {
color: #026aba;
font-weight: 600;
text-decoration: underline;
border: none;
}
}
}
.grids-tab-content {
overflow: hidden;
flex: 1;
padding-top: unset;
.grids-tab-container {
height: 100%;
}
}
}
}
</style>
|
//
// AppDelegate.swift
// BlockStackBrowser
//
// Created by lsease on 6/26/17.
// Copyright © 2017 blockstack. All rights reserved.
//
import UIKit
import BlockstackCoreApi_iOS
import SwiftyDropbox
import Google
import GoogleSignIn
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
DropboxService.shared().setup()
GoogleDriveService.shared().setup()
AmazonCloudDriveService.shared().setup()
// Override point for customization after application launch.
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
//handle authorization requests from 3rd party apps
if let scheme = url.scheme, scheme == "blockstack",
let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems,
let requestToken = queryItems.filter({ $0.name == "authRequest"}).first?.value
{
ExteralAuthorizationService.shared().processAuthorization(with: requestToken)
return true
}
//handle dropbox auth
else if let authResult = DropboxClientsManager.handleRedirectURL(url) {
switch authResult {
case .success:
print("Success! User is logged into Dropbox.")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: Constants.Notifications.dropboxStatusChanged), object: nil)
case .cancel:
print("Authorization flow was manually canceled by user!")
case .error(_, let description):
print("Error: \(description)")
}
return true
}
//google drive auth
else if let scheme = url.scheme, scheme.contains("com.googleusercontent.apps") {
let sourceApplication = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String
let annotation = options[UIApplicationOpenURLOptionsKey.annotation]
return GIDSignIn.sharedInstance().handle(url,
sourceApplication: sourceApplication,
annotation: annotation)
}
//amazon auth
else if let scheme = url.scheme, scheme.contains("amzn") {
let sourceApplication = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String
return AIMobileLib.handleOpen(url, sourceApplication: sourceApplication)
}
return false
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
UserDataService.shared().saveProfiles()
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
import React, { useState, useEffect } from "react";
import { fetchVideos } from "./api";
import Video from "./components/Video";
import "./App.css";
function App() {
const [videos, setVideos] = useState([]);
const [page, setPage] = useState(0);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchData() {
try {
const data = await fetchVideos(page);
console.log(data.data.posts);
setVideos(data.data.posts);
setError(null); // Reset error on success
} catch (error) {
console.error("Error fetching videos:", error);
setError("An error occurred while fetching videos.");
}
}
fetchData();
}, [page]);
return (
<div className="App">
<h1 className="Title">Video Clone</h1>
<div className="pagination">
<button
onClick={() => setPage((prevPage) => prevPage - 1)}
disabled={page === 0}
>
Previous Page
</button>
<p>Page {page + 1}</p>
<button
onClick={() => setPage((prevPage) => prevPage + 1)}
// Disable if no more videos disabled={videos.length === 0}
>
Next Page
</button>
</div>
{error && <p className="error">{error}</p>}
<div className="video-list">
{videos?.map((video) => (
<Video key={video.postId} video={video} />
))}
</div>
</div>
);
}
export default App;
|
"use client"
import { useState, useEffect } from "react"
import PromptCard from "./PromptCard"
const PromptCardList = ({ data, handleTagClick }) => {
return <div className="mt-16 prompt_layout">
{data.map((post) => (
<PromptCard
key={post._id}
post={post}
handleTagClick={handleTagClick}
/>
))}
</div>
}
const Feed = () => {
const [searchText, setSearchText] = useState('')
const [posts, setPosts] = useState([])
const [searchTimeout, setSearchTimeout] = useState(null);
const [searchedResults, setSearchedResults] = useState([]);
const handleSearchChange = (e) => {
clearTimeout(searchTimeout);
setSearchText(e.target.value);
// debounce method
setSearchTimeout(
setTimeout(() => {
setSearchedResults(e.target.value);
}, 500)
);
}
useEffect(() => {
const fetchPosts = async () => {
const res = await fetch(`/api/prompt?search=${searchedResults}`)
const data = await res.json()
setPosts(data)
}
fetchPosts()
}, [searchedResults])
return (
<section className="feed">
<form onSubmit={(e) => e.preventDefault()} className="relative w-full flex-center">
<input
type="text"
placeholder='Search for a tag or a username'
value={searchText}
onChange={handleSearchChange}
required
className='search_input peer'
/>
</form>
<PromptCardList
data={posts}
handleTagCLick={() => { }}
/>
</section>
)
}
export default Feed
|
// コングラチュレーション画面
//
// こちらがオリジナルです。
// 【作者】Ivan Rudnickiさん
// 【作品名】Slot Machine
// https://openprocessing.org/sketch/1025533
//
class GameSceneCongratulations48 extends GameSceneCongratulationsBase {
//final String[] reel0={"7", "Bell", "Berry", "Orange", "Berry", "Cherry", "Berry", "Bar", "Berry", "Orange", "Berry", "Cherry", "Berry", "Bar", "Berry", "Orange", "Berry", "Cherry", "Berry", "Bar", "Berry", "Orange"};
//final String[] reel1={"7", "Berry", "Bar", "Cherry", "Bar", "Orange", "Bar", "Bell", "Bar", "Cherry", "Bar", "Orange", "Bar", "Bell", "Bar", "Cherry", "Bar", "Orange", "Bar", "Bell", "Bar", "Cherry"};
//final String[] reel2={"7", "Berry", "Bell", "Orange", "Bell", "Berry", "Bell", "Orange", "Bell", "Berry", "Bell", "Bar", "Bell", "Orange", "Bell", "Berry", "Bell", "Orange", "Bell", "Berry", "Bell", "Orange"};
final String[] reel0={"7", "Bell", "Berry", "Orange", "Berry", "Cherry", "Berry", "Bar", "Berry", "Orange", "Berry", "Cherry", "Berry", "Bar", "Berry", "Orange", "Berry", "Cherry", "Berry", "Bar"};
final String[] reel1={"7", "Berry", "Bar", "Cherry", "Bar", "Orange", "Bar", "Bell", "Bar", "Cherry", "Bar", "Orange", "Bar", "Bell", "Bar", "Cherry", "Bar", "Orange", "Bar", "Bell"};
final String[] reel2={"7", "Berry", "Bell", "Orange", "Bell", "Berry", "Bell", "Orange", "Bell", "Berry", "Bell", "Bar", "Bell", "Orange", "Bell", "Berry", "Bell", "Orange", "Bell", "Berry"};
final String[][] reels={reel0, reel1, reel2};
PImage[] strips= new PImage[3];
Wheel[] wheels = new Wheel[3];
ArrayList<Coin> coins = new ArrayList();
//let click, lever, coins1, coins2;
Arm arm;
Cabinet cabinet;
Chart chart;
PImage logo;
PFont font;
int counter0=0;
int counter1=10000;
int counter1target=0;
PVector rotate, rotatev;
float total=0.0f;
// 360°を割り切れるようにしたいので図柄を22[個]から20[個]に変更した
final float MARK_NUM = 20;
PGraphics pg;
void P5preload() {
strips[0] = loadImage("data/48/20Strip1.jpg");
strips[1] = loadImage("data/48/20Strip2.jpg");
strips[2] = loadImage("data/48/20Strip3.jpg");
logo = loadImage("data/48/Bally.png");
mMA.entry("click", "data/48/clicker.mp3");
mMA.entry("lever", "data/48/lever.mp3");
mMA.entry("coins1", "data/48/coins.wav");
mMA.entry("coins2", "data/48/coins2.wav");
font = createFont("data/48/ArchivoBlack-Regular.ttf", 50, true);
}
@Override void setup() {
colorMode(RGB, 255);
imageMode(CORNER);
pg = createGraphics(width, height);
pg.beginDraw();
logo(pg, color(255, 0, 0));
pg.endDraw();
P5preload();
// angleMode(DEGREES);
for (int i=0; i<3; i++) {
PVector pos = new PVector(-60+(i*60), 0, 0);
wheels[i] = new Wheel(pos, strips[i], i);
}
arm = new Arm();
cabinet = new Cabinet();
chart = new Chart();
//reels.push(reel0);
//reels.push(reel1);
//reels.push(reel2);
logo.resize(160, 0);
imageMode(CENTER);
textFont(font);
counter0=0;
rotate = new PVector(180, -180, 0);
rotatev = new PVector(-9, 9, 0);
}
@Override void draw() {
push();
translate(width / 2, height / 2, +200);
checkKeys();
setScene();
for (Wheel w : wheels) {
w.spin();
w.show();
}
arm.rotate();
arm.show();
counter0+=1;
if (counter0==60) {
threeBarSpin();
}
if (counter0==120) {
arm.angtarget.x=-30;
}
cabinet.show();
chart.show();
for (Coin c : coins) {
if (c.alive) c.move();
c.show();
}
push();
scale(0.8);
translate(0, -140, 110 + 50);
image(pg, 0, 0);
pop();
counter1+=1;
if (counter1%10==0 && counter1<=counter1target) {
coins.add(new Coin());
total+=0.25;
}
if (counter0==260) {
checkResult();
}
pop();
}
void setScene() {
background(0);
// lights();
ambientLight(200, 200, 200);
// pointLight(150, 150, 150, 200, 200, 200);
pointLight(255, 255, 255, 200, 200, 200);
pointLight(255, 255, 255, 200, 200, 200);
pointLight(255, 255, 255, 200, 200, 200);
pointLight(255, 255, 255, 200, 200, 200);
pointLight(255, 255, 255, 200, 200, 200);
// orbitControl(1, 1, 0.1);
scale(0.9);
rotate.add(rotatev);
rotatev.mult(0.95);
rotateX(radians(rotate.x));
rotateY(radians(rotate.y));
translate(0, -50, 0);
}
void checkKeys() {
if (keyCode==RIGHT) rotatev.y+=0.3;
if (keyCode==LEFT) rotatev.y-=0.3;
if (keyCode==DOWN) rotatev.x-=0.3;
if (keyCode==UP) rotatev.x+=0.3;
}
void threeBarSpin() {
arm.angtarget.x=-80;
mMA.playAndRewind("lever");
wheels[0].av=28.146454;
wheels[0].spinning=true;
wheels[1].av=121.12816;
wheels[1].spinning=true;
wheels[2].av=543.10364;
wheels[2].spinning=true;
}
void spinWheels() {
if (arm.angtarget.x!=-80 && counter1>counter1target+30 && wheels[2].spinning==false) {
if (total>0) {
total-=0.25;
// coins.pop();
if (0 < coins.size()) {
coins.remove(coins.size()-1);
}
arm.angtarget.x=-80;
counter0=61;
mMA.playAndRewind("lever");
wheels[0].av=random(20, 40);
wheels[0].spinning=true;
wheels[1].av=random(100, 150);
wheels[1].spinning=true;
wheels[2].av=random(500, 550);
wheels[2].spinning=true;
} else {
mMA.playAndRewind("coins1");
}
}
}
void checkResult() {
String itema = reels[wheels[0].id][(int)wheels[0].a];
String itemb = reels[wheels[1].id][(int)wheels[1].a];
String itemc = reels[wheels[2].id][(int)wheels[2].a];
if (itema == "7" && itemb == "7" && itemc == "7") makeCoins(80);
if (itema == "Bar" && itemb == "Bar" && itemc == "Bar") makeCoins(20);
if (itema == "Bell" && itemb == "Bell" && itemc == "Bell") makeCoins(18);
if (itema == "Bell" && itemb == "Bell" && itemc == "Bar") makeCoins(18);
if (itema == "Berry" && itemb == "Berry" && itemc == "Berry") makeCoins(15);
if (itema == "Berry" && itemb == "Berry" && itemc == "Bar") makeCoins(15);
if (itema == "Orange" && itemb == "Orange" && itemc == "Orange") makeCoins(10);
if (itema == "Orange" && itemb == "Orange" && itemc == "Bar") makeCoins(10);
if (itema == "Cherry" && itemb == "Cherry") makeCoins(5);
else if (itema=="Cherry") makeCoins(3);
}
void makeCoins(int number) {
counter1=0;
counter1target=10*number;
}
class Arm {
PVector pos;
PVector ang;
PVector angtarget;
PShape[] cylinders = new PShape[4];
Arm() {
this.pos = new PVector(120, 120, 40);
this.ang = new PVector(-30, 0, 0);
this.angtarget = new PVector(-30, 0, 0);
cylinders[0] = createCan(10, 42, 24, true, true);
cylinders[0].setFill(color(250, 0, 0, 150));
cylinders[1] = createCan(20, 20, 24, true, true);
cylinders[1].setFill(color(100));
cylinders[2] = createCan(5, 100, 24, true, true);
cylinders[2].setFill(color(100));
cylinders[3] = createCan(5, 100, 24, true, true);
cylinders[3].setFill(color(100));
}
void rotate() {
this.ang.x+=(this.angtarget.x-this.ang.x)/3.0f;
}
void show() {
push();
translate(this.pos.x, this.pos.y, this.pos.z);
rotateX(radians(this.ang.x));
rotateY(radians(this.ang.y));
rotateZ(radians(this.ang.z));
noStroke();
rotateZ(radians(90));
// specularMaterial(250, 0, 0, 150);
// fill(color(250, 0, 0, 150));
// cylinder(10, 42);
shape(cylinders[0]);
translate(0, -10, 0);
// specularMaterial(100);
// fill(100);
// cylinder(20, 20);
shape(cylinders[1]);
rotateZ(radians(-90));
translate(0, -50, 0);
// cylinder(5, 100);
shape(cylinders[2]);
translate(0, -50, 0);
sphere(5);
rotateX(radians(30));
translate(0, -50, 0);
// cylinder(5, 100);
shape(cylinders[3]);
translate(0, -50, 0);
// specularMaterial(250, 0, 0, 150);
fill(color(250, 0, 0, 150));
sphere(16);
pop();
}
}
class Cabinet {
Cabinet() {
}
void show() {
push();
translate(0, 195, 110);
noStroke();
// specularMaterial(100);
fill(100);
translate(0, 40, 0);
box(160, 30, 4);
translate(0, 0, 60);
box(160, 30, 1);
translate(0, 0, 2);
textAlign(CENTER, CENTER);
textSize(24);
push();
fill(50);
if (total>0) text("$"+String.format("%.02f", total), 0, 0);
else text("BUST!", 0, 0);
pop();
translate(-80, 0, -32);
box(1, 30, 60);
translate(160, 0, 0);
box(1, 30, 60);
translate(-80, 15, 0);
box(160, 1, 60);
translate(0, -248, -42);
// specularMaterial(255, 0);
fill(color(255, 255, 255, 0));
//stroke(200);
box(150, 40, 22); //Reel slot
translate(0, 195, 0);
box(120, 30, 22); //Coin slot
translate(0, -115, -100);
// specularMaterial(250, 0, 0, 80);
fill(color(250, 0, 0, 80));
box(200, 400, 220); //Body
translate(0, -242, 80);
box(logo.width, logo.height, 10);
translate(0, 0, 6);
tint(180, 0, 0);
image(logo, 0, 0);
pop();
}
}
class Chart {
Chart() {
}
void show() {
push();
translate(0, 105, 112);
// specularMaterial(200);
fill(200);
textAlign(CENTER, CENTER);
textSize(9);
text("7 - 7 - 7 = 50", 0, 0);
text("Bar - Bar - Bar = 20", 0, 8);
text("Bell - Bell - Bell = 18", 0, 16);
text("Berry - Berry - Berry = 15", 0, 24);
text("Berry - Berry - Bar = 15", 0, 32);
text("Orange - Orange - Orange = 12", 0, 40);
text("Orange - Orange - Bar = 10", 0, 48);
text("Cherry - Cherry - Any = 5", 0, 56);
text("Cherry - Any - Any = 3", 0, 64);
pop();
}
}
class Coin {
PVector pos;
PVector posv;
PVector ang;
PVector angv;
boolean alive;
PShape cylinder;
Coin() {
this.pos = new PVector(random(-12, 12), 170, 85);
this.posv = new PVector(random(-2, 2), 0, random(2, 3.5));
this.ang = new PVector(0, 0, 0);
this.angv = new PVector(random(-30, 30), random(-10, 10), 0);
this.alive=true;
cylinder = createCan(12, 2, 24, true, true);
cylinder.setFill(color(207, 181, 159));
}
void move() {
if (this.pos.y<230) {
this.pos.add(this.posv);
this.ang.add(this.angv);
this.posv.y+=.3;
} else {
this.posv = this.posv.mult(0);
this.angv = this.angv.mult(0);
this.pos.y+=10;
this.ang.mult(0);
mMA.playAndRewind("coins2");
this.alive=false;
}
}
void show() {
push();
translate(this.pos.x, this.pos.y, this.pos.z);
rotateX(radians(this.ang.x));
rotateY(radians(this.ang.y));
rotateZ(radians(this.ang.z));
noStroke();
// specularMaterial(207, 181, 159);
// cylinder(12, 2);
shape(cylinder);
pop();
}
}
class Wheel {
PVector pos;
float a;
float av;
PImage txt;
boolean spinning;
int id;
PShape cylinder;
Wheel(PVector pos, PImage txt, int id) {
this.pos=pos;
this.a=0;
this.av=0;
this.txt=txt;
this.spinning=false;
this.id=id;
cylinder = createCan((800/TWO_PI), this.txt.height, 20);
cylinder.setTexture(this.txt);
}
void spin() {
this.a+=this.av;
this.av*=0.95;
if (this.av<0.1) {
this.av=0;
this.a=floor(this.a);
this.a%=MARK_NUM;
if (this.spinning) {
mMA.playAndRewind("click");
this.spinning=false;
}
}
}
void show() {
push();
scale(0.8);
translate(this.pos.x, this.pos.y, this.pos.z);
rotateZ(radians(-90));
rotateY(radians((360/MARK_NUM*this.a)+7));
// if (this.id==0) P5RotateY(1); //Fix left wheel alignment
texture(this.txt);
noStroke();
// cylinder(800/TWO_PI, this.txt.height, 24, 1, false, false);
shape(cylinder);
pop();
}
}
@Override void mousePressed() {
gGameStack.change(new GameSceneTitle());
}
@Override void keyPressed() {
super.keyPressed();
if (keyCode==32) spinWheels();
}
@Override void keyReleased() {
keyCode = 0;
}
}
|
@php
use App\capacitacion_user;
@endphp
@extends('layouts.app')
@section('content')
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header"><h2>Detalle de capacitación por colaborador</h2></div>
<div class="card-body">
@include('custom.message')
<input id="id_capacitacion" type="text" hidden name="id_capacitacion" value="{{ $id_capacitacion }}">
<div class="row">
@can('haveaccess','contacto.show')
<div class="col-6 col-sm-6 col-md-3 col-lg-2">
<button id="guardarcambios" class="btn btn-success btn-block" disabled><b>Guardar cambios</b></button>
</div>
<div class="col-6 col-sm-6 col-md-3 col-lg-2">
<a href="{{ route('capacitacion.show',$id_capacitacion) }}" class="btn btn-warning btn-block" title="Editar capacitación">Editar capacitación</a>
</div>
<div class="col-0 col-sm-0 col-md-3 col-lg-4">
</div>
<div class="col-0 col-sm-0 col-md-3 col-lg-4">
</div>
@endcan
</div>
<br>
<!--
<div class="form-group row float-right">
<label for="finalizar" class="col-md-7">{{ __('Finalizar todos') }}</label>
<div class="col-md-2">
<label class="switch">
<input type="checkbox" class="warning" name="finalizar" id="finalizarclass">
<span class="slider round"></span>
</label>
</div>
</div>
-->
<div class="table-responsive-md">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Código</th>
<th scope="col">Capacitación</th>
<th scope="col">Modalidad</th>
<th scope="col">Fecha inicio</th>
<th scope="col">Fecha fin</th>
<th scope="col">Horas</th>
<th scope="col">Costo</th>
<th scope="col">Colaborador</th>
<th scope="col">Finalizado</th>
<th colspan=3></th>
</tr>
</thead>
<tbody>
@foreach ($capacitaciones as $capacitacion)
<tr>
<th scope="row">{{ $capacitacion->codigo }}</th>
<th scope="row">{{ $capacitacion->nombre }}</th>
<th scope="row">{{ $capacitacion->modalidad }}</th>
<th scope="row">{{ date('d/m/Y',strtotime($capacitacion->fechainicio)) }}</th>
<th scope="row">{{ date('d/m/Y',strtotime($capacitacion->fechafin)) }}</th>
<th scope="row">{{ $capacitacion->horas }}</th>
<th scope="row">US$ {{ $capacitacion->costo }}</th>
<th scope="row">{{ $capacitacion->name }} {{ $capacitacion->last_name }}</th>
<th scope="row">{{ $capacitacion->estado }}</th>
<!--
<th scope="row" onclick="javascript:cambiocheck({{ $capacitacion->id_user }});">
<div class="col-md-2">
<label class="switch">
<input type="checkbox" class="finalizarclass warning" id="{{ 'chk'.$capacitacion->id_user }}" name="{{ $capacitacion->id_user }}"
@if($capacitacion->estado == "Finalizado")
checked
@endif
>
<span class="slider round"></span>
</label>
</div>
</th>
-->
@can('haveaccess','capacitacion.show')
<th><a href="{{ route('capacitacion_user.show',$capacitacion->id_cap_user) }}" title="Detalle"><img src="{{ asset('/imagenes/config.png') }}" height="20"></a> </th>
@endcan
</tr>
@endforeach
</tbody>
</table>
</div>
<div class="d-flex justify-content-center">
{!! $capacitaciones->links() !!}
</div>
</div>
</div>
</div>
</div>
</div>
<script type="application/javascript">
/*
function cambiocheck(check){
chkbox = document.getElementById('chk'+check);
$('#guardarcambios').attr('disabled', false);
if (chkbox.checked) {
chkbox.checked='';
}
else {
chkbox.checked='true';
}
}
*/
$(document).ready(function(){
$('#finalizarclass').change(function(){
chkid = $(this).attr('id');
$('#guardarcambios').attr('disabled', false);
chkboxlider = document.getElementById(chkid);
chkbox = document.getElementsByClassName(chkid);
totalchk = chkbox.length;
for (let i = 0; i < chkbox.length; i++) {
if (chkboxlider.checked) {
chkbox[i].checked='true';
}
else {
chkbox[i].checked='';
}
}
});
$('#guardarcambios').click(function(){
chkid = 'finalizarclass';
chkboxlider = document.getElementById(chkid);
chkbox = document.getElementsByClassName(chkid);
totalchk = chkbox.length;
var _token = $('input[name="_token"]').val();
var id_capacitacion = $('#id_capacitacion').val();
var id_usuario = new Array();
var estado = new Array();
this.disabled = true;
for (let i = 0; i < totalchk; i++) {
id_usuario[i] = chkbox[i].name;
if (chkbox[i].checked) {
estado[i] = 'Finalizado';
}
else {
estado[i] = 'Inscripto';
}
}
/*
$.ajax({
url:"{{ route('capacitacion.editestado') }}",
method:"POST",
data:{_token:_token,estado:estado, id_usuario:id_usuario, id_capacitacion:id_capacitacion},
error:function()
{
alert("Ha ocurrido un error, intentelo más tarde");
this.disabled = false;
},
success:function(data)
{
}
})
*/
$.ajax({
url:"{{ route('capacitacion.editestado') }}",
method:"POST",
data:{_token:_token,'estado': JSON.stringify(estado), id_capacitacion:id_capacitacion,cantidad:totalchk,'id_usuario': JSON.stringify(id_usuario)},
error:function()
{
alert("Ha ocurrido un error, intentelo más tarde");
this.disabled = false;
},
success:function(data)
{
alert('Se ha modificado con éxito el estado de finalización');
window.location = data.url
//alert(data);
}
})
});
});
</script>
@endsection
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Still Life Project</title>
<link rel="stylesheet" href="styles.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Indie+Flower&family=Limelight&family=Notable&family=Poller+One&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Indie+Flower&family=Limelight&family=Notable&family=Poller+One&display=swap" rel="stylesheet">
</head>
<style>
body {
background-color: lightgrey;
}
/* frame */
section {
background-color: darkgray;
border: 1px solid grey;
width: 700px;
height: 700px;
margin: 0 auto;
margin-top: 25px;
z-index: 0;
}
* {
border-radius: 10px;
}
#table-line {
position: absolute;
top: 450px;
height: 275px;
background-color: saddlebrown;
z-index: 0;
width: 700px;
}
.kettle {
position: relative;
width: 300px;
top: 60px;
left: 40px;
}
#black-cap {
border-bottom: 45px solid black;
border-left: 12.5px solid transparent;
border-right: 12.5px solid transparent;
height: 0;
width: 40px;
position: relative;
top: 25px;
left: 85px;
transform: rotate(180deg) scaleX(-1);
}
/* kettle body */
#red-kettle {
transform: rotate(180deg) scaleX(-1);
border-bottom: 200px solid red;
border-left: 35px solid transparent;
border-right: 35px solid transparent;
height: 0;
width: 215px;
position: relative;
border-radius: 10px;
top: 65px;
left: -22px;
}
/* rounded lid */
#red-kettle::before {
content: "";
display: block;
background-color: red;
height: 70px;
width: 277px;
position: relative;
border-bottom-left-radius: 50%;
border-bottom-right-radius: 50%;
top: 175px;
left: -31px;
}
/* kettle base */
#red-kettle::after {
content: "";
display: block;
background-color: red;
height: 50px;
width: 190px;
position: relative;
top: -115px;
left: 15px;
}
#silver-base {
content: "";
border-bottom: 200px solid lightgray;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
width: 225px;
position: relative;
top: 100px;
left: -15px;
z-index: 0;
overflow: hidden;
}
/* spout */
#silver-base::before {
content: "";
width: 10px;
height: 10px;
position: absolute;
top: 10px;
left: 10px;
border-style: solid;
border-width: 0px 0 15px 20px;
border-color: transparent transparent transparent black;
transform: rotate(-35deg) scaleX(-1);
}
#silver-base::after {
border-radius: 100%;
position: absolute;
background: green;
right: -500px;
left: -500px;
top: -200px;
content: "";
bottom: -210px;
z-index: 0;
}
.mug-stack {
position: relative;
top: 0px;
left: 20px;
z-index: 1;
}
/* white mug body */
#stripped-mug {
content: "";
position: relative;
background-color: white;
height: 115px;
width: 130px;
top: -60px;
left: 265px;
}
/* white round handle */
#stripped-mug::before {
content: " ";
display: block;
box-sizing: border-box;
position: absolute;
border: 15px solid white;
width: 75px;
height: 60px;
left: 50%;
margin-left: -115px;
top: 25px;
border-top-left-radius: 7em;
border-top-right-radius: 7em;
transform: rotate(-90deg) scaleX(-1);
}
/* blue stripes */
#mug-flag {
height: 95px;
width: 120px;
border-radius: 0px;
left: 10px;
top: 10px;
z-index: 1;
position: relative;
background: linear-gradient(to bottom,
blue 0%, blue 20%,
white 0%, white 40%,
blue 0%, blue 60%,
white 0%, white 80%,
blue 0%);
}
/* red triangle */
#mug-flag::before {
width: 0;
height: 0;
display: block;
content: "";
border-left: 60px solid red;
border-top: 45px solid transparent;
border-bottom: 50px solid transparent;
}
/* mug flag star */
#mug-flag p {
color: white;
position: relative;
font-size: 25px;
top: -95px;
left: 5px;
}
/* solo mug */
#stripped-mug.turned {
position: relative;
top: -530px;
left: 500px;
z-index: 1;
}
/* blue stripes */
#stripped-mug.turned #mug-flag {
width: 130px;
left: 0px;
}
/* hide red triangle */
#stripped-mug.turned #mug-flag::before {
display: none;
}
/* mug handle space */
#stripped-mug.turned::before {
width: 35px;
border-radius: 0;
border-top-right-radius: 50%;
border-bottom-right-radius: 50%;
border: 20px solid white;
transform: unset;
height: 100px;
top: 5px;
left: 180px;
z-index: 2;
}
#coffee-jar {
position: relative;
z-index: 0;
width: 300px;
height: 370px;
top: -530px;
left: 390px;
overflow: hidden;
}
/* yellow lid */
#coffee-jar::before {
border-radius: 100%;
position: absolute;
background: gold;
right: -500px;
left: -500px;
top: -200px;
content: "";
bottom: 340px;
z-index: 1;
}
#yellow-label {
background-color: yellow;
width: 300px;
height: 235px;
top: -550px;
left: 390px;
}
/* rounded bottom */
#yellow-label::after {
border-radius: 100%;
position: absolute;
background: yellow;
right: -500px;
left: -500px;
top: -200px;
content: "";
bottom: 100px;
z-index: 0;
}
#red-label {
background-color: red;
z-index: -2;
height: 115px;
}
#red-label::before {
border-radius: 100%;
position: absolute;
background: red;
right: -500px;
left: -500px;
top: -200px;
content: "";
bottom: 10px;
z-index: -1;
}
#red-label::after {
border-radius: 100%;
position: absolute;
background: lightgrey;
right: -500px;
left: -500px;
top: -200px;
content: "";
bottom: 0px;
z-index: -2;
}
#yellow-label h3 {
text-align: center;
padding: 0;
margin: 0;
z-index: 100;
position: relative;
width: 50px;
top: 80px;
left: 60px;
font-size: 60px;
font-family: "Indie Flower", cursive, "Limeligh", cursive;
}
#yellow-label p {
text-align: center;
padding: 0;
margin: 0;
z-index: 100;
position: relative;
top: 90px;
left: 20px;
font-family: "Poller One", cursive, "Notable", sans-serif;
}
#red-label p {
color: white;
text-align: center;
padding: 0;
margin: 0;
z-index: 100;
position: relative;
top: 50px;
left: 25px;
font-size: 12px;
font-family: sans-serif;
font-weight: bold;
}
svg {
text-align: center;
padding: 0;
margin: 0;
z-index: 100;
position: relative;
font-size: 98px;
font-family: "Limelight", cursive;
transform: rotate(-1deg) scaleX(1);
}
#cafe {
top: -50px;
}
#bustelo {
top: -280px;
}
#always {
top: -120px;
font-size: 20px;
}
#always text {
fill: white;
font-family: sans-serif;
font-weight: bold;
}
#netwt {
top: -365px;
left: 50px;
font-family: sans-serif;
font-weight: bold;
font-size: 20px;
}
#netwt text {
fill: white;
transform: rotate(-2.5deg) scaleX(1);
}
#espresso {
top: -530px;
font-size: 22px;
left: 20px;
font-family: "Poller One", cursive, "Notable", sans-serif;
transform: rotate(-2deg) scaleX(1);
}
path {
fill: transparent;
}
text {
fill: black;
}
</style>
<body>
<section>
<div id="table-line"></div>
<div class="kettle">
<div id="black-cap"></div>
<div id="red-kettle"></div>
<div id="silver-base"></div>
</div>
<div class="mug-stack">
<div id="stripped-mug">
<div id="mug-flag">
<p>★</p>
</div>
</div>
<div id="stripped-mug">
<div id="mug-flag">
<p>★</p>
</div>
</div>
</div>
<div id="stripped-mug" class="turned">
<div id="mug-flag"></div>
</div>
<div id="coffee-jar">
<div id="yellow-label">
<svg viewbox="0 0 500 500" id="cafe">
<path id="curve" d="M100,300 C228,311 382,310 500,300" />
<text width="500">
<textpath xlink:href="#curve">
Cafe
</textpath>
</text>
</svg>
<svg viewbox="0 0 500 500" id="bustelo">
<path id="curve" d="M100,300 C228,311 382,310 500,300" />
<text width="500">
<textpath xlink:href="#curve">
Bustelo
</textpath>
</text>
</svg>
<svg viewbox="0 0 500 500" id="espresso">
<path id="curve" d="M100,300 C228,311 382,310 500,300" />
<text width="500">
<textpath xlink:href="#curve">
Espresso Ground Coffee
</textpath>
</text>
</svg>
</div>
<div id="red-label">
<svg viewbox="0 0 500 500" id="always">
<path id="curve" d="M100,300 C228,311 382,310 500,300" />
<text width="500">
<textpath xlink:href="#curve">
ALWAYS PURE AND FLAVORFUL, LIKE NO
</textpath>
</text>
</svg>
<svg viewbox="0 0 500 500" id="netwt">
<path id="curve" d="M100,300 C228,311 382,310 500,300" />
<text width="500">
<textpath xlink:href="#curve">
NET WT 10 OZ (238g)
</textpath>
</text>
</svg>
</div>
</div>
</section>
</body>
</html>
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <semaphore.h>
#include "library.h"
#include <time.h>
#include <stdbool.h>
#define PATH "./" // Ścieżka do pliku
char semaphore_name[20];
bool synchronization;
void exit_handler(void) {
if (synchronization) {
remove_semaphore(semaphore_name); // Usuwanie semafora
}
}
void exit_signal_handler(int signal) {
if (synchronization) {
printf("Interrupt signal received, removing the semaphore.\n"); // Sygnał przerwania otrzymany, usuwanie semafora
remove_semaphore(semaphore_name); // Usuwanie semafora
}
_exit(EXIT_SUCCESS);
}
void validate_input(int argc, char* argv[]) {
if (argc != 7) {
printf("Incorrect number of arguments!\n");
printf("To run the program, use: %s subprogram_name num_incrementors num_critical_sections file_in_out semaphore_name synchronization\n", argv[0]);
exit(EXIT_FAILURE);
}
}
void validate_atexit() {
if (atexit(exit_handler) != 0) {
perror("atexit error");
exit(EXIT_FAILURE);
}
}
void validate_signal_setup() {
if (signal(SIGINT, exit_signal_handler) == SIG_ERR) {
perror("Signal error");
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[]) {
validate_input(argc, argv);
validate_atexit();
validate_signal_setup();
int stat_lock;
int num_incrementors;
int file;
char temp[strlen(PATH) + strlen(argv[1]) + 1]; // Tworzenie bufora tymczasowego
num_incrementors = atoi(argv[2]); // Pobieranie liczby inkrementorów
strcpy(semaphore_name, argv[5]); // Kopiowanie nazwy semafora
if (atoi(argv[6]) == 0) {
synchronization = false;
}
else {
synchronization = true;
}
if ((file = open(argv[4], O_WRONLY | O_CREAT | O_TRUNC, 0644)) == -1) {
printf("Error opening file %s for writing", argv[1]);
perror("File error");
exit(EXIT_FAILURE);
}
if (write(file, "0", 2) == -1) {
perror("Error writing to file");
exit(EXIT_FAILURE);
}
if (close(file) == -1) {
perror("Error closing file");
exit(EXIT_FAILURE);
}
if (synchronization) {
sem_t *semaphore = create_semaphore(semaphore_name); // Tworzenie semafora
int semaphore_value;
get_semaphore_value(semaphore, &semaphore_value); // Pobieranie wartości semafora
printf("Semaphore %s (%p) created with value %d\n", semaphore_name, (void *)semaphore, semaphore_value); // Wyświetlanie informacji o semaforze
}
int j=0;
while(j<num_incrementors) {
switch (fork()) {
case -1:
perror("Fork error");
exit(EXIT_FAILURE);
case 0:
sprintf(temp, "%s%s", PATH, argv[1]); // Formatowanie ścieżki do inkrementora
execl(temp, argv[1], argv[3], argv[4], argv[5], argv[6], NULL); // Wykonanie inkrementora
perror("Execl error");
exit(EXIT_FAILURE);
break;
default:
// Kod procesu macierzystego
break;
}
j++;
}
// Oczekiwanie na zakończenie procesów potomnych przy użyciu funkcji wait.
// Pętla wykonuje się `num_incrementors` razy.
int k=0;
while(k<num_incrementors){
if (wait(&stat_lock) == -1) { // Wywołanie funkcji wait, oczekiwanie na zakończenie procesu potomnego
perror("Wait error");
exit(EXIT_FAILURE);
}
k++;
}
// Otwieranie pliku w trybie do odczytu.
// Nazwa pliku jest pobierana z `argv[4]`.
// Jeśli otwarcie pliku nie powiedzie się, wyświetlany jest błąd i program kończy działanie.
int read_result;
char buffer[10];
if ((file = open(argv[4], O_RDONLY, 0644)) == -1) {
printf("Error opening file %s for reading", argv[4]);
perror("File error");
exit(EXIT_FAILURE);
}
// Odczyt danych z pliku do bufora `buffer`.
// Wartość zwracana przez funkcję `read` informuje o ilości odczytanych bajtów lub błędzie.
read_result = read(file, &buffer, 10);
if (read_result == -1) { // Błąd odczytu z pliku
printf("Error reading from file\n");
exit(EXIT_FAILURE);
}
else if (read_result == 0) { // Plik jest pusty
printf("The file is empty! Something went wrong!\n");
exit(EXIT_FAILURE);
}
else {
buffer[read_result] = '\0';
// Porównanie wartości w buforze z oczekiwaną wartością (`num_incrementors * atoi(argv[3])`).
// Wyświetlenie odpowiedniego komunikatu w zależności od wyniku porównania.
if (atoi(buffer) == (atoi(argv[2]) * atoi(argv[3]))) {
printf("\nNumber in the file: %s, Incrementation SUCCESS! \n", buffer);
}
else {
printf("\nIncrementation FAILED! Number in the file: %s, expected: %d\n", buffer, (atoi(argv[2]) * atoi(argv[3])));
}
}
// Zamykanie pliku.
// Jeśli zamknięcie pliku nie powiedzie się, wyświetlany jest błąd.
if (close(file) == -1) {
perror("Error closing file");
exit(EXIT_FAILURE);
}
return 0;
}
|
import {Component} from 'react'
import Cookies from 'js-cookie'
import {Link} from 'react-router-dom'
import Loader from 'react-loader-spinner'
import {formatDistanceToNow} from 'date-fns'
import {IoClose} from 'react-icons/io5'
import {FaSearch} from 'react-icons/fa'
import Header from '../Header'
import Sidebar from '../Sidebar'
import NxtWatchContext from '../NxtWatchContext'
import {
HomeContainer,
HomeFlexContainer,
HomeMainContainer,
IsSidebarVisible,
HomeBannerContainer,
HomeBannerWebsiteLogo,
HomeBannerPara,
HomeBannerButton,
HomeBannerCloseButton,
HomeVideosContainer,
HomeSearchContainer,
HomeSearchInput,
HomeSearchIcon,
HomeVideoFlexContainer,
HomeVideoListContainer,
HomeVideoListItem,
HomeVideoThumbnail,
HomeVideoChannelContainer,
HomeVideoChannelLogo,
HomeVideoTitle,
HomeVideoInfo,
HomeNoVideosContainer,
HomeFailureImage,
HomeFailureHeading,
HomeFailurePara,
HomeRetryButton,
} from './styledComponent'
const apiStatusConstants = {
initial: 'INITIAL',
success: 'SUCCESS',
inProgress: 'IN_PROGRESS',
failure: 'FAILURE',
}
class Home extends Component {
state = {
searchInput: '',
apiStatus: apiStatusConstants.initial,
homeVideoData: [],
isBannerShow: true,
}
componentDidMount() {
this.getHomeVideos()
}
onChangeSearchInput = event => {
this.setState({searchInput: event.target.value})
}
getSearchResult = () => {
this.getHomeVideos()
}
onClickCloseButton = () => {
this.setState({isBannerShow: false})
}
onClickRetry = () => {
this.setState({searchInput: ''}, this.getHomeVideos)
}
getHomeVideos = async () => {
this.setState({apiStatus: apiStatusConstants.inProgress})
const {searchInput} = this.state
const jwtToken = Cookies.get('jwt_token')
const url = `https://apis.ccbp.in/videos/all?search=${searchInput}`
const options = {
method: 'GET',
headers: {
Authorization: `Bearer ${jwtToken}`,
},
}
const response = await fetch(url, options)
if (response.ok) {
const fetchedData = await response.json()
const fetchedVideoData = fetchedData.videos
const updatedData = fetchedVideoData.map(eachVideo => ({
id: eachVideo.id,
title: eachVideo.title,
thumbnailUrl: eachVideo.thumbnail_url,
channel: eachVideo.channel,
channelName: eachVideo.channel.name,
channelProfileImageUrl: eachVideo.channel.profile_image_url,
viewCount: eachVideo.view_count,
publishedAt: eachVideo.published_at,
}))
this.setState({
homeVideoData: updatedData,
apiStatus: apiStatusConstants.success,
})
} else {
this.setState({apiStatus: apiStatusConstants.failure})
}
}
renderHomeSuccess = isDarkMode => {
const {homeVideoData, isBannerShow} = this.state
return (
<HomeVideoListContainer>
{homeVideoData.length > 0 ? (
homeVideoData.map(eachVideo => (
<HomeVideoListItem key={eachVideo.id}>
<Link to={`/videos/${eachVideo.id}`} className="video-link">
<HomeVideoThumbnail
src={eachVideo.thumbnailUrl}
alt="video thumbnail"
/>
<HomeVideoChannelContainer>
<HomeVideoChannelLogo
src={eachVideo.channelProfileImageUrl}
alt="channel logo"
/>
<div>
<HomeVideoTitle isDarkMode={isDarkMode}>
{eachVideo.title}
</HomeVideoTitle>
<HomeVideoInfo isDarkMode={isDarkMode}>
{eachVideo.channelName}
</HomeVideoInfo>
<HomeFlexContainer>
<HomeVideoInfo isDarkMode={isDarkMode}>
{eachVideo.viewCount} views
</HomeVideoInfo>
<HomeVideoInfo isDarkMode={isDarkMode}>-</HomeVideoInfo>
<HomeVideoInfo isDarkMode={isDarkMode}>
{eachVideo.publishedAt}
ago
</HomeVideoInfo>
</HomeFlexContainer>
</div>
</HomeVideoChannelContainer>
</Link>
</HomeVideoListItem>
))
) : (
<HomeNoVideosContainer isBannerShow={isBannerShow}>
<HomeFailureImage
src="https://assets.ccbp.in/frontend/react-js/nxt-watch-no-search-results-img.png"
alt="no videos"
/>
<HomeFailureHeading isDarkMode={isDarkMode}>
No Search results found
</HomeFailureHeading>
<HomeFailurePara isDarkMode={isDarkMode}>
Try different key words or remove search filter
</HomeFailurePara>
<HomeRetryButton type="button" onClick={this.onClickRetry}>
Retry
</HomeRetryButton>
</HomeNoVideosContainer>
)}
</HomeVideoListContainer>
)
}
renderLoader = () => (
<div data-testid="loader">
<Loader type="ThreeDots" height={50} width={50} color="#3b82f6" />
</div>
)
renderHomeFailure = isDarkMode => (
<>
<HomeFailureImage
src={
isDarkMode
? 'https://assets.ccbp.in/frontend/react-js/nxt-watch-failure-view-dark-theme-img.png'
: 'https://assets.ccbp.in/frontend/react-js/nxt-watch-failure-view-light-theme-img.png'
}
alt="failure view"
/>
<HomeFailureHeading isDarkMode={isDarkMode}>
Oops! Something Went Wrong
</HomeFailureHeading>
<HomeFailurePara isDarkMode={isDarkMode}>
We are having some trouble to complete your request.
</HomeFailurePara>
<HomeFailurePara isDarkMode={isDarkMode}>
Please try again.
</HomeFailurePara>
<HomeRetryButton type="button" onClick={this.getHomeVideos}>
Retry
</HomeRetryButton>
</>
)
renderHomeSwitchCondition = isDarkMode => {
const {apiStatus} = this.state
switch (apiStatus) {
case apiStatusConstants.success:
return this.renderHomeSuccess(isDarkMode)
case apiStatusConstants.inProgress:
return this.renderLoader(isDarkMode)
case apiStatusConstants.failure:
return this.renderHomeFailure()
default:
return null
}
}
render() {
const {searchInput, isBannerShow} = this.state
return (
<NxtWatchContext.Consumer>
{value => {
const {isDarkMode} = value
return (
<>
<Header />
<HomeContainer>
<IsSidebarVisible>
<Sidebar />
</IsSidebarVisible>
<HomeMainContainer data-testid="home" isDarkMode={isDarkMode}>
<HomeBannerContainer
isBannerShow={isBannerShow}
data-testid="banner"
>
<div>
<HomeBannerWebsiteLogo
src="https://assets.ccbp.in/frontend/react-js/nxt-watch-logo-light-theme-img.png"
alt="nxt watch logo"
/>
<HomeBannerPara>
Buy Nxt Watch Premium prepaid plans with UPI
</HomeBannerPara>
<HomeBannerButton type="button">
GET IT NOW
</HomeBannerButton>
</div>
<div>
<HomeBannerCloseButton
onClick={this.onClickCloseButton}
data-testid="close"
>
<IoClose size={15} />
</HomeBannerCloseButton>
</div>
</HomeBannerContainer>
<HomeVideosContainer
data-testid="home"
isBannerShow={isBannerShow}
isDarkMode={isDarkMode}
>
<HomeSearchContainer>
<HomeSearchInput
type="search"
value={searchInput}
onChange={this.onChangeSearchInput}
placeholder="Search"
/>
<HomeSearchIcon
onClick={this.getSearchResult}
data-testid="searchButton"
>
<FaSearch size={15} />
</HomeSearchIcon>
</HomeSearchContainer>
<HomeVideoFlexContainer>
{this.renderHomeSwitchCondition(isDarkMode)}
</HomeVideoFlexContainer>
</HomeVideosContainer>
</HomeMainContainer>
</HomeContainer>
</>
)
}}
</NxtWatchContext.Consumer>
)
}
}
export default Home
|
import 'package:flutter/material.dart';
import 'package:flutter_platform_widget/DrawerScreen.dart';
import 'package:flutter_platform_widget/HomeScreen.dart';
import 'package:flutter_platform_widget/SettingsScreen.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Platform Widget',
debugShowCheckedModeBanner: false,
theme: ThemeData(
brightness: Brightness.dark,
),
home: const MyHomePage(
title: 'MaterialApp',
),
// home: const Contacts(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int selectedIndex = 0;
final List<Widget> _list = [
const HomeScreen(),
const SettingsScreen(),
];
void onItemTapped(int index) {
setState(() {
selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
drawer: const DrawerScreen(),
body: Center(
child: _list.elementAt(selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: "Home",
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: "Settings",
),
],
currentIndex: selectedIndex,
selectedItemColor: Colors.green,
unselectedItemColor: Colors.grey,
showUnselectedLabels: true,
onTap: onItemTapped,
),
);
}
}
|
import os
import pinecone
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.chat_models import ChatOpenAI
from langchain.vectorstores import Pinecone
from langchain.chains.llm import LLMChain
from chat_history_prompt import CONDENSE_QUESTION_PROMPT
from langchain.chains import ConversationalRetrievalChain
from langchain.chains.qa_with_sources import load_qa_with_sources_chain
from langchain.prompts import PromptTemplate
from customprompt import PROMPT
# import sys
# #sys.path.append('C:/Users/noteb/Documents/MVP/mvp/utils')
# sys.path.insert(1, '/mvp/utils')
# os.environ['PYTHONSAFEPATH'] = 'C:/Users/noteb/Documents/MVP/mvp/utils'
class LLMHelper:
def __init__(self,
embeddings: OpenAIEmbeddings = None,
llm: ChatOpenAI = None,
llm_type: str = None,
temperature: float = None,
custom_prompt: str = "",
vector_store: Pinecone = None,
vector_store_type: str = None):
# Set API keys
self.pinecone_api_key = os.environ["PINECONE_API_KEY"]
self.pinecone_api_env = os.environ["PINECONE_API_ENV"]
self.openai_api_key = os.environ["OPENAI_API_KEY"]
# OpenAI settings
self.embedding_model: str = os.getenv("OPENAI_EMBEDDINGS_ENGINE", "text-embedding-ada-002")
self.temperature: float = float(os.getenv("OPENAI_TEMPERATURE", 0.0)) if temperature is None else temperature
self.vector_store_type: str = os.getenv("VECTOR_STORE_TYPE", "Pinecone") if vector_store_type is None else vector_store_type
self.llm_type: str = os.getenv("LLM_TYPE","Chat" ) if llm_type is None else llm_type
self.prompt = PROMPT if custom_prompt == '' else PromptTemplate(template=custom_prompt, input_variables=["summaries", "question"])
self.embedding_model = "text-embedding-ada-002"
# setting embedding model
self.embeddings: OpenAIEmbeddings = OpenAIEmbeddings(model=self.embedding_model, openai_api_key=self.openai_api_key) if embeddings is None else embeddings
# setting the llm model
if self.llm_type == "Chat":
self.llm: ChatOpenAI = ChatOpenAI(temperature=self.temperature, openai_api_key=self.openai_api_key) if llm is None else llm
else:
raise Exception("Currently only the ChatGPT 3.5 turbo model is allowed.")
# vector store settings
self.vector_store = vector_store
def set_vector_store(self, index_name=None):
"""
This is a setter function that aims to set our vector store.
It initializes the Vector Store and them creates a vector store instance.
Atributes:
- index_name = reffers to the vector database's name
"""
# setting the vector database
if self.vector_store_type == "Pinecone":
pinecone.init(api_key=self.pinecone_api_key, environment=self.pinecone_api_env)
self.vector_store: Pinecone = Pinecone.from_existing_index(index_name, self.embeddings)
else:
raise Exception("Currently we only support Pinecone vector database.")
return self.vector_store
def get_semantic_search_conversational_chain(self, question, chat_history):
self.set_vector_store("source-test")
question_generator = LLMChain(llm=self.llm, prompt=CONDENSE_QUESTION_PROMPT, verbose=False)
# vector_store = self.set_vector_store("index name goes heree") # set index name to test
doc_chain = load_qa_with_sources_chain(self.llm, chain_type="stuff", verbose=True, prompt=self.prompt)
chain = ConversationalRetrievalChain(
retriever=self.vector_store.as_retriever(),
question_generator=question_generator,
combine_docs_chain=doc_chain,
return_source_documents=False
)
result = chain({"question": question, "chat_history": chat_history})
return question, result['answer']
|
import re
from pydriller import Repository
import typing
from urllib.parse import urlparse
from pydriller import Repository
def url_preprocess(url: str) -> typing.Dict[str, str]:
"""
输入url比如:https://github.com/anc95/ChatGPT-CodeReview/commit/26625e44efdc890b97f6c5452e442c366cac95d5
解析出仓库地址https://github.com/anc95/ChatGPT-CodeReview/
解析出哈希值26625e44efdc890b97f6c5452e442c366cac95d5
:param url: commit的url
:return:一个字典,包含解析内容
{
'url': 'https://github.com/anc95/ChatGPT-CodeReview/',
'hash': '26625e44efdc890b97f6c5452e442c366cac95d5'
}
"""
# 复制URL
parsed_url = urlparse(url)
# 分离URL与harsh
path_segments = parsed_url.path.strip('/').split('/')
repository_url = f"{parsed_url.scheme}://{parsed_url.netloc}/{'/'.join(path_segments[:-2])}"
commit_hash = path_segments[-1]
return {
'url': repository_url,
'hash': commit_hash
}
def get_commit_diff(repositories_address: str, commit_hash: str) -> typing.Dict[str, typing.List]:
"""
输入仓库地址以及哈希值,获取这个commit中全部的文件变更存储在字典中返回
:param repositories_address:仓库地址
:param commit_hash:commit哈希值
:return:一个字典,字典的key是变更的文件名,value是一个列表,包含了文件全部变更信息
"""
file_changes = dict()
for commit in Repository(repositories_address).traverse_commits():
if commit.hash != commit_hash:
continue
for file in commit.modified_files:
file_name = file.filename
file_diff = file.diff
file_changes[file_name] = list()
sections = re.split(r'@@.*?@@', file_diff)
for i, section in enumerate(sections):
if not i:
continue
file_changes[file_name].append(section)
return file_changes
commit = 'https://github.com/xuzel/ChatGPT_AUTO_CodeReview/commit/f7e958de987c38c0f49d16dc3bdce4160238083e'
a = url_preprocess(commit)
print(a)
b = get_commit_diff(a['url'], a['hash'])
for x, y in b.items():
print('\n\n')
print(x)
for z in y:
print(z)
|
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RolesCreateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|unique:roles|min:3|max:20',
];
}
public function messages()
{
return [
'name.required' => 'El nombre del rol es requerido',
'name.unique'=> 'El rol ya existe',
'name.min'=> 'El nombre del rol debe tener al menos 3 caracteres',
'name.max'=> 'El nombre del rol debe tener maximo 20 caracteres'
];
}
}
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
class GioHangRedux extends Component {
render() {
console.log(this.props);
return (
<div>
<h2>Giỏ Hàng</h2>
<table className='table'>
<thead>
<tr>
<th>Mã Sản Phẩm</th>
<th>Tên Sản Phẩm</th>
<th>Ảnh</th>
<th>Giá Tiền</th>
<th>Số Lượng</th>
<th>Tổng Giá Tiền</th>
<th></th>
</tr>
</thead>
<tbody>
{this.props.gioHang.map((sanPham, index) => {
return (
<tr key={index}>
<td>{sanPham.maSP}</td>
<td>{sanPham.tenSP}</td>
<td>
<img
src={sanPham.hinhAnh}
alt='...'
style={{
width: 50,
height: 50,
}}
/>
</td>
<td>{sanPham.giaBan.toLocaleString()}</td>
<td>
<button
className='btn btn-success mx-2'
onClick={() => {
this.props.tangGiamSoLuongSanPham(sanPham.maSP, 1);
}}>
+
</button>
{sanPham.soLuong}
<button
className='btn btn-success mx-2'
onClick={() => {
this.props.tangGiamSoLuongSanPham(sanPham.maSP, -1);
}}>
-
</button>
</td>
<td>{(sanPham.giaBan * sanPham.soLuong).toLocaleString()}</td>
<td>
<button
className='btn btn-danger'
onClick={() => {
this.props.xoaSanPham(sanPham.maSP);
}}>
Xoá
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
}
const mapStateToProps = (rootReducer) => {
return {
gioHang: rootReducer.gioHangReducer,
};
};
const mapDispatchToProps = (dispatch) => {
return {
xoaSanPham: (maSP) => {
console.log({ maSP });
// đẩy dữ liệu lên trên redux
// Cach 1:
// 1.
const action = {
type: 'XOA_SAN_PHAM', // Mô tả hành động
payload: maSP, // gửi dữ liệu lên redux
};
//2.
dispatch(action);
// Cach 2:
// dispatch({
// type: 'XOA_SAN_PHAM',
// payload: maSP,
// });
},
tangGiamSoLuongSanPham: (maSP, soLuong) => {
console.log({ maSP, soLuong }); // kiểu dữ liệu mà mình đang log ra ??? object
// object literal
// gửi dữ liệu lên trên Redux
dispatch({
type: 'TANG_GIAM_SO_LUONG_SAN_PHAM',
payload: {
maSP,
soLuong,
},
});
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(GioHangRedux);
// trả về 1 component 'GioHangRedux' mà có kết hợp với redux
|
slice message_packing(
int public_key,
;; slice signature,
int valid_until
;; int mode, ;; doesn't matter for test
;; cell msg_to_send ;; doesn't matter for test
) inline method_id {
;; request#_ valid_until:uint32 mode:uint8 msg_to_send:^Cell = Request;
;; msg_body#_ public_key:uint256 signature:(512 * Bit) request:^Request = MsgBody;
cell request = begin_cell()
.store_uint(valid_until, 32) ;; valid_until
.store_uint(128, 8) ;; mode
.store_ref(
begin_cell().store_uint(13, 32).end_cell() ;; msg_to_send
)
.end_cell();
cell signature_cell = begin_cell().store_uint(1, 256).store_uint(2, 256).end_cell();
cell message = begin_cell()
.store_uint(public_key, 256)
.store_slice(signature_cell.begin_parse())
.store_ref(request)
.end_cell();
return message.begin_parse();
}
;; Each test function must specify method_id
;; Test functions method_id need to started from 0
;; Each test functions must to be in pairs
;; First funtion expect nothing in arguments
;; But need to return:
;; function selector - which function to test, e.g. 0 for recv_internal, -1 recv_external, 85143 for seqno, and so on
;; tuple - stack values needed to be passed to function in tuple
;; c4 cell - start data of smart contract
;; c7 tuple / null
;; gas limit integer / null
[int, tuple, cell, tuple, int] test_init_data() method_id(0) {
;; Funtion to run (recv_external)
int function_selector = 90427; ;; pack_data
tuple stack = unsafe_tuple([
13, ;; public_key1
21 ;; public_key2
]);
cell data = begin_cell().end_cell();
return [function_selector, stack, data, get_c7(), null()];
}
;; After test data function
;; We need to define test funtion
;; It will accept:
;; exit code - exit code of runvm, here you can check errors / not
;; c4 cell - data of smart contract after runvm invokes
;; tuple - stack values of smart contract
;; c5 cell - here you can check all outcoming messages
;; gas - gas that was used
;; By default test is passed
;; You can use throw_if to fail test
_ test_init(int exit_code, cell data, tuple stack, cell actions, int gas) method_id(1) {
throw_if(100, exit_code != 0); ;; test need to be passed
var ds = data.begin_parse();
throw_unless(101, ds~load_uint(256) == 13);
throw_unless(101, ds~load_uint(256) == 21);
ds = first(stack).begin_parse();
throw_unless(101, ds~load_uint(256) == 13);
throw_unless(101, ds~load_uint(256) == 21);
throw_if(102, gas > 1000000); ;; check if gas usage is not so big
}
[int, tuple, cell, tuple, int] test_owner1valid_data() method_id(2) {
int function_selector = -1;
tuple stack = unsafe_tuple([message_packing(13, now() + 1000)]);
return [function_selector, stack, get_prev_c4(), get_c7(), null()];
}
_ test_owner1valid(int exit_code, cell data, tuple stack, cell actions, int gas) method_id(3) {
throw_if(100, exit_code != 1001);
}
[int, tuple, cell, tuple, int] test_owner1ignore_data() method_id(4) {
int function_selector = -1;
tuple stack = unsafe_tuple([message_packing(13, now() + 1000)]);
return [function_selector, stack, get_prev_c4(), get_c7(), null()];
}
_ test_owner1ignore(int exit_code, cell data, tuple stack, cell actions, int gas) method_id(5) {
throw_if(100, exit_code != 1002);
}
[int, tuple, cell, tuple, int] test_owner2valid_data() method_id(6) {
int function_selector = -1;
tuple stack = unsafe_tuple([message_packing(21, now() + 1000)]);
return [function_selector, stack, get_prev_c4(), get_c7(), null()];
}
_ test_owner2valid(int exit_code, cell data, tuple stack, cell actions, int gas) method_id(7) {
throw_if(100, exit_code != 1003);
}
[int, tuple, cell, tuple, int] test_not_owner_invalid_data() method_id(8) {
int function_selector = -1;
tuple stack = unsafe_tuple([message_packing(1, now() + 1000)]);
return [function_selector, stack, get_prev_c4(), get_c7(), null()];
}
_ test_not_owner_invalid(int exit_code, cell data, tuple stack, cell actions, int gas) method_id(9) {
throw_if(100, exit_code != 101);
}
|
!> @file
!> @brief Define the variables in the derived data type discipline.
!> @author Jun Wang @date 2012/01/25
!> @brief Define the variables in the derived data type discipline
!> provided in Section 0.
!>
!> ### Program History Log
!> Date | Programmer | Comments
!> -----|------------|---------
!> 12/04/2009 | V. Krishna Kumar | Creation
!> 2012/01/25 | Jun Wang | Add template 4.44 and 4.48
!> 2012/02/20 | Jun Wang | Add complex packing
!> 2014/07/08 | Boi Vuong | Corrected Scaled value of second fixed surfaces in template 4.8 and Added generating process model HRRR
!> 2015/01/09 | Boi Vuong | Added template 4.1, 411 and 4.12 and update code tables routines: get_g2_typeof ensfcst, get_g2_typeofderivefcst
!> 2015/09/02 | Boi Vuong | Added 4 type of aerosols in table4_233
!> 2017/03/01 | Boi Vuong | Added generating process model (HREF and Great lake short range model in table on388_tablea
!> 2019/06/25 | Boi Vuong | Corrected tablec sub-center: Changed name: ncep_hpc to ncep_wpc; ncep_tpc to ncep_nhc; sec - swpc and aded new sub-center: esrl
!> 2019/06/25 | Boi Vuong | 17 Added new entries in table4_3,table4_5 and added new table4_8,table4_9,table 4_201 Added generating process model table on388_tablea
!> 2021/04/20 | Boi Vuong | Updated table 4.3, 4.5,4.7 and on388_tablea
!> 2023/03/30 | Andrew Benjamin | Added new entires to on388)_tablea
!>
!> @author Jun Wang @date 2012/01/25
module grib2_all_tables_module
implicit none
!> maxsubcen
integer, parameter :: MAXSUBCEN=100
!> maxver
integer, parameter :: MAXVER=100
!> maxlocver
integer, parameter :: MAXLOCVER=20
!> maxreftime
integer, parameter :: MAXREFTIME=15
!> maxprodstatus
integer, parameter :: MAXPRODSTATUS=17
!> maxtypeofdata
integer, parameter :: MAXTYPEOFDATA=100
!> maxtypeofgenproc
integer, parameter :: MAXTYPEOFGENPROC=100
!> maxtypeofensfcst
integer, parameter :: MAXTYPEOFENSFCST=100
!> maxtypeofderivefcst
integer, parameter :: MAXTYPEOFDERIVEFCST=100
!> Max fixed surface types
integer, parameter :: MAXFIXEDSURFACETYPES=200
!> maxunitoftimerange
integer, parameter :: MAXUNITOFTIMERANGE=30
!> maxgenproc
integer, parameter :: MAXGENPROC=250
!> maxorigincenters
integer, parameter :: MAXORIGINCENTERS=500
!> maxtypeoforigfieldval
integer, parameter :: MAXTYPEOFORIGFIELDVAL=15
!> maxtypeofcompression
integer, parameter :: MAXTYPEOFCOMPRESSION=50
!> maxtypeofpackingmethod
integer, parameter :: MAXTYPEOFPACKINGMETHOD=50
!> maxstatprocesstypes
integer, parameter :: MAXSTATPROCESSTYPES=50
!> maxtypeoftimeintvls
integer, parameter :: MAXTYPEOFTIMEINTVLS=50
!> maxtypeofprob
integer, parameter :: MAXTYPEOFPROB=100
!> maxtypeofprecip
integer, parameter :: MAXTYPEOFPRECIP=100
!> maxtypeofcluster
integer, parameter :: MAXTYPEOFCLUSTER=100
!> maxtypeofaerosol
integer, parameter :: MAXTYPEOFAEROSOL=200
!> maxtypeofintvls
integer, parameter :: MAXTYPEOFINTVLS=50
!> maxordofsptdiff
integer, parameter :: MAXORDOFSPTDIFF=50
type subcenters
character(len=20) :: subcenkey
integer :: subcenval
end type subcenters
!> tablec
type(subcenters), dimension(MAXSUBCEN) :: tablec
data tablec(1) /subcenters('ncep_reanl',1)/
data tablec(2) /subcenters('ncep_ensem',2)/
data tablec(3) /subcenters('ncep_nco',3)/
data tablec(4) /subcenters('ncep_emc',4)/
data tablec(5) /subcenters('ncep_wpc',5)/
data tablec(6) /subcenters('ncep_opc',6)/
data tablec(7) /subcenters('ncep_cpc',7)/
data tablec(8) /subcenters('ncep_awc',8)/
data tablec(9) /subcenters('ncep_spc',9)/
data tablec(10) /subcenters('ncep_nhc',10)/
data tablec(11) /subcenters('nws_tdl',11)/
data tablec(12) /subcenters('nesdis_ora',12)/
data tablec(13) /subcenters('faa',13)/
data tablec(14) /subcenters('nws_mdl',14)/
data tablec(15) /subcenters('narr',15)/
data tablec(16) /subcenters('swpc',16)/
!
! Added Sub-Center (06/26/2019)
!
data tablec(17) /subcenters('esrl',17)/
type version_no
character(len=20) :: verskey
integer :: versval
end type version_no
!> Table 1 0
type(version_no),dimension(MAXVER) :: table1_0
data table1_0(1) /version_no('expt',0)/
data table1_0(2) /version_no('v2001',1)/
data table1_0(3) /version_no('v2003',2)/
data table1_0(4) /version_no('v2005',3)/
data table1_0(5) /version_no('v2007',4)/
data table1_0(6) /version_no('v2009',5)/
data table1_0(7) /version_no('v2010',6)/
data table1_0(8) /version_no('v052011',7)/
data table1_0(9) /version_no('v112011',8)/
data table1_0(10) /version_no('v052012',9)/
data table1_0(11) /version_no('v112012',10)/
data table1_0(12) /version_no('v052013',11)/
data table1_0(13) /version_no('v112013',12)/
data table1_0(14) /version_no('v052014',13)/
data table1_0(15) /version_no('v112014',14)/
data table1_0(16) /version_no('v052015',15)/
data table1_0(17) /version_no('v112015',16)/
data table1_0(18) /version_no('v052016',17)/
data table1_0(19) /version_no('v112016',18)/
data table1_0(20) /version_no('v052017',19)/
data table1_0(21) /version_no('v112017',20)/
data table1_0(22) /version_no('v052018',21)/
data table1_0(23) /version_no('v112018',22)/
data table1_0(24) /version_no('v052019',23)/
data table1_0(25) /version_no('v112019',24)/
data table1_0(26) /version_no('v052020',25)/
data table1_0(27) /version_no('v112020',26)/
data table1_0(28) /version_no('v052021',27)/
data table1_0(29) /version_no('v112021',28)/
data table1_0(30) /version_no('preoper',29)/
!
!
type local_table_vers_no
character(len=20) :: locverskey
integer :: locversval
end type local_table_vers_no
!> Table 1 1
type(local_table_vers_no),dimension(MAXLOCVER) :: table1_1
!
data table1_1(1) /local_table_vers_no('local_tab_no',0)/
data table1_1(2) /local_table_vers_no('local_tab_yes1',1)/
data table1_1(3) /local_table_vers_no('local_tab_yes2',2)/
data table1_1(4) /local_table_vers_no('local_tab_yes3',3)/
data table1_1(5) /local_table_vers_no('local_tab_yes4',4)/
data table1_1(6) /local_table_vers_no('local_tab_yes5',5)/
data table1_1(7) /local_table_vers_no('missing',255)/
!
!
type sigreftime
character(len=20) :: sigrefkey
integer :: sigrefval
end type sigreftime
! Declare a variable of type discipline
!> Table 1 2
type(sigreftime),dimension(MAXREFTIME) :: table1_2
data table1_2(1) /sigreftime('anal',0)/
data table1_2(2) /sigreftime('fcst',1)/
data table1_2(3) /sigreftime('vfcst',2)/
data table1_2(4) /sigreftime('obstime',3)/
data table1_2(5) /sigreftime('missing',255)/
!
!
type prod_status
character(len=20) :: prodstatuskey
integer :: prodstatusval
end type prod_status
! Declare a variable of type discipline
!> Table 1 3
type(prod_status),dimension(MAXPRODSTATUS) :: table1_3
data table1_3(1) /prod_status('oper',0)/
data table1_3(2) /prod_status('oper_test',1)/
data table1_3(3) /prod_status('res',2)/
data table1_3(4) /prod_status('reanal',3)/
data table1_3(5) /prod_status('tigge',4)/
data table1_3(6) /prod_status('tigge_test',5)/
data table1_3(7) /prod_status('missing',255)/
data table1_3(8) /prod_status('s2s_oper',6)/
data table1_3(9) /prod_status('s2s_test',7)/
data table1_3(10) /prod_status('unens_rreanl',8)/
data table1_3(11) /prod_status('unens_rreanl_test',9)/
!
!
type type_of_data
character(len=20) :: typeofdatakey
integer :: typeofdataval
end type type_of_data
!
!> table1_4
type(type_of_data),dimension(MAXTYPEOFDATA) :: table1_4
data table1_4(1) /type_of_data('anal',0)/
data table1_4(2) /type_of_data('fcst',1)/
data table1_4(3) /type_of_data('anal_fcst',2)/
data table1_4(4) /type_of_data('con_fcst',3)/
data table1_4(5) /type_of_data('per_fcst',4)/
data table1_4(6) /type_of_data('con_per_fcst',5)/
data table1_4(7) /type_of_data('proc_sat_obs',6)/
data table1_4(8) /type_of_data('proc_rad_obs',7)/
data table1_4(9) /type_of_data('event_prob',8)/
data table1_4(10) /type_of_data('missing',255)/
data table1_4(11) /type_of_data('experimental_products',192)/
!
!
type type_of_gen_proc
character(len=30) :: typeofgenprockey
integer :: typeofgenprocval
end type type_of_gen_proc
! 2015/09/02 Boi Vuong Added 4 type of aerosols in table4_233
! 2019/06/25 Boi Vuong Added new entries 197,198,199 in table4_3
!
!> table4_3
type(type_of_gen_proc),dimension(MAXTYPEOFGENPROC) :: table4_3
data table4_3(1) /type_of_gen_proc('anal',0)/
data table4_3(2) /type_of_gen_proc('init',1)/
data table4_3(3) /type_of_gen_proc('fcst',2)/
data table4_3(4) /type_of_gen_proc('bias_corr_fcst',3)/
data table4_3(5) /type_of_gen_proc('ens_fcst',4)/
data table4_3(6) /type_of_gen_proc('prob_fcst',5)/
data table4_3(7) /type_of_gen_proc('fcst_err',6)/
data table4_3(8) /type_of_gen_proc('anal_err',7)/
data table4_3(9) /type_of_gen_proc('obs',8)/
data table4_3(10) /type_of_gen_proc('clim',9)/
data table4_3(11) /type_of_gen_proc('prob_wt_fcst',10)/
data table4_3(12) /type_of_gen_proc('fcst_con_ind',192)/
data table4_3(13) /type_of_gen_proc('bias_corr_ens_fcst',11)/
data table4_3(14) /type_of_gen_proc('missing',255)/
data table4_3(15) /type_of_gen_proc('post_proc_anal',12)/
data table4_3(16) /type_of_gen_proc('post_proc_fcst',13)/
data table4_3(17) /type_of_gen_proc('nowcast',14)/
data table4_3(18) /type_of_gen_proc('hincsast',15)/
data table4_3(19) /type_of_gen_proc('physical_retrieval',16)/
data table4_3(20) /type_of_gen_proc('regression_analysis',17)/
data table4_3(21) /type_of_gen_proc('difference_two_forecasts',18)/
data table4_3(22) /type_of_gen_proc('prob_matched_mean',193)/
data table4_3(23) /type_of_gen_proc('neighborhood_prob',194)/
data table4_3(24) /type_of_gen_proc('bias_corrected_downscale',195)/
data table4_3(25) /type_of_gen_proc('perturbed_analysis',196)/
!
! Added Generating Process (06/26/2019)
!
data table4_3(26) /type_of_gen_proc('ens_scale_prob',197)/
data table4_3(27) /type_of_gen_proc('post_dew_fcst',198)/
data table4_3(28) /type_of_gen_proc('ens_fcst_base',199)/
!
! Added Generating Process (04/20/2021)
!
data table4_3(29) /type_of_gen_proc('local_prob_match_mean',200)/
!
!
type unit_of_time_range
character(len=30) :: unitoftimerangekey
integer :: unitoftimerangeval
end type unit_of_time_range
!
!> table4_4
type(unit_of_time_range),dimension(MAXUNITOFTIMERANGE) :: table4_4
data table4_4(1) /unit_of_time_range('minute',0)/
data table4_4(2) /unit_of_time_range('hour',1)/
data table4_4(3) /unit_of_time_range('day',2)/
data table4_4(4) /unit_of_time_range('month',3)/
data table4_4(5) /unit_of_time_range('year',4)/
data table4_4(6) /unit_of_time_range('decade',5)/
data table4_4(7) /unit_of_time_range('normal_30y',6)/
data table4_4(8) /unit_of_time_range('century',7)/
data table4_4(9) /unit_of_time_range('3hours',10)/
data table4_4(10) /unit_of_time_range('6hours',11)/
data table4_4(11) /unit_of_time_range('12hours',12)/
data table4_4(12) /unit_of_time_range('second',13)/
data table4_4(13) /unit_of_time_range('missing',255)/
!
!
type fixed_surface_types
character(len=80) :: fixedsurfacetypeskey
integer :: fixedsurfacetypesval
end type fixed_surface_types
!
!> table4_5
type(fixed_surface_types),dimension(MAXFIXEDSURFACETYPES) :: table4_5
data table4_5(1) /fixed_surface_types('surface',1)/
data table4_5(2) /fixed_surface_types('cloud_base',2)/
data table4_5(3) /fixed_surface_types('cloud_top',3)/
data table4_5(4) /fixed_surface_types('0C_isotherm',4)/
data table4_5(5) /fixed_surface_types('lvl_of_adiab_cond_from_sfc',5)/
data table4_5(6) /fixed_surface_types('max_wind',6)/
data table4_5(7) /fixed_surface_types('tropopause',7)/
data table4_5(8) /fixed_surface_types('top_of_atmos',8)/
data table4_5(9) /fixed_surface_types('sea_bottom',9)/
data table4_5(10) /fixed_surface_types('entire_atmos',10)/
data table4_5(11) /fixed_surface_types('cb_base',11)/
data table4_5(12) /fixed_surface_types('cb_top',12)/
data table4_5(13) /fixed_surface_types('isothermal',20)/
data table4_5(14) /fixed_surface_types('isobaric_sfc',100)/
data table4_5(15) /fixed_surface_types('mean_sea_lvl',101)/
data table4_5(16) /fixed_surface_types('spec_alt_above_mean_sea_lvl',102)/
data table4_5(17) /fixed_surface_types('spec_hgt_lvl_above_grnd',103)/
data table4_5(18) /fixed_surface_types('sigma_lvl',104)/
data table4_5(19) /fixed_surface_types('hybrid_lvl',105)/
data table4_5(20) /fixed_surface_types('depth_bel_land_sfc',106)/
data table4_5(21) /fixed_surface_types('isentropic_lvl',107)/
data table4_5(22) /fixed_surface_types('spec_pres_above_grnd',108)/
data table4_5(23) /fixed_surface_types('pot_vort_sfc',109)/
data table4_5(24) /fixed_surface_types('eta_lvl',111)/
data table4_5(25) /fixed_surface_types('mixed_lyr_depth',117)/
data table4_5(26) /fixed_surface_types('depth_below_sea_lvl',160)/
data table4_5(27) /fixed_surface_types('entire_atmos_single_lyr',200)/
data table4_5(28) /fixed_surface_types('entire_ocean_single_lyr',201)/
data table4_5(29) /fixed_surface_types('hghst_trop_frz_lvl',204)/
data table4_5(30) /fixed_surface_types('grid_scale_cloud_bot_lvl',206)/
data table4_5(31) /fixed_surface_types('grid_scale_cloud_top_lvl',207)/
data table4_5(32) /fixed_surface_types('bound_lyr_cloud_bot_lvl',209)/
data table4_5(33) /fixed_surface_types('bound_lyr_cloud_top_lvl',210)/
data table4_5(34) /fixed_surface_types('bound_lyr_cloud_lyr',211)/
data table4_5(35) /fixed_surface_types('low_cloud_bot_lvl',212)/
data table4_5(36) /fixed_surface_types('low_cloud_top_lvl',213)/
data table4_5(37) /fixed_surface_types('low_cloud_lyr',214)/
data table4_5(38) /fixed_surface_types('cloud_ceilng',215)/
data table4_5(39) /fixed_surface_types('planetary_bound_lyr',220)/
data table4_5(40) /fixed_surface_types('lyr_betwn_2hybrid_lvls',221)/
data table4_5(41) /fixed_surface_types('mid_cloud_bot_lvl',222)/
data table4_5(42) /fixed_surface_types('mid_cloud_top_lvl',223)/
data table4_5(43) /fixed_surface_types('mid_cloud_lyr',224)/
data table4_5(44) /fixed_surface_types('high_cloud_bot_lvl',232)/
data table4_5(45) /fixed_surface_types('high_cloud_top_lvl',233)/
data table4_5(46) /fixed_surface_types('high_cloud_lyr',234)/
data table4_5(47) /fixed_surface_types('ocean_isotherm_lvl',235)/
data table4_5(48) /fixed_surface_types('lyr_betwn_2depths_below_ocean_sfc',236)/
data table4_5(49) /fixed_surface_types('bot_of_ocean_mix_lyr',237)/
data table4_5(50) /fixed_surface_types('bot_of_ocean_isoth_lyr',238)/
data table4_5(51) /fixed_surface_types('lyr_ocean_sfc_26c_ocean_isotherm_lvl',239)/
data table4_5(52) /fixed_surface_types('ocean_mix_lyr',240)/
data table4_5(53) /fixed_surface_types('ordered_seq_of_data',241)/
data table4_5(54) /fixed_surface_types('convective_cloud_bot_lvl',242)/
data table4_5(55) /fixed_surface_types('convective_cloud_top_lvl',243)/
data table4_5(56) /fixed_surface_types('convective_cloud_lyr',244)/
data table4_5(57) /fixed_surface_types('lwst_lvl_of_wet_bulb_zero',245)/
data table4_5(58) /fixed_surface_types('max_equiv_pot_temp_lvl',246)/
data table4_5(59) /fixed_surface_types('equil_lvl',247)/
data table4_5(60) /fixed_surface_types('shall_convective_cloud_bot_lvl',248)/
data table4_5(61) /fixed_surface_types('shall_convective_cloud_top_lvl',249)/
data table4_5(62) /fixed_surface_types('deep_convective_cloud_bot_lvl',251)/
data table4_5(63) /fixed_surface_types('deep_convective_cloud_top_lvl',252)/
data table4_5(64) /fixed_surface_types('lwst_bot_lvl_of_supercooled_liq_water_lyr',253)/
data table4_5(65) /fixed_surface_types('hghst_top_lvl_of_supercooled_liq_water_lyr',254)/
data table4_5(66) /fixed_surface_types('missing',255)/
data table4_5(67) /fixed_surface_types('hybrid_height_lvl',118)/
data table4_5(68) /fixed_surface_types('hybrid_pres_lvl',119)/
data table4_5(69) /fixed_surface_types('gen_vertical_height_coor',150)/
data table4_5(70) /fixed_surface_types('depth_below_water_lvl',161)/
data table4_5(71) /fixed_surface_types('lake_or_river_bottom',162)/
data table4_5(72) /fixed_surface_types('bottom_of_sediment_layer',163)/
data table4_5(73) /fixed_surface_types('bottom_of_therm_sediment_layer',164)/
data table4_5(74) /fixed_surface_types('bottom_of_sediment_layer_thermal_wave',165)/
data table4_5(75) /fixed_surface_types('maxing_layer',166)/
data table4_5(76) /fixed_surface_types('bottom_root_zone',167)/
data table4_5(77) /fixed_surface_types('topsfc_ice_onsealakeriver',174)/
data table4_5(78) /fixed_surface_types('topsfc_ice_unsnow_onsealakeriver',175)/
data table4_5(79) /fixed_surface_types('bottomsfc_ice_onsealakeriver',176)/
data table4_5(80) /fixed_surface_types('deep_soil',177)/
data table4_5(81) /fixed_surface_types('topsfc_glacierice_inlandice',179)/
data table4_5(82) /fixed_surface_types('deepinland_glacierice',180)/
data table4_5(83) /fixed_surface_types('gridtile_landfrac',181)/
data table4_5(84) /fixed_surface_types('gridtile_waterfrac',182)/
data table4_5(85) /fixed_surface_types('gridtile_icefrac_onsealakeriver',183)/
data table4_5(86) /fixed_surface_types('gridtile_glacierice_inland_icefrac',184)/
data table4_5(87) /fixed_surface_types('lowest_level_vertical_icc',13)/
data table4_5(88) /fixed_surface_types('level_free_convection',14)/
data table4_5(89) /fixed_surface_types('covection_conden_level',15)/
data table4_5(90) /fixed_surface_types('level_neutral_buoy',16)/
data table4_5(91) /fixed_surface_types('soil_level',151)/
!
! Added fixed surface levels (06/26/2019)
!
data table4_5(92) /fixed_surface_types('lowest_mass_den',21)/
data table4_5(93) /fixed_surface_types('highest_mass_den',22)/
data table4_5(94) /fixed_surface_types('lowest_air_con',23)/
data table4_5(95) /fixed_surface_types('highest_air_con',24)/
data table4_5(96) /fixed_surface_types('highest_rref',25)/
data table4_5(97) /fixed_surface_types('log_hyb_lev',113)/
data table4_5(98) /fixed_surface_types('snow_lev',114)/
data table4_5(100) /fixed_surface_types('sigma_hi_lev',115)/
!
! Added fixed surface levels (04/20/2021)
!
data table4_5(101) /fixed_surface_types('ocean_model_level',168)/
data table4_5(102) /fixed_surface_types('ocean_level_water_density',169)/
data table4_5(103) /fixed_surface_types('ocean_level_water_potential_temp',170)/
data table4_5(104) /fixed_surface_types('eff_layer_top_level',216)/
data table4_5(105) /fixed_surface_types('eff_layer_bottom_level',217)/
data table4_5(106) /fixed_surface_types('eff_layer',218)/
!
!
type type_of_ens_fcst
character(len=50) :: typeofensfcstkey
integer :: typeofensfcstval
end type type_of_ens_fcst
!
!> table4_6
type(type_of_ens_fcst),dimension(MAXTYPEOFENSFCST) :: table4_6
data table4_6(1) /type_of_ens_fcst('unpert_hi_res_ctrl_fcst',0)/
data table4_6(2) /type_of_ens_fcst('unpert_lo_res_ctrl_fcst',1)/
data table4_6(3) /type_of_ens_fcst('neg_pert_fcst',2)/
data table4_6(4) /type_of_ens_fcst('pos_pert_fcst',3)/
data table4_6(5) /type_of_ens_fcst('multi_model_fcst',4)/
data table4_6(6) /type_of_ens_fcst('pert_ens_member',192)/
!
!
type type_of_derive_fcst
character(len=50) :: typeofderivefcstkey
integer :: typeofderivefcstval
end type type_of_derive_fcst
!
!> table4_7
type(type_of_derive_fcst),dimension(MAXTYPEOFDERIVEFCST) :: table4_7
data table4_7(1) /type_of_derive_fcst('unweighted_mean_all_mem',0)/
data table4_7(2) /type_of_derive_fcst('weighted_mean_all_mem',1)/
data table4_7(3) /type_of_derive_fcst('std_devn_res_cluster_mean',2)/
data table4_7(4) /type_of_derive_fcst('std_devn_res_cluster_mean_norm',3)/
data table4_7(5) /type_of_derive_fcst('spread_all_mem',4)/
data table4_7(6) /type_of_derive_fcst('large_anomaly_index',5)/
data table4_7(7) /type_of_derive_fcst('unweighted_mean_cluster',6)/
data table4_7(8) /type_of_derive_fcst('interquartile_range',7)/
data table4_7(9) /type_of_derive_fcst('min_all_ens_mem',8)/
data table4_7(10) /type_of_derive_fcst('max_all_ens_mem',9)/
data table4_7(11) /type_of_derive_fcst('unweighted_mode_all_mem',192)/
data table4_7(12) /type_of_derive_fcst('percentile_val_10',193)/
data table4_7(13) /type_of_derive_fcst('percentile_val_50',194)/
data table4_7(14) /type_of_derive_fcst('percentile_val_90',195)/
data table4_7(15) /type_of_derive_fcst('stat_decide_mem',196)/
data table4_7(16) /type_of_derive_fcst('clim_percentile',197)/
data table4_7(17) /type_of_derive_fcst('deviation_ens_mean',198)/
data table4_7(18) /type_of_derive_fcst('extream_forecast_index',199)/
!
! Added type of derive forecast (04/20/2021)
!
data table4_7(19) /type_of_derive_fcst('equally_weighted_mean',200)/
data table4_7(20) /type_of_derive_fcst('percentile_value_5',201)/
data table4_7(21) /type_of_derive_fcst('percentile_value_25',202)/
data table4_7(22) /type_of_derive_fcst('percentile_value_75',203)/
data table4_7(23) /type_of_derive_fcst('percentile_value_95',204)/
!
!
! Added Clustering Method Table 4.8 (06/26/2019)
!
type type_of_cluster
character(len=80) :: typeofclusterkey
integer :: typeofclusterval
end type type_of_cluster
!
!> table4_8
type(type_of_cluster),dimension(MAXTYPEOFCLUSTER) :: table4_8
data table4_8(1) /type_of_cluster('anomoly_correlation',0)/
data table4_8(2) /type_of_cluster('root_mean_square',1)/
!
!
! Added Probability Type Table 4.9 (06/26/2019)
!
type type_of_prob
character(len=80) :: typeofprobkey
integer :: typeofprobval
end type type_of_prob
!
!> table4_9
type(type_of_prob),dimension(MAXTYPEOFPROB) :: table4_9
data table4_9(1) /type_of_prob('prob_below_lower_limit',0)/
data table4_9(2) /type_of_prob('prob_above_upper_limit',1)/
data table4_9(3) /type_of_prob('prob_between_upper_lower_limit',2)/
data table4_9(4) /type_of_prob('prob_above_lower_limit',3)/
data table4_9(5) /type_of_prob('prob_below_upper_limit',4)/
data table4_9(6) /type_of_prob('prob_equal_lower_limit',5)/
data table4_9(7) /type_of_prob('prob_above_normal_cat',6)/
data table4_9(8) /type_of_prob('prob_near_normal_cat',7)/
data table4_9(9) /type_of_prob('prob_below_normal_cat',8)/
!
!
type statistical_processing_types
character(len=80) :: statprocesstypeskey
integer :: statprocesstypesval
end type statistical_processing_types
!
!> table4_10
type(statistical_processing_types),dimension(MAXSTATPROCESSTYPES) :: table4_10
data table4_10(1) /statistical_processing_types('AVE',0)/
data table4_10(2) /statistical_processing_types('ACM',1)/
data table4_10(3) /statistical_processing_types('MAX',2)/
data table4_10(4) /statistical_processing_types('MIN',3)/
data table4_10(5) /statistical_processing_types('diff_end-beg',4)/
data table4_10(6) /statistical_processing_types('rms',5)/
data table4_10(7) /statistical_processing_types('std_devn',6)/
data table4_10(8) /statistical_processing_types('covariance',7)/
data table4_10(9) /statistical_processing_types('diff_beg-end',8)/
data table4_10(10) /statistical_processing_types('ratio',9)/
data table4_10(11) /statistical_processing_types('std_anomaly',10)/
data table4_10(12) /statistical_processing_types('clim_mean',192)/
data table4_10(13) /statistical_processing_types('ave_n_fcsts',193)/
data table4_10(14) /statistical_processing_types('ave_n_unin_anal',194)/
data table4_10(15) /statistical_processing_types('ave_fcst_acc_24',195)/
data table4_10(16) /statistical_processing_types('ave_succ_fcst_acc',196)/
data table4_10(17) /statistical_processing_types('ave_fcst_ave_24',197)/
data table4_10(18) /statistical_processing_types('ave_succ_fcst_ave',198)/
data table4_10(19) /statistical_processing_types('clim_ave_n_anal',199)/
data table4_10(20) /statistical_processing_types('clim_ave_n_fcst',200)/
data table4_10(21) /statistical_processing_types('clim_rms_diff',201)/
data table4_10(22) /statistical_processing_types('clim_std_n_fcst',202)/
data table4_10(23) /statistical_processing_types('clim_std_n_anal',203)/
data table4_10(24) /statistical_processing_types('ave_fcst_acc_6',204)/
data table4_10(25) /statistical_processing_types('ave_fcst_ave_6',205)/
data table4_10(26) /statistical_processing_types('ave_fcst_acc_12',206)/
data table4_10(27) /statistical_processing_types('ave_fcst_ave_12',207)/
data table4_10(28) /statistical_processing_types('missing',255)/
data table4_10(29) /statistical_processing_types('summation',11)/
data table4_10(30) /statistical_processing_types('confidence_index',12)/
data table4_10(31) /statistical_processing_types('quality_indicator',13)/
data table4_10(32) /statistical_processing_types('variance',208)/
data table4_10(33) /statistical_processing_types('confficient',209)/
!
!
type type_of_time_intervals
character(len=80) :: typeoftimeintervalskey
integer :: typeoftimeintervalsval
end type type_of_time_intervals
!
!> table4_11
type(type_of_time_intervals),dimension(MAXTYPEOFTIMEINTVLS) :: table4_11
data table4_11(1) /type_of_time_intervals('reserved',0)/
data table4_11(2) /type_of_time_intervals('same_fcst_time_start_time_fcst_inc',1)/
data table4_11(3) /type_of_time_intervals('same_start_time_fcst_fcst_time_inc',2)/
data table4_11(4) /type_of_time_intervals('start_time_fcst_inc_fcst_time_dec',3)/
data table4_11(5) /type_of_time_intervals('start_time_fcst_dec_fcst_time_inc',4)/
data table4_11(6) /type_of_time_intervals('fltng_time_betwn_fcst_time_end_time_intvl',5)/
data table4_11(7) /type_of_time_intervals('local1',192)/
data table4_11(8) /type_of_time_intervals('local2',193)/
data table4_11(9) /type_of_time_intervals('local3',194)/
data table4_11(10) /type_of_time_intervals('missing',255)/
!
!
type type_of_intervals
character(len=80) :: typeofintervalskey
integer :: typeofintervalsval
end type type_of_intervals
!
!> table4_91
type(type_of_intervals),dimension(MAXTYPEOFINTVLS) :: table4_91
data table4_91(1) /type_of_intervals('smaller_than_first_limit',0)/
data table4_91(2) /type_of_intervals('greater_than_second_limit',1)/
data table4_91(3) /type_of_intervals('between_first_second_limit_noincl2ndlmt',2)/
data table4_91(4) /type_of_intervals('greater_than_first_limit',3)/
data table4_91(5) /type_of_intervals('smaller_than_second_limit',4)/
data table4_91(6) /type_of_intervals('smaller_or_equal_first_limit',5)/
data table4_91(7) /type_of_intervals('greater_or_equal_second_limit',6)/
data table4_91(8) /type_of_intervals('between_first_second_limit',7)/
data table4_91(9) /type_of_intervals('greater_or_equal_first_limit',8)/
data table4_91(10) /type_of_intervals('smaller_or_equal_second_limit',9)/
data table4_91(11) /type_of_intervals('between_first_second_limit_noincl1stlmt',10)/
data table4_91(12) /type_of_intervals('equall_to_first_limit',11)/
data table4_91(13) /type_of_intervals('missing',255)/
!
! Added Precipitation Table 4.201 (06/26/2019)
!
type type_of_precip
character(len=80) :: typeofprecipkey
integer :: typeofprecipval
end type type_of_precip
!
!> table4_201
type(type_of_precip),dimension(MAXTYPEOFPRECIP) :: table4_201
data table4_201(1) /type_of_precip('reserved',0)/
data table4_201(2) /type_of_precip('rain',1)/
data table4_201(3) /type_of_precip('thunderstorm',2)/
data table4_201(4) /type_of_precip('freezing_rain',3)/
data table4_201(5) /type_of_precip('mixed_ice',4)/
data table4_201(6) /type_of_precip('snow',5)/
data table4_201(7) /type_of_precip('wet_snow',6)/
data table4_201(8) /type_of_precip('mixture_rain_snow',7)/
data table4_201(91) /type_of_precip('ice_pellets',8)/
data table4_201(10) /type_of_precip('graupel',9)/
data table4_201(11) /type_of_precip('hail',10)/
data table4_201(12) /type_of_precip('drizzle',11)/
data table4_201(13) /type_of_precip('freezing_drizzle',12)/
!
!
type type_of_aerosol
character(len=80) :: typeofaerosolkey
integer :: typeofaerosolval
end type type_of_aerosol
!
!> table4_233
type(type_of_aerosol),dimension(MAXTYPEOFAEROSOL) :: table4_233
data table4_233(1) /type_of_aerosol('ozone',0)/
data table4_233(2) /type_of_aerosol('water_vapor',1)/
data table4_233(3) /type_of_aerosol('methane',2)/
data table4_233(4) /type_of_aerosol('carbon_dioxide',3)/
data table4_233(5) /type_of_aerosol('carbon_monoxide',4)/
data table4_233(6) /type_of_aerosol('nitrogen_dioxide',5)/
data table4_233(7) /type_of_aerosol('nitrous_oxide',6)/
data table4_233(8) /type_of_aerosol('formaldehyde',7)/
data table4_233(9) /type_of_aerosol('sulphur_dioxide',8)/
data table4_233(10) /type_of_aerosol('ammonia',9)/
data table4_233(11) /type_of_aerosol('ammonium',10)/
data table4_233(12) /type_of_aerosol('nitrogen_monoxide',11)/
data table4_233(13) /type_of_aerosol('atomic_oxygen',12)/
data table4_233(14) /type_of_aerosol('nitrate_radical',13)/
data table4_233(15) /type_of_aerosol('hydroperoxyl_radical',14)/
data table4_233(16) /type_of_aerosol('dinitrogen_pentoxide',15)/
data table4_233(17) /type_of_aerosol('nitrous_acid',16)/
data table4_233(18) /type_of_aerosol('nitric_acid',17)/
data table4_233(19) /type_of_aerosol('peroxynitric_acid',18)/
data table4_233(20) /type_of_aerosol('hydrogen_peroxide',19)/
data table4_233(21) /type_of_aerosol('molecular_hydrogen',20)/
data table4_233(22) /type_of_aerosol('atomic_nitrogen',21)/
data table4_233(23) /type_of_aerosol('sulphate',22)/
data table4_233(24) /type_of_aerosol('radon',23)/
data table4_233(25) /type_of_aerosol('elemental_mercury',24)/
data table4_233(26) /type_of_aerosol('divalent_mercury',25)/
data table4_233(27) /type_of_aerosol('atomic_chlorine',26)/
data table4_233(28) /type_of_aerosol('chlorine_monoxide',27)/
data table4_233(29) /type_of_aerosol('dichlorine_peroxide',28)/
data table4_233(30) /type_of_aerosol('hypochlorous_acid',29)/
data table4_233(31) /type_of_aerosol('chlorine_nitrate',30)/
data table4_233(32) /type_of_aerosol('chlorine_dioxide',31)/
data table4_233(33) /type_of_aerosol('atomic_bromide',32)/
data table4_233(34) /type_of_aerosol('bromine_monoxide',33)/
data table4_233(35) /type_of_aerosol('bromine_chloride',34)/
data table4_233(36) /type_of_aerosol('hydrogen_bromide',35)/
data table4_233(37) /type_of_aerosol('hypobromous_acid',36)/
data table4_233(38) /type_of_aerosol('bromine_nitrate',37)/
data table4_233(39) /type_of_aerosol('hydroxyl_radical',10000)/
data table4_233(40) /type_of_aerosol('methyl_peroxy_radical',10001)/
data table4_233(41) /type_of_aerosol('methyl_hydroperoxide',10002)/
data table4_233(42) /type_of_aerosol('methanol',10004)/
data table4_233(43) /type_of_aerosol('formic_acid',10005)/
data table4_233(44) /type_of_aerosol('hydrogen_cyanide',10006)/
data table4_233(45) /type_of_aerosol('aceto_nitrile',10007)/
data table4_233(46) /type_of_aerosol('ethane',10008)/
data table4_233(47) /type_of_aerosol('ethene',10009)/
data table4_233(48) /type_of_aerosol('ethyne',10010)/
data table4_233(49) /type_of_aerosol('ethanol',10011)/
data table4_233(50) /type_of_aerosol('acetic_acid',10012)/
data table4_233(51) /type_of_aerosol('peroxyacetyl_nitrate',10013)/
data table4_233(52) /type_of_aerosol('propane',10014)/
data table4_233(53) /type_of_aerosol('propene',10015)/
data table4_233(54) /type_of_aerosol('butanes',10016)/
data table4_233(55) /type_of_aerosol('isoprene',10017)/
data table4_233(56) /type_of_aerosol('alpha_pinene',10018)/
data table4_233(57) /type_of_aerosol('beta_pinene',10019)/
data table4_233(58) /type_of_aerosol('limonene',10020)/
data table4_233(59) /type_of_aerosol('benzene',10021)/
data table4_233(60) /type_of_aerosol('toluene',10022)/
data table4_233(61) /type_of_aerosol('xylene',10023)/
data table4_233(62) /type_of_aerosol('dumethyl_sulphide',10500)/
data table4_233(63) /type_of_aerosol('hydrogen_chloride',20001)/
data table4_233(64) /type_of_aerosol('cfc-11',20002)/
data table4_233(65) /type_of_aerosol('cfc-12',20003)/
data table4_233(66) /type_of_aerosol('cfc-113',20004)/
data table4_233(67) /type_of_aerosol('cfc-113a',20005)/
data table4_233(68) /type_of_aerosol('cfc-114',20006)/
data table4_233(69) /type_of_aerosol('cfc-115',20007)/
data table4_233(70) /type_of_aerosol('hcfc-22',20008)/
data table4_233(71) /type_of_aerosol('hcfc-141b',20009)/
data table4_233(72) /type_of_aerosol('hcfc-142b',20010)/
data table4_233(73) /type_of_aerosol('halon-1202',20011)/
data table4_233(74) /type_of_aerosol('halon-1211',20012)/
data table4_233(75) /type_of_aerosol('halon-1301',20013)/
data table4_233(76) /type_of_aerosol('halon-2402',20014)/
data table4_233(77) /type_of_aerosol('methyl_chloride',20015)/
data table4_233(78) /type_of_aerosol('carbon_tetrachloride',20016)/
data table4_233(79) /type_of_aerosol('hcc-140a',20017)/
data table4_233(80) /type_of_aerosol('methyl_bromide',20018)/
data table4_233(81) /type_of_aerosol('hexachlorocyclohexane',20019)/
data table4_233(82) /type_of_aerosol('alpha_hexachlorocyclohexane',20020)/
data table4_233(83) /type_of_aerosol('hexachlorobiphenyl',20021)/
data table4_233(84) /type_of_aerosol('radioactive_pollutant',30000)/
data table4_233(85) /type_of_aerosol('hox_radical',60000)/
data table4_233(86) /type_of_aerosol('total_inorganic_org_peroxy_radicals',60001)/
data table4_233(87) /type_of_aerosol('passive_ozone',60002)/
data table4_233(88) /type_of_aerosol('nox_nitrogen',60003)/
data table4_233(89) /type_of_aerosol('all_nitrogen_oxides',60004)/
data table4_233(90) /type_of_aerosol('total_inorganic_chlorine',60005)/
data table4_233(91) /type_of_aerosol('total_inorganic_bromine',60006)/
data table4_233(92) /type_of_aerosol('total_inorganic_chlorine_noHclClono2Clox',60007)/
data table4_233(93) /type_of_aerosol('total_inorganic_bromine_noHbrBrono2Brox',60008)/
data table4_233(94) /type_of_aerosol('lumped_alkanes',60009)/
data table4_233(95) /type_of_aerosol('lumped_alkenes',60010)/
data table4_233(96) /type_of_aerosol('lumped_aromatic_comp',60011)/
data table4_233(97) /type_of_aerosol('lumped_terpenes',60012)/
data table4_233(98) /type_of_aerosol('non_methane_volatile_org_comp_carbon)',60013)/
data table4_233(99) /type_of_aerosol('anthropogenic_non_methane_voiatile_org_comp_carbon',60014)/
data table4_233(100) /type_of_aerosol('biogenic_non_methane_volatile_org_comp_carbon',60015)/
data table4_233(101) /type_of_aerosol('lumped_oxygenated_hydrocarbon',60016)/
data table4_233(102) /type_of_aerosol('total_aerosol',62000)/
data table4_233(103) /type_of_aerosol('dust_dry',62001)/
data table4_233(104) /type_of_aerosol('water_in_ambient',62002)/
data table4_233(105) /type_of_aerosol('ammonium_dry',62003)/
data table4_233(106) /type_of_aerosol('nitrate_dry',62004)/
data table4_233(107) /type_of_aerosol('nitric_acid_trihydrate',62005)/
data table4_233(108) /type_of_aerosol('sulphate_dry',62006)/
data table4_233(109) /type_of_aerosol('mercury_dry',62007)/
data table4_233(110) /type_of_aerosol('sea_salt_dry',62008)/
data table4_233(111) /type_of_aerosol('black_carbon_dry',62009)/
data table4_233(112) /type_of_aerosol('particulate_org_matter_dry',62010)/
data table4_233(113) /type_of_aerosol('primary_particulate_org_matter_dry',62011)/
data table4_233(114) /type_of_aerosol('secondary_particulate_org_matter_dry',62012)/
data table4_233(115) /type_of_aerosol('missing',65535)/
data table4_233(116) /type_of_aerosol('black_carbon_hydrophilic',62013)/
data table4_233(117) /type_of_aerosol('black_carbon_hydrophobic',62014)/
data table4_233(118) /type_of_aerosol('particulate_org_matter_hydrophilic',62015)/
data table4_233(119) /type_of_aerosol('particulate_org_matter_hydrophobic',62016)/
data table4_233(120) /type_of_aerosol('nitrate_hydrophilic',62017)/
data table4_233(121) /type_of_aerosol('nitrate_hydrophobic',62018)/
data table4_233(122) /type_of_aerosol('smoke_hi_absorption',62020)/
data table4_233(123) /type_of_aerosol('smoke_lo_absorption',62021)/
data table4_233(124) /type_of_aerosol('aerosol_hi_absorption',62022)/
data table4_233(125) /type_of_aerosol('aerosol_lo_absorption',62023)/
data table4_233(126) /type_of_aerosol('volcanic_ash',62025)/
! Add new parameter (04/12/2022)
data table4_233(127) /type_of_aerosol('brown_carbon_dry',63034)/
!
!
type type_of_orig_field_vals
character(len=50) :: typeoforigfieldvalskey
integer :: typeoforigfieldvals
end type type_of_orig_field_vals
!
!> table5_1
type(type_of_orig_field_vals), dimension(MAXTYPEOFORIGFIELDVAL) :: table5_1
data table5_1(1) /type_of_orig_field_vals('fltng_pnt',0)/
data table5_1(2) /type_of_orig_field_vals('integer',1)/
data table5_1(3) /type_of_orig_field_vals('local1',192)/
data table5_1(4) /type_of_orig_field_vals('local2',193)/
data table5_1(5) /type_of_orig_field_vals('local3',194)/
data table5_1(6) /type_of_orig_field_vals('local4',195)/
data table5_1(7) /type_of_orig_field_vals('local5',196)/
data table5_1(8) /type_of_orig_field_vals('local6',197)/
data table5_1(9) /type_of_orig_field_vals('local7',198)/
data table5_1(10) /type_of_orig_field_vals('local8',199)/
data table5_1(11) /type_of_orig_field_vals('local9',200)/
data table5_1(12) /type_of_orig_field_vals('local10',201)/
data table5_1(13) /type_of_orig_field_vals('missing',255)/
!
!
type order_of_sptdiff_vals
character(len=50) :: ordofsptdiffkey
integer :: ordofsptdiffvals
end type order_of_sptdiff_vals
!
!> table5_6
type(order_of_sptdiff_vals), dimension(MAXORDOFSPTDIFF) :: table5_6
data table5_6(1) /order_of_sptdiff_vals('1st_ord_sptdiff',1)/
data table5_6(2) /order_of_sptdiff_vals('2nd_ord_sptdiff',2)/
data table5_6(3) /order_of_sptdiff_vals('missing',255)/
!
!
type type_of_compression
character(len=50) :: typeofcompressionkey
integer :: typeofcompressionvals
end type type_of_compression
!
!> table5_40
type(type_of_compression), dimension(MAXTYPEOFCOMPRESSION) :: table5_40
data table5_40(1) /type_of_compression('lossless',0)/
data table5_40(2) /type_of_compression('lossy',1)/
data table5_40(3) /type_of_compression('missing',255)/
!
!
type type_of_packingmethod
character(len=50) :: packingmethodkey
integer :: packingmethodvals
end type type_of_packingmethod
!
!> table5_0
type(type_of_packingmethod), dimension(MAXTYPEOFPACKINGMETHOD) :: table5_0
data table5_0(1) /type_of_packingmethod('simple_packing',0)/
data table5_0(2) /type_of_packingmethod('maxtric_simple_packing',1)/
data table5_0(3) /type_of_packingmethod('complex_packing',2)/
data table5_0(4) /type_of_packingmethod('complex_packing_spatial_diff',3)/
data table5_0(5) /type_of_packingmethod('ieee_floating_point',4)/
data table5_0(6) /type_of_packingmethod('jpeg2000',40)/
data table5_0(7) /type_of_packingmethod('png',41)/
data table5_0(8) /type_of_packingmethod('spectral_simple_packing',50)/
data table5_0(9) /type_of_packingmethod('spectral_complex_packing',51)/
data table5_0(10) /type_of_packingmethod('simple_packing_log_preprcs',61)/
data table5_0(11) /type_of_packingmethod('run_length_packing_lvl_val',200)/
!
!
type origin_centers
character(len=50) :: origincenterskey
integer :: origincentersval
end type origin_centers
!
!> ON388 Table
type(origin_centers),dimension(MAXORIGINCENTERS) :: on388_table0
data on388_table0(1) /origin_centers('melbourne1',1)/
data on388_table0(2) /origin_centers('melbourne2',2)/
data on388_table0(3) /origin_centers('melbourne3',3)/
data on388_table0(4) /origin_centers('moscow1',4)/
data on388_table0(5) /origin_centers('moscow2',5)/
data on388_table0(6) /origin_centers('moscow3',6)/
data on388_table0(7) /origin_centers('nws_ncep',7)/
data on388_table0(8) /origin_centers('nws_nwstg',8)/
data on388_table0(9) /origin_centers('nws_other',9)/
data on388_table0(10) /origin_centers('cairo1',10)/
data on388_table0(11) /origin_centers('cairo2',11)/
data on388_table0(12) /origin_centers('dakar1',12)/
data on388_table0(13) /origin_centers('dakar2',13)/
data on388_table0(14) /origin_centers('nairobi1',14)/
data on388_table0(15) /origin_centers('nairobi2',15)/
data on388_table0(16) /origin_centers('casablanca',16)/
data on388_table0(17) /origin_centers('tunis',17)/
data on388_table0(18) /origin_centers('tunis_casablanca1',18)/
data on388_table0(19) /origin_centers('tunis-casablanca2',19)/
data on388_table0(20) /origin_centers('las_palmas',20)/
data on388_table0(21) /origin_centers('algiers',21)/
data on388_table0(22) /origin_centers('acmad',22)/
data on388_table0(23) /origin_centers('mozambique',23)/
data on388_table0(24) /origin_centers('pretoria',24)/
data on388_table0(25) /origin_centers('la_reunion',25)/
data on388_table0(26) /origin_centers('khabarovsk1',26)/
data on388_table0(27) /origin_centers('khabarovsk2',27)/
data on388_table0(28) /origin_centers('new_delhi1',28)/
data on388_table0(29) /origin_centers('new_delhi2',29)/
data on388_table0(30) /origin_centers('novosibirsk1',30)/
data on388_table0(31) /origin_centers('novosibirsk2',31)/
data on388_table0(32) /origin_centers('tashkent',32)/
data on388_table0(33) /origin_centers('jeddah',33)/
data on388_table0(34) /origin_centers('jma_tokyo1',34)/
data on388_table0(35) /origin_centers('jma_tokyo2',35)/
data on388_table0(36) /origin_centers('bankok',36)/
data on388_table0(37) /origin_centers('ulan_bator',37)/
data on388_table0(38) /origin_centers('beijing1',38)/
data on388_table0(39) /origin_centers('beijing2',39)/
data on388_table0(40) /origin_centers('seoul',40)/
data on388_table0(41) /origin_centers('buenos_aires1',41)/
data on388_table0(42) /origin_centers('buenos_aires2',42)/
data on388_table0(43) /origin_centers('brasilia1',43)/
data on388_table0(44) /origin_centers('brasilia2',44)/
data on388_table0(45) /origin_centers('santiago',45)/
data on388_table0(46) /origin_centers('brazilian_inpe',46)/
data on388_table0(47) /origin_centers('columbia',47)/
data on388_table0(48) /origin_centers('ecuador',48)/
data on388_table0(49) /origin_centers('peru',49)/
data on388_table0(50) /origin_centers('venezuela',50)/
data on388_table0(51) /origin_centers('miami',51)/
data on388_table0(52) /origin_centers('tpc_nhc',52)/
data on388_table0(53) /origin_centers('cms_montreal1',53)/
data on388_table0(54) /origin_centers('cms_montreal2',54)/
data on388_table0(55) /origin_centers('san_francisco',55)/
data on388_table0(56) /origin_centers('arinc_center',56)/
data on388_table0(57) /origin_centers('usaf_gwc',57)/
data on388_table0(58) /origin_centers('us_navy_fnoc',58)/
data on388_table0(59) /origin_centers('noaa_fsl_boulder',59)/
data on388_table0(60) /origin_centers('ncar_boulder',60)/
data on388_table0(61) /origin_centers('service_argos',61)/
data on388_table0(62) /origin_centers('us_naval_ocean_off',62)/
data on388_table0(63) /origin_centers('honolulu',64)/
data on388_table0(64) /origin_centers('darwin1',65)/
data on388_table0(65) /origin_centers('darwin2',66)/
data on388_table0(66) /origin_centers('melbourne4',67)/
data on388_table0(67) /origin_centers('wellington1',69)/
data on388_table0(68) /origin_centers('wellington2',70)/
data on388_table0(69) /origin_centers('nadi',71)/
data on388_table0(70) /origin_centers('singapore',72)/
data on388_table0(71) /origin_centers('malaysia',73)/
data on388_table0(72) /origin_centers('ukmo_exeter1',74)/
data on388_table0(73) /origin_centers('ukmo_exeter2',75)/
data on388_table0(74) /origin_centers('moscow4',76)/
data on388_table0(75) /origin_centers('offenbach1',78)/
data on388_table0(76) /origin_centers('offenbach2',79)/
data on388_table0(77) /origin_centers('rome1',80)/
data on388_table0(78) /origin_centers('rome2',81)/
data on388_table0(79) /origin_centers('norrkoping1',82)/
data on388_table0(80) /origin_centers('norrkoping2',83)/
data on388_table0(81) /origin_centers('french_weather_toulouse1',84)/
data on388_table0(82) /origin_centers('french_weather_toulouse2',85)/
data on388_table0(83) /origin_centers('helsinki',86)/
data on388_table0(84) /origin_centers('belgrade',87)/
data on388_table0(85) /origin_centers('oslo',88)/
data on388_table0(86) /origin_centers('prague',89)/
data on388_table0(87) /origin_centers('episkopi',90)/
data on388_table0(88) /origin_centers('ankara',91)/
data on388_table0(89) /origin_centers('frankfurt_main',92)/
data on388_table0(90) /origin_centers('london',93)/
data on388_table0(91) /origin_centers('copenhagen',94)/
data on388_table0(92) /origin_centers('rota',95)/
data on388_table0(93) /origin_centers('athens',96)/
data on388_table0(94) /origin_centers('esa',97)/
data on388_table0(95) /origin_centers('ecmwf',98)/
data on388_table0(96) /origin_centers('de_bilt_netherlands',99)/
data on388_table0(97) /origin_centers('brazzaville',100)/
data on388_table0(98) /origin_centers('abidjan',101)/
data on388_table0(99) /origin_centers('libyan_arab_jamahiriya',102)/
data on388_table0(100) /origin_centers('madagascar',103)/
data on388_table0(101) /origin_centers('mauritius',104)/
data on388_table0(102) /origin_centers('niger',105)/
data on388_table0(103) /origin_centers('seychelles',106)/
data on388_table0(104) /origin_centers('uganda',107)/
data on388_table0(105) /origin_centers('tanzania',108)/
data on388_table0(106) /origin_centers('zimbabwe',109)/
data on388_table0(107) /origin_centers('hong_kong',110)/
data on388_table0(108) /origin_centers('afghanistan',111)/
data on388_table0(109) /origin_centers('bahrain',112)/
data on388_table0(110) /origin_centers('bangladesh',113)/
data on388_table0(111) /origin_centers('bhutan',114)/
data on388_table0(112) /origin_centers('cambodia',115)/
data on388_table0(113) /origin_centers('dprk',116)/
data on388_table0(114) /origin_centers('iran',117)/
data on388_table0(115) /origin_centers('iraq',118)/
data on388_table0(116) /origin_centers('kazakhstan',119)/
data on388_table0(117) /origin_centers('kuwait',120)/
data on388_table0(118) /origin_centers('kyrgyz_republic',121)/
data on388_table0(119) /origin_centers('lao_pdr',122)/
data on388_table0(120) /origin_centers('macao_china',123)/
data on388_table0(121) /origin_centers('maldives',124)/
data on388_table0(122) /origin_centers('myanmar',125)/
data on388_table0(123) /origin_centers('nepal',126)/
data on388_table0(124) /origin_centers('oman',127)/
data on388_table0(125) /origin_centers('pakistan',128)/
data on388_table0(126) /origin_centers('qatar',129)/
data on388_table0(127) /origin_centers('yemen',130)/
data on388_table0(128) /origin_centers('sri_lanka',131)/
data on388_table0(129) /origin_centers('tajikistan',132)/
data on388_table0(130) /origin_centers('turkmenistan',133)/
data on388_table0(131) /origin_centers('uae',134)/
data on388_table0(132) /origin_centers('uzbekistan',135)/
data on388_table0(133) /origin_centers('viet_nam ',136)/
data on388_table0(134) /origin_centers('bolivia',140)/
data on388_table0(135) /origin_centers('guyana',141)/
data on388_table0(136) /origin_centers('paraguay',142)/
data on388_table0(137) /origin_centers('suriname',143)/
data on388_table0(138) /origin_centers('uruguay',144)/
data on388_table0(139) /origin_centers('french_guyana',145)/
data on388_table0(140) /origin_centers('brazilian_navy_hydro_center',146)/
data on388_table0(141) /origin_centers('antigua_barbuda',150)/
data on388_table0(142) /origin_centers('bahamas',151)/
data on388_table0(143) /origin_centers('barbados',152)/
data on388_table0(144) /origin_centers('belize',153)/
data on388_table0(145) /origin_centers('british_caribbean_terr_center',154)/
data on388_table0(146) /origin_centers('san_jose',155)/
data on388_table0(147) /origin_centers('cuba',156)/
data on388_table0(148) /origin_centers('dominica',157)/
data on388_table0(149) /origin_centers('dominican_republic',158)/
data on388_table0(150) /origin_centers('el_salvador',159)/
data on388_table0(151) /origin_centers('us_noaa_nesdis',160)/
data on388_table0(152) /origin_centers('us_noaa_oar',161)/
data on388_table0(153) /origin_centers('guatemala',162)/
data on388_table0(154) /origin_centers('haiti',163)/
data on388_table0(155) /origin_centers('honduras',164)/
data on388_table0(156) /origin_centers('jamaica',165)/
data on388_table0(157) /origin_centers('mexico',166)/
data on388_table0(158) /origin_centers('netherlands_antilles_aruba',167)/
data on388_table0(159) /origin_centers('nicaragua',168)/
data on388_table0(160) /origin_centers('panama',169)/
data on388_table0(161) /origin_centers('saint_lucia',170)/
data on388_table0(162) /origin_centers('trinidad_tobago',171)/
data on388_table0(163) /origin_centers('french_departments',172)/
data on388_table0(164) /origin_centers('cook_islands',190)/
data on388_table0(165) /origin_centers('french_polynesia',191)/
data on388_table0(166) /origin_centers('tonga',192)/
data on388_table0(167) /origin_centers('vanuatu',193)/
data on388_table0(168) /origin_centers('brunei',194)/
data on388_table0(169) /origin_centers('indonesia',195)/
data on388_table0(170) /origin_centers('kiribati',196)/
data on388_table0(171) /origin_centers('federated_states_micronesia',197)/
data on388_table0(172) /origin_centers('new_caledonia',198)/
data on388_table0(173) /origin_centers('niue',199)/
data on388_table0(174) /origin_centers('papua_new_guinea',200)/
data on388_table0(175) /origin_centers('philippines',201)/
data on388_table0(176) /origin_centers('samoa',202)/
data on388_table0(177) /origin_centers('solomon_islands',203)/
data on388_table0(178) /origin_centers('frascati',210)/
data on388_table0(179) /origin_centers('lanion',211)/
data on388_table0(180) /origin_centers('lisboa',212)/
data on388_table0(181) /origin_centers('reykjavik',213)/
data on388_table0(182) /origin_centers('madrid',214)/
data on388_table0(183) /origin_centers('zurich',215)/
data on388_table0(184) /origin_centers('service_argos_toulouse_fr',216)/
data on388_table0(185) /origin_centers('bratislava',217)/
data on388_table0(186) /origin_centers('budapest',218)/
data on388_table0(187) /origin_centers('ljubljana',219)/
data on388_table0(188) /origin_centers('warsaw',220)/
data on388_table0(189) /origin_centers('zagreb',221)/
data on388_table0(190) /origin_centers('albania',222)/
data on388_table0(191) /origin_centers('armenia',223)/
data on388_table0(192) /origin_centers('austria',224)/
data on388_table0(193) /origin_centers('azerbaijan',225)/
data on388_table0(194) /origin_centers('belarus',226)/
data on388_table0(195) /origin_centers('belgium',227)/
data on388_table0(196) /origin_centers('bosnia_herzegovina',228)/
data on388_table0(197) /origin_centers('bulgaria',229)/
data on388_table0(198) /origin_centers('cyprus',230)/
data on388_table0(199) /origin_centers('estonia',231)/
data on388_table0(200) /origin_centers('georgia',232)/
data on388_table0(201) /origin_centers('dublin',233)/
data on388_table0(202) /origin_centers('israel',234)/
data on388_table0(203) /origin_centers('jordan',235)/
data on388_table0(204) /origin_centers('latvia',236)/
data on388_table0(205) /origin_centers('lebanon',237)/
data on388_table0(206) /origin_centers('lithuania',238)/
data on388_table0(207) /origin_centers('luxembourg',239)/
data on388_table0(208) /origin_centers('malta',240)/
data on388_table0(209) /origin_centers('monaco',241)/
data on388_table0(210) /origin_centers('romania',242)/
data on388_table0(211) /origin_centers('syrian_arab_republic',243)/
data on388_table0(212) /origin_centers('macedonia',244)/
data on388_table0(213) /origin_centers('ukraine',245)/
data on388_table0(214) /origin_centers('republic_moldova',246)/
data on388_table0(215) /origin_centers('eumetsat_op_cen',254)/
data on388_table0(216) /origin_centers('missing',255)/
!
! Added original center (06/26/2019)
!
data on388_table0(217) /origin_centers('ncsa_argentina',147)/
data on388_table0(218) /origin_centers('brazilian_decea',148)/
!
!
type gen_proc
character(len=30) :: genprockey
integer :: genprocval
end type gen_proc
!
!> ON 388 Table A
type(gen_proc),dimension(MAXGENPROC) :: on388_tablea
data on388_tablea(1) /gen_proc('res',0)/
data on388_tablea(2) /gen_proc('uvim',2)/
data on388_tablea(3) /gen_proc('ncep_arl_tdm',3)/
data on388_tablea(4) /gen_proc('ncep_arl_smoke',4)/
data on388_tablea(5) /gen_proc('sat_der_prec_temp',5)/
data on388_tablea(6) /gen_proc('gwind_wave_mod',10)/
data on388_tablea(7) /gen_proc('multi_grid_wave_mod',11)/
data on388_tablea(8) /gen_proc('prob_st_surg',12)/
data on388_tablea(9) /gen_proc('lfm_anal',19)/
data on388_tablea(10) /gen_proc('snow_cov_anal',25)/
data on388_tablea(11) /gen_proc('for_gen_field',30)/
data on388_tablea(12) /gen_proc('val_add_post_proc_field',31)/
data on388_tablea(13) /gen_proc('ngm',39)/
data on388_tablea(14) /gen_proc('goi_gfs',42)/
data on388_tablea(15) /gen_proc('goi_fnl',43)/
data on388_tablea(16) /gen_proc('ssta',44)/
data on388_tablea(17) /gen_proc('coast_ocm',45)/
data on388_tablea(18) /gen_proc('hycom_glob',46)/
data on388_tablea(19) /gen_proc('hycom_npb',47)/
data on388_tablea(20) /gen_proc('hycom_nab',48)/
data on388_tablea(21) /gen_proc('ozone_anal_tiros',49)/
data on388_tablea(22) /gen_proc('ozone_anal_nimbus',52)/
data on388_tablea(23) /gen_proc('lfm_fofm',53)/
data on388_tablea(24) /gen_proc('roi',64)/
data on388_tablea(25) /gen_proc('t80l18gfs',68)/
data on388_tablea(26) /gen_proc('t80l18mrf',69)/
data on388_tablea(27) /gen_proc('qlm',70)/
data on388_tablea(28) /gen_proc('fogfm_opc',73)/
data on388_tablea(29) /gen_proc('gulf_of_mex_wind_wave',74)/
data on388_tablea(30) /gen_proc('gulf_of_alas_wind_wave',75)/
data on388_tablea(31) /gen_proc('bias_corr_mrf',76)/
data on388_tablea(32) /gen_proc('t126l28gfs',77)/
data on388_tablea(33) /gen_proc('t126l28mrf',78)/
data on388_tablea(34) /gen_proc('backup_from_prev_run',79)/
data on388_tablea(35) /gen_proc('t62l28mrf',80)/
data on388_tablea(36) /gen_proc('anal_gfs',81)/
data on388_tablea(37) /gen_proc('anal_gdas',82)/
data on388_tablea(38) /gen_proc('meso_nam12km',84)/
data on388_tablea(39) /gen_proc('early_hur_wind_speed_prob',86)/
data on388_tablea(40) /gen_proc('cac_ensem_fcsts_spect',87)/
data on388_tablea(41) /gen_proc('nww3_owm',88)/
data on388_tablea(42) /gen_proc('nmm_8km',89)/
data on388_tablea(43) /gen_proc('t62l28extmrf',90)/
data on388_tablea(44) /gen_proc('t62l28extgfs',91)/
data on388_tablea(45) /gen_proc('t62l28mrffnl',92)/
data on388_tablea(46) /gen_proc('t62l28gdasmrf',93)/
data on388_tablea(47) /gen_proc('t170l42mrf',94)/
data on388_tablea(48) /gen_proc('t126l42mrf',95)/
data on388_tablea(49) /gen_proc('gfs_avn',96)/
data on388_tablea(50) /gen_proc('cfs_t62l64_l40mom3',98)/
data on388_tablea(51) /gen_proc('misc_test_id',99)/
data on388_tablea(52) /gen_proc('ruc_sanal_60km_40n',100)/
data on388_tablea(53) /gen_proc('core',101)/
data on388_tablea(54) /gen_proc('rap',105)/
data on388_tablea(55) /gen_proc('gefs',107)/
data on388_tablea(56) /gen_proc('lamp',108)/
data on388_tablea(57) /gen_proc('rtma',109)/
data on388_tablea(58) /gen_proc('nam_15k',110)/
data on388_tablea(59) /gen_proc('nam_gen_sref',111)/
data on388_tablea(60) /gen_proc('wrf_nmm_ncep',112)/
data on388_tablea(61) /gen_proc('prod_ncep_sref',113)/
data on388_tablea(62) /gen_proc('naefs_prod_ncep_cmc',114)/
data on388_tablea(63) /gen_proc('down_scal_gfs_nam_ext',115)/
data on388_tablea(64) /gen_proc('wrf_em_ncar_arwrf',116)/
data on388_tablea(65) /gen_proc('ice_conc_anal',120)/
data on388_tablea(66) /gen_proc('wna_reg_wav_mod',121)/
data on388_tablea(67) /gen_proc('alas_wat_reg_wav_mod',122)/
data on388_tablea(68) /gen_proc('na_hurr_wav_mod',123)/
data on388_tablea(69) /gen_proc('enp_reg_wav_mod',124)/
data on388_tablea(70) /gen_proc('np_hurr_wav_mod',125)/
data on388_tablea(71) /gen_proc('sea_ice_fcst_mod',126)/
data on388_tablea(72) /gen_proc('lake_ice_fcst_mod',127)/
data on388_tablea(73) /gen_proc('glob_oce_fcst_mod',128)/
data on388_tablea(74) /gen_proc('godas',129)/
data on388_tablea(75) /gen_proc('merge_fields_ruc_nam_gfs',130)/
data on388_tablea(76) /gen_proc('great_lakes_wave_mod',131)/
data on388_tablea(77) /gen_proc('narr',140)/
data on388_tablea(78) /gen_proc('ldafs',141)/
data on388_tablea(79) /gen_proc('nwsrfs',150)/
data on388_tablea(80) /gen_proc('nwsffgs',151)/
data on388_tablea(81) /gen_proc('wsr_88d_s2_prec_anal',152)/
data on388_tablea(82) /gen_proc('wsr_88d_s3_prec_anal',153)/
data on388_tablea(83) /gen_proc('qpf_ncep',180)/
data on388_tablea(84) /gen_proc('rfcqpf_ncep',181)/
data on388_tablea(85) /gen_proc('rfcqpe_ncep',182)/
data on388_tablea(86) /gen_proc('ndfd_ncep_hpc',183)/
data on388_tablea(87) /gen_proc('ncwd_ncep_awc',190)/
data on388_tablea(88) /gen_proc('cipap_ncep_awc',191)/
data on388_tablea(89) /gen_proc('anal_ncep_awc',192)/
data on388_tablea(90) /gen_proc('fcst_ncep_awc',193)/
data on388_tablea(91) /gen_proc('cdas2',195)/
data on388_tablea(92) /gen_proc('cdas2_regen',196)/
data on388_tablea(93) /gen_proc('cdas',197)/
data on388_tablea(94) /gen_proc('cdas_regen',198)/
data on388_tablea(95) /gen_proc('cfsr_t382l64_l40mom4',199)/
data on388_tablea(96) /gen_proc('cpc_man_fcst',200)/
data on388_tablea(97) /gen_proc('cpc_auto_prod',201)/
data on388_tablea(98) /gen_proc('epa_usne',210)/
data on388_tablea(99) /gen_proc('epa_use',211)/
data on388_tablea(100) /gen_proc('spc_man_fcst',215)/
data on388_tablea(101) /gen_proc('ncep_opc_auto_prod',220)/
data on388_tablea(102) /gen_proc('missing',255)/
data on388_tablea(103) /gen_proc('ngac',117)/
data on388_tablea(104) /gen_proc('hrrr',83)/
data on388_tablea(105) /gen_proc('ncep_arl_dust',6)/
data on388_tablea(106) /gen_proc('hrricane_mult_wave',13)/
data on388_tablea(107) /gen_proc('extratropical_storm_surge',14)/
data on388_tablea(108) /gen_proc('nearshore_wave_prediction',15)/
data on388_tablea(109) /gen_proc('href',132)/
data on388_tablea(110) /gen_proc('great_lakes_short_range_mod',133)/
!
! Added new entries in tablea (06/27/2019)
!
data on388_tablea(111) /gen_proc('extra_trop_storm_surge',16)/
data on388_tablea(112) /gen_proc('extra_trop_storm_surge_pacific',17)/
data on388_tablea(113) /gen_proc('prob_extra_trop_storm_surge',18)/
data on388_tablea(114) /gen_proc('linmit_fine_mesh_anal',19)/
data on388_tablea(115) /gen_proc('extra_trop_storm_surge_micronesia',20)/
data on388_tablea(116) /gen_proc('hur_weather_res_and_fcst',71)/
data on388_tablea(117) /gen_proc('hur_non-hydro_multi',72)/
!
! Added new entries in tablea (03/11/2021)
!
data on388_tablea(118) /gen_proc('rrfs',134)/
!
! Added new entries in tablea (06/01/2021)
!
data on388_tablea(119) /gen_proc('hafs',135)/
!
! Added new enties in tablea (03/30/2023)
!
data on388_tablea(120) /gen_proc('extra_trop_storm_surge_atl_3d',21)/
data on388_tablea(121) /gen_proc('extra_trop_storm_surge_pac_3d',22)/
data on388_tablea(122) /gen_proc('extra_trop_storm_surge_micro_3d',23)/
contains
!
!> This subroutine returns the corresponding GRIB2 subcenters
!> value for a given short key name based on Table C
!>
!> @param[in] key - GRIB2 character short key for subcenter
!> @param[out] value - corresponding GRIB2 subcenter value from table c
!> @param[out] ierr - Error return code.
!> - 0 = no error
!> - 9 = key not found
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2009-12-10
subroutine get_g2_subcenters(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXSUBCEN
if (trim(tablec(n)%subcenkey).eq.trim(key)) then
value=tablec(n)%subcenval
return
endif
enddo
print *, 'get_g2_subcenters key: ', key, &
' not found in ON-388 table C'
ierr=9
return
end subroutine get_g2_subcenters
!>
!> This subroutine returns the corresponding GRIB2 version
!> number for a given short key name based on Table 1.0
!>
!> @param[in] key - GRIB2 character short key for version number
!> @param[out] value - corresponding GRIB2 version number value from table 1.0
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2009-12-10
subroutine get_g2_versionno(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXVER
if (trim(table1_0(n)%verskey).eq.trim(key)) then
value=table1_0(n)%versval
return
endif
enddo
print *, 'get_g2_versionno key: ', key, &
' not found in table 1.0'
ierr=9
return
end subroutine get_g2_versionno
!>
!> This subroutine returns the corresponding GRIB2 local table version
!> number for a given short key name based on Table 1.1
!>
!> @param[in] key - GRIB2 character short key for local table version number
!> @param[out] value - corresponding GRIB2 local table version number value from table 1.1
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2009-12-10
subroutine get_g2_loctabversno(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXLOCVER
if (trim(table1_1(n)%locverskey).eq.trim(key)) then
value=table1_1(n)%locversval
return
endif
enddo
print *, 'get_g2_loctabversno key: ', key, &
' not found in table 1.1'
ierr=9
return
end subroutine get_g2_loctabversno
!>
!> This subroutine returns the corresponding GRIB2 significant
!> reference time value for a given short key name based on Table 1.2
!> @param[in] key - GRIB2 character short key for significant reference time
!> @param[out] value - corresponding GRIB2 significant value from table 1.2
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2009-12-10
subroutine get_g2_sigreftime(key, value, ierr)
! integer, parameter :: MAXREFTIME=15
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXREFTIME
if (trim(table1_2(n)%sigrefkey).eq.trim(key)) then
value=table1_2(n)%sigrefval
return
endif
enddo
print *, 'get_g2_sigreftime key: ', key, &
' not found in table 1.2'
ierr=9
return
end subroutine get_g2_sigreftime
!>
!> This subroutine returns the corresponding GRIB2 production
!> status of data value for a given short key name based on Table 1.3
!>
!> @param[in] key - GRIB2 character short key for production status of data
!> @param[out] value - corresponding GRIB2 significant value from table 1.3
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2009-12-10
subroutine get_g2_prodstatus(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXPRODSTATUS
if (trim(table1_3(n)%prodstatuskey).eq.trim(key)) then
value=table1_3(n)%prodstatusval
return
endif
enddo
print *, 'get_g2_prodstatus key: ', key, &
' not found in table 1.3'
ierr=9
return
end subroutine get_g2_prodstatus
!>
!> This subroutine returns the corresponding GRIB2 type of
!> data value for a given short key name based on Table 1.4
!>
!> @param[in] key - GRIB2 character short key for production status of data
!> @param[out] value - corresponding GRIB2 type of data value from table 1.4
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2009-12-10
subroutine get_g2_typeofdata(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFDATA
if (trim(table1_4(n)%typeofdatakey).eq.trim(key)) then
value=table1_4(n)%typeofdataval
return
endif
enddo
print *, 'get_g2_typeofdata key: ', key, &
' not found in table 1.4'
ierr=9
return
end subroutine get_g2_typeofdata
!>
!> This subroutine returns the corresponding GRIB2 - Type of Generating
!> Process value for a given short key name based on Table 4.3 of Section 4, Octet 12
!>
!> @param[in] key - GRIB2 character short key for type of generating process from Table 4.3
!> @param[out] value - corresponding GRIB2 value from Table 4.3
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2009-12-10
subroutine get_g2_typeofgenproc(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFGENPROC
if (trim(table4_3(n)%typeofgenprockey).eq.trim(key)) then
value=table4_3(n)%typeofgenprocval
return
endif
enddo
print *, 'get_g2_typeofgenproc key}: ', key, &
' not found in table 4.3'
ierr=9
return
end subroutine get_g2_typeofgenproc
!>
!> This subroutine returns the corresponding GRIB2 - Indicator of unit of time
!> range value for a given short key name based on Table 4.4 of Section 4, Octet 18
!>
!> @param[in] key - GRIB2 character short key for indicator of unit of time range from Table 4.4
!> @param[out] value - corresponding GRIB2 value from Table 4.4
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2009-12-10
subroutine get_g2_unitoftimerange(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXUNITOFTIMERANGE
if (trim(table4_4(n)%unitoftimerangekey).eq.trim(key)) then
value=table4_4(n)%unitoftimerangeval
return
endif
enddo
value=255
print *, 'get_g2_unitoftimerange key: ', key, &
' not found in table 4.4'
ierr=9
return
end subroutine get_g2_unitoftimerange
!>
!> This subroutine returns the corresponding GRIB2 - Fixed Surface Types and Units
!> value for a given short key name based on Table 4.5 of Section 4, Octets 23 and 29
!>
!> @param[in] key - GRIB2 character short key for fixed surface types from Table 4.5
!> @param[out] value - corresponding GRIB2 value from Table 4.5
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2009-12-10
subroutine get_g2_fixedsurfacetypes(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXFIXEDSURFACETYPES
if (trim(table4_5(n)%fixedsurfacetypeskey).eq.trim(key)) then
value=table4_5(n)%fixedsurfacetypesval
return
endif
enddo
value=table4_5(66)%fixedsurfacetypesval
! print *, 'get_g2_fixedsurfacetypes key: ', trim(key), value, &
! ' not found in table 4.5'
! ierr=9
return
end subroutine get_g2_fixedsurfacetypes
!>
!> This subroutine returns the corresponding GRIB2 - Type of statistica
!> processing
!> value for a given short key name based on Table 4.10 of Section 4 Octets 47 (template 8)
!> 60 (temp 9), 48 (temp 10), 50 (temp 11), 49 (temp 12), 81 (temp 13), 77 (temp 14), 27 (temp 1001),
!> 25 (temp 1002) and 39 (temp 1101)
!>
!> @param[in] key - GRIB2 character short key for type of statistical processing from Table 4.10
!> @param[out] value - corresponding GRIB2 value from Table 4.10
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2009-12-10
subroutine get_g2_statprocesstypes(key, value, ierr)
character(len=*), intent(in) :: key
! integer, intent(out) :: value, ierr
integer :: value, ierr
integer :: n
!
do n=1, MAXSTATPROCESSTYPES
if (trim(table4_10(n)%statprocesstypeskey).eq.key) then
value=table4_10(n)%statprocesstypesval
return
endif
enddo
print *, 'get_g2_statprocesstypes key: ', key, &
' not found in table 4.10'
ierr=9
return
end subroutine get_g2_statprocesstypes
!>
!> This subroutine returns the corresponding GRIB2 - Type of time intervals
!> value for a given short key name based on Table 4.11 of Section 4 Octets 48 (template 8)
!> 61 (temp 9), 49 (temp 10), 51 (temp 11), 50 (temp 12), 82 (temp 13), 78 (tem p 14), 28 (temp 1001),
!> and 40 (temp 1101)
!>
!> @param[in] key - GRIB2 character short key for type of statistical processing from Table 4.11
!> @param[out] value - corresponding GRIB2 value from Table 4.11
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2010-04-03
subroutine get_g2_typeoftimeintervals(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFTIMEINTVLS
if (trim(table4_11(n)%typeoftimeintervalskey).eq.key) then
value=table4_11(n)%typeoftimeintervalsval
return
endif
enddo
print *, 'get_g2_typeoftimeintervals key: ', key, &
' not found in table 4.11'
ierr=9
return
end subroutine get_g2_typeoftimeintervals
!>
!> This subroutine returns the corresponding GRIB2 - Type of intervals
!> value for a given short key name based on Table 4.91 of Section 4 Octets 14 (template 44)
!> 14 (temp 45), 14 (temp 46), 15 (temp 47), 14 and 25 (temp 48)
!>
!> @param[in] key - GRIB2 character short key for type of intervals from Table 4.91
!> @param[out] value - corresponding GRIB2 value from Table 4.91
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2010-04-03
subroutine get_g2_typeofintervals(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFINTVLS
if (trim(table4_91(n)%typeofintervalskey).eq.trim(key)) then
value=table4_91(n)%typeofintervalsval
return
endif
enddo
if(trim(key).eq.'') then
value=255
return
endif
print *, 'get_g2_typeofintervals key: ', key, &
' not found in table 4.91'
ierr=9
return
end subroutine get_g2_typeofintervals
!>
!> This subroutine returns the corresponding GRIB2 - Type of aerosol
!> value for a given short key name based on Table 4.233 of Section 4 Octets 12-13
!> (template 44), 12-13 (temp 45), 12-13 (temp 46), 13-14 (temp 47),
!> 12-13 (temp 48)
!>
!> @param[in] key - GRIB2 character short key for type of aerosol from Table 4.233
!> @param[out] value - corresponding GRIB2 value from Table 4.233
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2010-04-03
subroutine get_g2_typeofaerosol(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFAEROSOL
if (trim(table4_233(n)%typeofaerosolkey).eq.trim(key)) then
value=table4_233(n)%typeofaerosolval
return
endif
enddo
if (trim(key).eq.'') then
value=65535
return
endif
print *, 'get_g2_typeofaerosol key: ', key, &
' not found in table 4.233'
ierr=9
return
end subroutine get_g2_typeofaerosol
!>
!> This subroutine returns the corresponding GRIB1 - PDS Ocet5
!> GRIB2 - Section 1, Octet 6-7 National/International Originating Centers
!> value for a given short key name based on ON388 - Table 0
!>
!> @param[in] key - GRIB1 character short key for originating center based on ON388 - Table 0
!> @param[out] value - corresponding GRIB1-PDS Octet 5/GRIB2-Section 1, Octets 6-7 value from ON388 - Table 0
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2009-12-10
subroutine get_g2_on388origincenters(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXORIGINCENTERS
if (trim(on388_table0(n)%origincenterskey).eq.trim(key)) then
value=on388_table0(n)%origincentersval
return
endif
enddo
print *, 'get_g2_on388origincenters key: ', key, &
' not found in ON-388 - table 0'
ierr=9
return
end subroutine get_g2_on388origincenters
!>
!> This subroutine returns the corresponding GRIB1 - PDS Ocet6
!> data value (Generating process or model) from originating center 7 (USNWS NCEP)
!> for a given short key name based on ON388 - Table A
!>
!> @param[in] key - GRIB1 character short key for model based on ON388 - Table A
!> @param[out] value - corresponding GRIB1 - PDS Octet 6 value from ON388 - Table A
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2009-12-10
subroutine get_g2_on388genproc(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXGENPROC
if (trim(on388_tablea(n)%genprockey).eq.trim(key)) then
value=on388_tablea(n)%genprocval
return
endif
enddo
print *, 'get_g2_on388genproc key: ', key, &
' not found in ON-388 - table A'
ierr=9
return
end subroutine get_g2_on388genproc
!>
!> This subroutine returns the corresponding GRIB2 - Table 5.1
!> Type of Original Field Values for a given short key name based on GRIB2 - Table 5.1
!>
!> @param[in] key - GRIB2 character short key for type of original field values based on Table 5.1
!> @param[out] value - corresponding GRIB2 - Table 5.1 value
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2010-03-08
subroutine get_g2_typeoforigfieldvals(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFORIGFIELDVAL
if (trim(table5_1(n)%typeoforigfieldvalskey).eq.trim(key)) then
value=table5_1(n)%typeoforigfieldvals
return
endif
enddo
print *, 'get_g2_typeoforigfieldvals key: ', key, &
' not found in table 5.1'
ierr=9
return
end subroutine get_g2_typeoforigfieldvals
!>
!> This subroutine returns the corresponding GRIB2 - Table 5.6
!> Order of spatial differencing for a given short key name based on GRIB2 - Table 5.6
!> default is 1st order spatial differencing
!>
!> @param[in] key - GRIB2 character short key for Order of spatial differencing based on Table 5.6
!> @param[out] value - corresponding GRIB2 - Table 5.6 value
!> @param[out] ierr - error messages
!>
!> @author J.Wang ORG: NCEP/EMC @date 2012-02-20
subroutine get_g2_ordofspcdiffvals(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXORDOFSPTDIFF
if (trim(table5_6(n)%ordofsptdiffkey).eq.trim(key)) then
value=table5_6(n)%ordofsptdiffvals
return
endif
enddo
print *, 'get_g2_ordofsptdiffvals key: ', key, &
' not found in table 5.6'
ierr=9
value=1
return
end subroutine get_g2_ordofspcdiffvals
!>
!> This subroutine returns the corresponding GRIB2 - Table 5.40
!> Type of compression for a given short key name based on GRIB2 - Table 5.40
!>
!> @param[in] key - GRIB2 character short key for type of compression based on Table 5.40
!> @param[out] value - corresponding GRIB2 - Table 5.40 value
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2010-03-08
subroutine get_g2_typeofcompression(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFCOMPRESSION
if (trim(table5_40(n)%typeofcompressionkey).eq.trim(key)) then
value=table5_40(n)%typeofcompressionvals
return
endif
enddo
print *, 'get_g2_typeofcompression key: ', key, &
' not found in table 5.40'
ierr=9
return
end subroutine get_g2_typeofcompression
!>
!> This subroutine returns the corresponding GRIB2 template number
!> for a given short key name based on GRIB2 -
!>
!> PROGRAM HISTORY LOG:
!> 2009-12-10 V. Krishna Kumar
!> 2010-03-15 Jun Wang : get section5 template number
!>
!> @param[in] key - GRIB2 character short key for packing method based on Table 5.0
!> @param[out] value - corresponding GRIB2 - Table 5.0 value
!> @param[out] ierr - error messages
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2010-03-08
subroutine get_g2_sec5packingmethod(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFPACKINGMETHOD
if (trim(table5_0(n)%packingmethodkey).eq.trim(key)) then
value=table5_0(n)%packingmethodvals
return
endif
enddo
print *, 'get_g2_sec5packingmethod key: ', key, &
' not found in table 5.0'
ierr=9
return
end subroutine get_g2_sec5packingmethod
!>
!> This subroutine returns the section 0 list for a given discipline
!> value
!>
!> @param[in] idisc - GRIB2 Discipline (From Table 0.0)
!> @param[out] listsec0 - Section 0
!> - listsec0(1) - GRIB2 Discipline (From Table 0.0)
!> - listsec0(2) - Edition number - 2 for GRIB2
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2010-03-01
subroutine g2sec0(idisc, listsec0)
integer :: idisc
integer :: listsec0(2)
!
listsec0(1) = idisc
listsec0(2) = 2 ! Edition number - 2 for GRIB2
end subroutine g2sec0
!>
!> This subroutine returns the section 1 list for given keys
!>
!> @param[in] origin_key - Identification of originating/generating center (See Table 0 {GRIB1})
!> @param[in] subcen_key - Identification of originating/generating subcenter (See Table C)
!> @param[in] vers_key - GRIB master tables version number (currently 2) (See Table 1.0) (See note 1 below)
!> @param[in] lvers_key - Version number of GRIB local tables used to augment Master Tables (see Table 1.1)
!> @param[in] sigreftime_key - Significance of reference time (See Table 1.2)
!> @param[in] refyear_val - Year (4 digits)
!> @param[in] refmon_val - Month
!> @param[in] refday_val - Day
!> @param[in] refhour_val - Hour
!> @param[in] refmin_val - Minute
!> @param[in] refsec_val - Second
!> @param[in] prodstatus_key - Production Status of Processed data in the GRIB message (See Table 1.3)
!> @param[in] typeofdata_key - Type of processed data in this GRIB message (See Table 1.4)
!> @param[out] listsec1 - GRIB2 Section 1 Identification Section values array
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2010-03-01
subroutine g2sec1(origin_key, subcen_key, vers_key, lvers_key, sigreftime_key, refyear_val, &
refmon_val, refday_val, refhour_val, refmin_val, refsec_val, prodstatus_key, &
typeofdata_key, listsec1)
! integer, intent(inout) :: listsec1(13)
integer :: listsec1(13)
integer :: refyear_val, refmon_val, refday_val, refhour_val, refmin_val, refsec_val
character(len=*) :: origin_key, subcen_key, vers_key, lvers_key, &
sigreftime_key, prodstatus_key, typeofdata_key
!
integer(4) :: value, ierr
!
call get_g2_on388origincenters(origin_key, value, ierr)
listsec1(1) = value
!
call get_g2_subcenters(subcen_key, value, ierr)
listsec1(2) = value
!
call get_g2_versionno(vers_key, value, ierr)
listsec1(3) = value
!
call get_g2_loctabversno(lvers_key, value, ierr)
listsec1(4) = value
!
call get_g2_sigreftime(sigreftime_key, value, ierr)
listsec1(5) = value
!
! Set the time yyyy, mm, dd, hh, min, sec
!
listsec1(6) = refyear_val
listsec1(7) = refmon_val
listsec1(8) = refday_val
listsec1(9) = refhour_val
listsec1(10) = refmin_val
listsec1(11) = refsec_val
!
call get_g2_prodstatus(prodstatus_key, value, ierr)
listsec1(12) = value
!
call get_g2_typeofdata(typeofdata_key, value, ierr)
listsec1(13) = value
!
end subroutine g2sec1
!>
!> This subroutine returns the Grib2 Section 4 Template 4.0 list for given keys
!> PDT 4.0 - Analysis or forecast at a horizontal level or in a
!> horizontal layer at a point in time.
!>
!> @param[in] icatg - Parameter category (see Code table 4.1)
!> @param[in] iparm - Parameter number (see Code table 4.2)
!> @param[in] typ_gen_proc_key - Type of generating process (see Code table 4.3)
!> @param[in] gen_proc_or_mod_key - Analysis or forecast generating process identified (see Code ON388 Table A)
!> @param[in] hrs_obs_cutoff - Hours of observational data cutoff after reference time (see Note)
!> @param[in] min_obs_cutoff - Minutes of observational data cutoff after reference time (see Note)
!> @param[in] unit_of_time_key - Indicator of unit of time range (see Code table 4.4)
!> @param[in] fcst_time - Forecast time in units defined by octet 18
!> @param[in] lvl_type1 - Type of first fixed surface (see Code table 4.5)
!> @param[in] scale_fac1 - Scale factor of first fixed surface
!> @param[in] scaled_val1 - Scaled value of first fixed surface
!> @param[in] lvl_type2 - Type of second fixed surfaced (see Code table 4.5)
!> @param[in] scale_fac2 - Scale factor of second fixed surface
!> @param[in] scaled_val2 - Scaled value of second fixed surfaces
!> @param[out] ipdstmpl0 - GRIB2 PDS Template 4.0 listing
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2010-03-01
subroutine g2sec4_temp0(icatg, iparm, typ_gen_proc_key, &
gen_proc_or_mod_key, hrs_obs_cutoff, min_obs_cutoff, &
unit_of_time_key, fcst_time, lvl_type1, scale_fac1, &
scaled_val1, lvl_type2, scale_fac2, scaled_val2, &
ipdstmpl0)
integer(4), intent(in) :: icatg, iparm, hrs_obs_cutoff, min_obs_cutoff, &
fcst_time, scale_fac1, scaled_val1, scale_fac2, scaled_val2
! integer(4), intent(inout) :: bckgnd_gen_proc_id ! defined by the center
!
character(len=*), intent(in) :: typ_gen_proc_key, gen_proc_or_mod_key, &
unit_of_time_key, lvl_type1, lvl_type2
!
integer(4), intent(inout) :: ipdstmpl0(15)
!
!local vars
integer(4) :: value, ierr
integer(4) :: bckgnd_gen_proc_id ! defined by the center
!
bckgnd_gen_proc_id=0 ! defined by the center
!
ipdstmpl0(1) = icatg
ipdstmpl0(2) = iparm
!
call get_g2_typeofgenproc(typ_gen_proc_key, value, ierr)
ipdstmpl0(3) = value
!
ipdstmpl0(4) = bckgnd_gen_proc_id
!
call get_g2_on388genproc(gen_proc_or_mod_key, value, ierr)
ipdstmpl0(5) = value
!
ipdstmpl0(6) = hrs_obs_cutoff
ipdstmpl0(7) = min_obs_cutoff
!
call get_g2_unitoftimerange(unit_of_time_key, value, ierr)
ipdstmpl0(8) = value
ipdstmpl0(9) = fcst_time
!
call get_g2_fixedsurfacetypes(lvl_type1, value, ierr)
ipdstmpl0(10) = value
ipdstmpl0(11) = scale_fac1
ipdstmpl0(12) = scaled_val1
!
call get_g2_fixedsurfacetypes(lvl_type2, value, ierr)
ipdstmpl0(13) = value
!
ipdstmpl0(14) = scale_fac2
ipdstmpl0(15) = scaled_val2
!
end subroutine g2sec4_temp0
!>
!> This subroutine returns the Grib2 Section 4 Template 4.8 list for given keys
!> PDT 4.8 - Average, accumulation, extreme values or other statistically
!> processed values at a horizontal level or in a horizontal layer
!> in a continuous or non-continuous time interval.
!>
!> PROGRAM HISTORY LOG:
!> 2010-03-01 V. Krishna Kumar
!> 2010-04-20 Jun Wang
!>
!> @param[in] icatg - Parameter category (see Code Table 4.1)
!> @param[in] iparm - Parameter number (see Code Table 4.2)
!> @param[in] typ_gen_proc_key - Type of generating process (see Code Table 4.3)
!> @param[in] gen_proc_or_mod_key - Analysis or forecast generating process identified (see Code ON388 Table A)
!> @param[in] hrs_obs_cutoff - Hours after reference time data cutoff (see Note 1)
!> @param[in] min_obs_cutoff - Minutes after reference time data cutoff
!> @param[in] unit_of_time_key - Indicator of unit of time range (see Code Table 4.4)
!> @param[in] fcst_time - Forecast time in units defined by octet 18 (see Note 2)
!> @param[in] lvl_type1 - Type of first fixed surface (see Code Table 4.5)
!> @param[in] scale_fac1 - Scale factor of first fixed surface
!> @param[in] scaled_val1 - Scaled value of first fixed surface
!> @param[in] lvl_type2 - Type of second fixed surfaced (see Code Table 4.5)
!> @param[in] scale_fac2 - Scale factor of second fixed surface
!> @param[in] scaled_val2 - Scaled value of second fixed surfaces
!> @param[in] year_intvl - Year Time of end of overall time interval
!> @param[in] mon_intvl - Month Time of end of overall time interval
!> @param[in] day_intvl - Day Time of end of overall time interval
!> @param[in] hour_intvl - Hour Time of end of overall time interval
!> @param[in] min_intvl - Minute Time of end of overall time interval
!> @param[in] sec_intvl - Second Time of end of overall time interval
!> @param[in] num_time_range - n number of time ranges specifications describing
!> the time intervals used to calculate the
!> statistically-processed field
!> @param[in] stat_miss_val - Total number of data values missing in statistical process
!> Specification of the outermost (or only) time range over
!> which statistical processing is done
!> @param[in] type_of_stat_proc - Statistical process used to calculate the processed
!> field from the field at each time increment during the
!> time range (see Code Table 4.10)
!> @param[in] type_of_time_inc - Type of time increment between successive fields
!> used in the statistical processing (see Code Table 4.11)
!> @param[in] stat_unit_time_key - Indicator of unit of time for time range over which
!> statistical processing is done (see Code Table 4.4)
!> @param[in] leng_time_range_stat - Length of the time range over which statistical processing
!> is done, in units defined by the previous octet
!> @param[in] stat_unit_time_key_succ - Indicator of unit of time for the increment between the
!> successive fields used (see Code table 4.4)
!> @param[in] time_inc_betwn_succ_fld - Time increment between successive fields,
!> in units defined by the previous octet (see Notes 3 & 4)
!> @param[out] ipdstmpl8 - GRIB2 PDS Template 4.8 listing
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2010-03-01
subroutine g2sec4_temp8(icatg, iparm, typ_gen_proc_key, gen_proc_or_mod_key, &
hrs_obs_cutoff, min_obs_cutoff, unit_of_time_key, &
fcst_time, lvl_type1, scale_fac1, scaled_val1, lvl_type2, &
scale_fac2, scaled_val2, year_intvl, &
mon_intvl, day_intvl, hour_intvl, min_intvl, sec_intvl, &
num_time_range, stat_miss_val, type_of_stat_proc, &
type_of_time_inc, stat_unit_time_key, &
leng_time_range_stat, stat_unit_time_key_succ, &
time_inc_betwn_succ_fld, ipdstmpl8)
!
integer(4), intent(in) :: icatg, iparm, hrs_obs_cutoff, min_obs_cutoff, fcst_time, &
scale_fac1, scaled_val1, scale_fac2, scaled_val2
integer(4), intent(in) :: year_intvl, mon_intvl, day_intvl, hour_intvl, min_intvl, &
sec_intvl, num_time_range, stat_miss_val, &
leng_time_range_stat, time_inc_betwn_succ_fld
!
character(len=*), intent(in) :: typ_gen_proc_key, gen_proc_or_mod_key, &
unit_of_time_key, lvl_type1, lvl_type2, &
type_of_stat_proc, type_of_time_inc, &
stat_unit_time_key, stat_unit_time_key_succ
!
integer(4) :: bckgnd_gen_proc_id ! defined by the center
!
integer(4), intent(inout) :: ipdstmpl8(29) ! currently works only for n=1
! later on, this will be generalized
!
!-- local vars
integer(4) :: value, ierr
!
bckgnd_gen_proc_id=0
!
ipdstmpl8(1) = icatg
ipdstmpl8(2) = iparm
!
call get_g2_typeofgenproc(typ_gen_proc_key, value, ierr)
ipdstmpl8(3) = value
!
ipdstmpl8(4) = bckgnd_gen_proc_id
!
call get_g2_on388genproc(gen_proc_or_mod_key, value, ierr)
ipdstmpl8(5) = value
!
ipdstmpl8(6) = hrs_obs_cutoff
ipdstmpl8(7) = min_obs_cutoff
!
call get_g2_unitoftimerange(unit_of_time_key, value, ierr)
ipdstmpl8(8) = value
ipdstmpl8(9) = fcst_time
!
call get_g2_fixedsurfacetypes(lvl_type1, value, ierr)
ipdstmpl8(10) = value
ipdstmpl8(11) = scale_fac1
ipdstmpl8(12) = scaled_val1
!
call get_g2_fixedsurfacetypes(lvl_type2, value, ierr)
ipdstmpl8(13) = value
!
ipdstmpl8(14) = scale_fac2
ipdstmpl8(15) = scaled_val2
ipdstmpl8(16) = year_intvl
ipdstmpl8(17) = mon_intvl
ipdstmpl8(18) = day_intvl
ipdstmpl8(19) = hour_intvl
ipdstmpl8(20) = min_intvl
ipdstmpl8(21) = sec_intvl
!
ipdstmpl8(22) = num_time_range ! choose n=1 for this case
ipdstmpl8(23) = stat_miss_val ! choose 0 for this case
!
call get_g2_statprocesstypes(type_of_stat_proc, value, ierr)
ipdstmpl8(24) = value ! types_of_stat_proc='accumulation'
!
call get_g2_typeoftimeintervals(type_of_time_inc, value, ierr)
ipdstmpl8(25) = value ! type_of_time_inc='same_start_time_fcst_fcst_time_inc'
! value = 2 (Successive times processed have same start
! time of forecast, forecast time is incremented)
!
call get_g2_unitoftimerange(stat_unit_time_key, value, ierr)
ipdstmpl8(26) = value ! stat_unit_time_key='hour'
! value = 1
ipdstmpl8(27) = leng_time_range_stat ! value = 6
!
call get_g2_unitoftimerange(stat_unit_time_key_succ, value, ierr)
! stat_unit_time_key_succ='missing'
ipdstmpl8(28) = value ! value = 255
!
ipdstmpl8(29) = time_inc_betwn_succ_fld ! value = 0
!
end subroutine g2sec4_temp8
!>
!> This subroutine returns the Grib2 Section 4 Template 4.44 list for given keys
!> PDT 4.44 - Analysis or forecast at a horizontal level or in a
!> horizontal layer at a point in time for aerosol
!>
!> @param[in] icatg - Parameter category (see Code table 4.1)
!> @param[in] iparm - Parameter number (see Code table 4.2)
!> @param[in] aer_type - Aetosol type (see Code table 4.233)
!> @param[in] typ_intvl_size - Type of interval for first and second size (see Code table 4.91)
!> @param[in] scale_fac1_size - Scale factor of first size
!> @param[in] scale_val1_size - Scale value of first size in meters
!> @param[in] scale_fac2_size - Scale factor of second size
!> @param[in] scale_val2_size - Scale value of second size in meters
!> @param[in] typ_gen_proc_key - Type of generating process (see Code table 4.3)
!> @param[in] gen_proc_or_mod_key - Analysis or forecast generating process identified (see Code ON388 Table A)
!> @param[in] hrs_obs_cutoff - Hours of observational data cutoff after reference time (see Note)
!> @param[in] min_obs_cutoff - Minutes of observational data cutoff after reference time (see Note)
!> @param[in] unit_of_time_key - Indicator of unit of time range (see Code table 4.4)
!> @param[in] fcst_time - Forecast time in units defined by octet 18
!> @param[in] lvl_type1 - Type of first fixed surface (see Code table 4.5)
!> @param[in] scale_fac1 - Scale factor of first fixed surface
!> @param[in] scaled_val1 - Scaled value of first fixed surface
!> @param[in] lvl_type2 - Type of second fixed surfaced (see Code table 4.5)
!> @param[in] scale_fac2 - Scale factor of second fixed surface
!> @param[in] scaled_val2 - Scaled value of second fixed surfaces
!> @param[out] ipdstmpl44 - GRIB2 PDS Template 4.44 listing
!>
!> @author J. WANG ORG: NCEP/EMC @date 2012-01-25
subroutine g2sec4_temp44(icatg, iparm, aer_type, typ_intvl_size, &
scale_fac1_size, scale_val1_size, scale_fac2_size, &
scale_val2_size, typ_gen_proc_key, &
gen_proc_or_mod_key, hrs_obs_cutoff, min_obs_cutoff, &
unit_of_time_key, fcst_time, lvl_type1, scale_fac1, &
scaled_val1, lvl_type2, scale_fac2, scaled_val2, &
ipdstmpl44)
integer(4), intent(in) :: icatg, iparm, hrs_obs_cutoff, min_obs_cutoff, &
scale_fac1_size, scale_fac2_size, &
fcst_time, scale_fac1, scaled_val1, scale_fac2, scaled_val2
real, intent(in) :: scale_val1_size, scale_val2_size
!
character(len=*), intent(in) :: aer_type, typ_intvl_size, typ_gen_proc_key, &
gen_proc_or_mod_key, unit_of_time_key, lvl_type1, lvl_type2
!
integer(4), intent(inout) :: ipdstmpl44(21)
!
!local vars
integer(4) :: value, ierr
integer(4) :: bckgnd_gen_proc_id ! defined by the center
!
bckgnd_gen_proc_id = 0 ! defined by the center
!
ipdstmpl44(1) = icatg
ipdstmpl44(2) = iparm
!
call get_g2_typeofaerosol(aer_type, value, ierr)
ipdstmpl44(3) = value
!
call get_g2_typeofintervals(typ_intvl_size, value, ierr)
ipdstmpl44(4) = value
ipdstmpl44(5) = scale_fac1_size
ipdstmpl44(6) = scale_val1_size
ipdstmpl44(7) = scale_fac2_size
ipdstmpl44(8) = scale_val2_size
!
call get_g2_typeofgenproc(typ_gen_proc_key, value, ierr)
ipdstmpl44(9) = value
!
ipdstmpl44(10) = bckgnd_gen_proc_id
!
call get_g2_on388genproc(gen_proc_or_mod_key, value, ierr)
ipdstmpl44(11) = value
!
ipdstmpl44(12) = hrs_obs_cutoff
ipdstmpl44(13) = min_obs_cutoff
!
call get_g2_unitoftimerange(unit_of_time_key, value, ierr)
ipdstmpl44(14) = value
ipdstmpl44(15) = fcst_time
!
call get_g2_fixedsurfacetypes(lvl_type1, value, ierr)
ipdstmpl44(16) = value
ipdstmpl44(17) = scale_fac1
ipdstmpl44(18) = scaled_val1
!
call get_g2_fixedsurfacetypes(lvl_type2, value, ierr)
ipdstmpl44(19) = value
!
ipdstmpl44(20) = scale_fac2
ipdstmpl44(21) = scaled_val2
!
end subroutine g2sec4_temp44
!>
!> This subroutine returns the Grib2 Section 4 Template 4.0 list for given keys
!> PDT 4.48 - Analysis or forecast at a horizontal level or in a
!> horizontal layer at a point in time for aerosol.
!>
!> @param[in] icatg - Parameter category (see Code table 4.1)
!> @param[in] iparm - Parameter number (see Code table 4.2)
!> @param[in] aer_type - Aetosol type (see Code table 4.233)
!> @param[in] typ_intvl_size - Type of interval for first and second size (see Code table 4.91)
!> @param[in] scale_fac1_size - Scale factor of first size
!> @param[in] scale_val1_size - Scale value of first size in meters
!> @param[in] scale_fac2_size - Scale factor of second size
!> @param[in] scale_val2_size - Scale value of second size in meters
!> @param[in] typ_intvl_wavelength - Type of interval for first and second wavelength (see Code table 4.91)
!> @param[in] scale_fac1_wavelength - Scale factor of first wavelength
!> @param[in] scale_val1_wavelength - Scale value of first wavelength in meters
!> @param[in] scale_fac2_wavelength - Scale factor of second wavelength
!> @param[in] scale_val2_wavelength - Scale value of second wavelength in meters
!> @param[in] typ_gen_proc_key - Type of generating process (see Code table 4.3)
!> @param[in] gen_proc_or_mod_key - Analysis or forecast generating process identified (see Code ON388 Table A)
!> @param[in] hrs_obs_cutoff - Hours of observational data cutoff after reference time (see Note)
!> @param[in] min_obs_cutoff - Minutes of observational data cutoff after reference time (see Note)
!> @param[in] unit_of_time_key - Indicator of unit of time range (see Code table 4.4)
!> @param[in] fcst_time - Forecast time in units defined by octet 18
!> @param[in] lvl_type1 - Type of first fixed surface (see Code table 4.5)
!> @param[in] scale_fac1 - Scale factor of first fixed surface
!> @param[in] scaled_val1 - Scaled value of first fixed surface
!> @param[in] lvl_type2 - Type of second fixed surfaced (see Code table 4.5)
!> @param[in] scale_fac2 - Scale factor of second fixed surface
!> @param[in] scaled_val2 - Scaled value of second fixed surfaces
!> @param[out] ipdstmpl48 - GRIB2 PDS Template 4.48 listing
!>
!> @author J. WANG ORG: NCEP/EMC @date 2012-01-25
subroutine g2sec4_temp48(icatg, iparm, aer_type, typ_intvl_size, &
scale_fac1_size, scale_val1_size, scale_fac2_size, &
scale_val2_size, typ_intvl_wavelength, &
scale_fac1_wavelength, scale_val1_wavelength, &
scale_fac2_wavelength, scale_val2_wavelength, &
typ_gen_proc_key, gen_proc_or_mod_key, &
hrs_obs_cutoff, min_obs_cutoff, &
unit_of_time_key, fcst_time, lvl_type1, scale_fac1, &
scaled_val1, lvl_type2, scale_fac2, scaled_val2, &
ipdstmpl48)
integer(4), intent(in) :: icatg, iparm, hrs_obs_cutoff, min_obs_cutoff, &
scale_fac1_size, scale_fac2_size, scale_fac1_wavelength, &
scale_fac2_wavelength, &
fcst_time, scale_fac1, scaled_val1, &
scale_fac2, scaled_val2
real, intent(in) :: scale_val1_size, scale_val2_size, scale_val1_wavelength, &
scale_val2_wavelength
!
character(len=*), intent(in) :: aer_type, typ_intvl_size, &
typ_intvl_wavelength, typ_gen_proc_key, &
gen_proc_or_mod_key, unit_of_time_key, lvl_type1, lvl_type2
!
integer(4), intent(inout) :: ipdstmpl48(26)
!
!local vars
integer(4) :: value, ierr
integer(4) :: bckgnd_gen_proc_id ! defined by the center
!
bckgnd_gen_proc_id=0 ! defined by the center
!
ipdstmpl48(1) = icatg
ipdstmpl48(2) = iparm
!
call get_g2_typeofaerosol(aer_type, value, ierr)
ipdstmpl48(3) = value
!
call get_g2_typeofintervals(typ_intvl_size, value, ierr)
ipdstmpl48(4) = value
ipdstmpl48(5) = scale_fac1_size
ipdstmpl48(6) = nint(scale_val1_size)
ipdstmpl48(7) = scale_fac2_size
ipdstmpl48(8) = nint(scale_val2_size)
!
call get_g2_typeofintervals(typ_intvl_wavelength, value, ierr)
ipdstmpl48(9) = value
ipdstmpl48(10) = scale_fac1_wavelength
ipdstmpl48(11) = nint(scale_val1_wavelength)
ipdstmpl48(12) = scale_fac2_wavelength
ipdstmpl48(13) = nint(scale_val2_wavelength)
!
call get_g2_typeofgenproc(typ_gen_proc_key, value, ierr)
ipdstmpl48(14) = value
!
ipdstmpl48(15) = bckgnd_gen_proc_id
!
call get_g2_on388genproc(gen_proc_or_mod_key, value, ierr)
ipdstmpl48(16) = value
!
ipdstmpl48(17) = hrs_obs_cutoff
ipdstmpl48(18) = min_obs_cutoff
!
call get_g2_unitoftimerange(unit_of_time_key, value, ierr)
ipdstmpl48(19) = value
ipdstmpl48(20) = fcst_time
!
call get_g2_fixedsurfacetypes(lvl_type1, value, ierr)
ipdstmpl48(21) = value
ipdstmpl48(22) = scale_fac1
ipdstmpl48(23) = scaled_val1
!
call get_g2_fixedsurfacetypes(lvl_type2, value, ierr)
ipdstmpl48(24) = value
!
ipdstmpl48(25) = scale_fac2
ipdstmpl48(26) = scaled_val2
!
end subroutine g2sec4_temp48
!
!
!> This subroutine returns the corresponding GRIB2 type of
!> ensemble forecast value for a given short key name based on Table 4.6
!>
!> @param[in] key - GRIB2 character short key for type of ensemble forecast
!> @param[out] value - corresponding GRIB2 type of ensemble forecast value from table 4.6
!> @param[out] ierr - error messages
!>
!> @author Boi Vuong ORG: W/SIB @date 2015-01-09
subroutine get_g2_typeofensfcst(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFENSFCST
if (trim(table4_6(n)%typeofensfcstkey).eq.trim(key)) then
value=table4_6(n)%typeofensfcstval
return
endif
enddo
print *, 'get_g2_typeofensfcst key: ', key, &
' not found in table 4.6'
ierr=9
return
end subroutine get_g2_typeofensfcst
!>
!> This subroutine returns the corresponding GRIB2 type of
!> derive forecast value for a given short key name based on Table 4.7
!>
!> @param[in] key - GRIB2 character short key for type of derive forecast
!> @param[out] value - corresponding GRIB2 type of derive forecast value from table 4.7
!> @param[out] ierr - error messages
!>
!> @author Boi Vuong ORG: W/SIB @date 2015-01-09
subroutine get_g2_typeofderivefcst(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFDERIVEFCST
if (trim(table4_7(n)%typeofderivefcstkey).eq.trim(key)) then
value=table4_7(n)%typeofderivefcstval
return
endif
enddo
print *, 'get_g2_typeofderivefcst key: ', key, &
' not found in table 4.7'
ierr=9
return
end subroutine get_g2_typeofderivefcst
!>
!> This subroutine returns the section 5 list array for a given decimal
!> scale factor (D) and type of original field values (Table 5.1) value from
!> GRIB2 - GRID Template 5.0 Grid point data - simple packing
!>
!> PROGRAM HISTORY LOG:
!> 2010-03-01 V. Krishna Kumar
!> 2012-02-21 J. Wang add binary scale factor and number of bits in argument list
!>
!> @param[in] dec_scale_fac - Decimal scale factor (E)
!> @param[in] bin_scale_fac - binary scale factor (D)
!> @param[in] tlnumbits - Number of bits used
!> @param[out] ifield5 - GRIB2 - GRID Template 5.0 listing
!> - ifield5(1): reference value(R) (IEEE 32-bit floating-point value)
!> - ifield5(2): binary scale factor (E)
!> - ifield5(3): decimal scale factor (D)
!> - ifield5(4): number of bits used for each packed value for simple packing
!> or for each group reference value for complex packing or
!> spatial differencing
!> - ifield5(5): type of original field values (See Code Table 5.1)
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2010-03-01
subroutine g2sec5_temp0(dec_scale_fac, bin_scale_fac, tlnumbits, ifield5)
integer(4), intent(in) :: bin_scale_fac, dec_scale_fac, tlnumbits
integer(4), intent(out) :: ifield5(5)
! character(len=50) :: type_of_field
integer(4) :: value, ierr
!
ifield5(1) = 0 ! Any value. Will be later overwritten
ifield5(2) = bin_scale_fac
ifield5(3) = dec_scale_fac
ifield5(4) = tlnumbits
ifield5(5) = 0 !g2 lib only 0
!
end subroutine g2sec5_temp0
!>
!> This subroutine returns the section 5 list array with a given binary,
!> and decimal scale factor from GRIB2 - GRID Template 5.2 Grid point data -
!> complex packing
!>
!> @param[in] bin_scale_fac - binary scale factor (E)
!> @param[in] dec_scale_fac - Decimal scale factor (D)
!> @param[out] ifield5 - GRIB2 - GRID Template 5.2 listing
!> - ifield5(1): reference value(R) (IEEE 32-bit floating-point value)
!> - ifield5(2): binary scale factor (E)
!> - ifield5(3): decimal scale factor (D)
!> - ifield5(4): number of bits used for each packed value for simple packing
!> or for each group reference value for complex packing or
!> spatial differencing
!>
!> @author J.Wang ORG: W/EMC @date 2012-02-20
subroutine g2sec5_temp2(dec_scale_fac, bin_scale_fac, ifield5)
!
integer(4), intent(inout) :: ifield5(16)
integer(4), intent(in) :: dec_scale_fac, bin_scale_fac
!
integer(4) :: value, ierr
!
ifield5=0
ifield5(1) = 0 ! Any value. Will be later overwritten
ifield5(2) = bin_scale_fac
ifield5(3) = dec_scale_fac
!
end subroutine g2sec5_temp2
!>
!> This subroutine returns the section 5 list array with a given binary,
!> and decimal scale factor from GRIB2 - GRID Template 5.3 Grid point data -
!> complex packing with spatial difference
!>
!> @param[in] bin_scale_fac - binary scale factor (E)
!> @param[in] dec_scale_fac - Decimal scale factor (D)
!> @param[in] order_of_sptdiff - Order of spatial difference
!> @param[out] ifield5 - GRIB2 - GRID Template 5.3 listing
!> - ifield5(1): reference value(R) (IEEE 32-bit floating-point value)
!> - ifield5(2): binary scale factor (E)
!> - ifield5(3): decimal scale factor (D)
!> - ifield5(4): number of bits used for each packed value for simple packing
!> or for each group reference value for complex packing or
!> spatial differencing
!>
!> @author J.Wang ORG: W/EMC @date 2012-02-20
subroutine g2sec5_temp3(dec_scale_fac, bin_scale_fac, order_of_sptdiff, &
ifield5)
!
integer(4), intent(in) :: dec_scale_fac, bin_scale_fac
character(*), intent(in) :: order_of_sptdiff
integer(4), intent(out) :: ifield5(18)
!
integer(4) :: value, ierr
!
ifield5=0
ifield5(1) = 0 ! Any value. Will be later overwritten
ifield5(2) = bin_scale_fac
ifield5(3) = dec_scale_fac
!
call get_g2_ordofspcdiffvals(order_of_sptdiff, value, ierr)
ifield5(17) = value
!
end subroutine g2sec5_temp3
!>
!> This subroutine returns the section 5 list array for a given decimal
!> scale factor (D), type of original field value (Table 5.40) and type of compression used
!> from GRIB2 - GRID Template 5.40 Grid point data - JPEG 2000 Code Stream Format
!>
!> PROGRAM HISTORY LOG:
!> 2010-03-01 V. Krishna Kumar
!> 2010-04-07 Jun Wang add total number of bits
!>
!> @param[in] dec_scale_fac - Decimal scale factor (D)
!> @param[in] bin_scale_fac - binary scale factor (B)
!> @param[in] tlnumbits - total number of bits
!> @param[in] type_of_compression - Type of original field values (see Code Table 5.40)
!> @param[out] ifield5 - GRIB2 - GRID Template 5.40 listing
!> - ifield5(1): reference value(R) (IEEE 32-bit floating-point value)
!> - ifield5(2): binary scale factor (E)
!> - ifield5(3): decimal scale factor (D)
!> - ifield5(4): number of bits required to hold the resulting scaled and
!> reference data values (i.e. The depth of the grayscale image.)
!> (see Note 2)
!> - ifield5(5): type of original field values (See Code Table 5.1)
!> - ifield5(6): type of compression used (See Code Table 5.40)
!> - ifield5(7): target compression ration, M:1 (with respect to the bit-depth
!> specified in octet 20), when octet 22 indicates Lossy Compression.
!> Otherwise, set to missing (see Note 3)
!>
!> @author V. Krishna Kumar ORG: W/NP12 @date 2010-03-01
subroutine g2sec5_temp40(dec_scale_fac, bin_scale_fac, tlnumbits, &
type_of_compression, ifield5)
!
integer(4), intent(in) :: bin_scale_fac, dec_scale_fac, tlnumbits
character(*), intent(in) :: type_of_compression
integer(4), intent(inout) :: ifield5(7)
!
!--- local variable
integer(4) :: value, ierr
integer, parameter :: MAX_NUMBIT=16
integer ibm
integer, allocatable :: mg(:)
!
ifield5(1) = 0 ! Any value. Will be later overwritten
ifield5(2) = bin_scale_fac
ifield5(3) = dec_scale_fac
ifield5(4) = tlnumbits
ifield5(5) = 0 !g2lib assumes original data were reals
!
! call get_g2_typeoforigfieldvals(type_of_field, value, ierr)
! ifield5(5) = value
!
call get_g2_typeofcompression(type_of_compression, value, ierr)
ifield5(6) = value
!
ifield5(7) = 255
end subroutine g2sec5_temp40
!> This subroutine returns the corresponding GRIB2 type of
!> clustering method for a given short key name based on Table 4.8
!>
!> @param[in] key - GRIB2 character short key for type of clustering method
!> @param[out] value - corresponding GRIB2 type of cluster value from table 4.8
!> @param[out] ierr - error messages
!>
!> @author Boi Vuong ORG: EMC/EIB @date 2019-07-01
subroutine get_g2_typeofcluster(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFCLUSTER
if (trim(table4_8(n)%typeofclusterkey).eq.trim(key)) then
value=table4_8(n)%typeofclusterval
return
endif
enddo
print *, 'get_g2_typeofcluster key: ', key, &
' not found in table 4.8'
ierr=9
return
end subroutine get_g2_typeofcluster
!>
!> This subroutine returns the corresponding GRIB2 type of
!> probability for a given short key name based on Table 4.9
!>
!> @param[in] key - GRIB2 character short key for type of probability
!> @param[out] value - corresponding GRIB2 type of probability value from table 4.9
!> @param[out] ierr - error messages
!>
!> @author Boi Vuong ORG: EMC/EIB @date 2019-07-01
subroutine get_g2_typeofprob(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFPROB
if (trim(table4_9(n)%typeofprobkey).eq.trim(key)) then
value=table4_9(n)%typeofprobval
return
endif
enddo
print *, 'get_g2_typeofprob key: ', key, &
' not found in table 4.9'
ierr=9
return
end subroutine get_g2_typeofprob
!> This subroutine returns the corresponding GRIB2 type of
!> precipitation for a given short key name based on Table 4.201
!>
!> @param[in] key GRIB2 character short key for type of precipitation
!> @param[out] value corresponding GRIB2 type of precipitation value from table 4.201
!> @param[out] ierr error messages
!>
!> @author Boi Vuong @date 2019-07-01
subroutine get_g2_typeofprecip(key, value, ierr)
character(len=*) :: key
integer :: value, n, ierr
!
do n=1, MAXTYPEOFPRECIP
if (trim(table4_201(n)%typeofprecipkey).eq.trim(key)) then
value=table4_201(n)%typeofprecipval
return
endif
enddo
print *, 'get_g2_typeofprecip key: ', key, &
' not found in table 4.201'
ierr=9
return
end subroutine get_g2_typeofprecip
end module grib2_all_tables_module
|
leetcode 704
左右闭区间
class Solution:
def search(self, nums: List[int], target: int) -> int:
right = len(nums)-1
left = 0
while left<=right:
mid = (right+left)//2
if nums[mid]>target:
right = mid-1
elif nums[mid]<target:
left = mid+1
else:
return mid
return -1
左闭右开
class Solution:
def search(self, nums: List[int], target: int) -> int:
right = len(nums)
left = 0
while left<right:
mid = (right+left)//2
if nums[mid]>target:
right = mid
elif nums[mid]<target:
left = mid+1
else:
return mid
return -1
首先这个left, right数值和左右闭区间不一样,其次每次取值都不一样这个要注意
leetcode 27
快慢指针,快指针查找val值,慢指针用于更新数组,注意最后return的是慢指针!
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
fast = 0
slow = 0
while fast<len(nums):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
|
import pytest
import datetime
import pandas as pd
from REPTILE.FissionFragmentSpectrum import FissionFragmentSpectrum, FissionFragmentSpectra
@pytest.fixture
def sample_spectrum_data():
# Sample data for testing
data = {
"channel": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
"counts": [100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 50, 25, 10, 5, 3, 1, 0, 0, 0]
}
return data
@pytest.fixture
def sample_spectrum_data2():
# Sample data for testing
data = {
"channel": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
"counts": [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 5, 3, 1, 1, 0, 0, 0, 0, 0]
}
return data
@pytest.fixture
def sample_spectrum_1(sample_spectrum_data):
return FissionFragmentSpectrum(start_time=datetime.datetime(2024, 5, 18, 20, 30, 15),
life_time=10,
real_time=10,
data=pd.DataFrame(sample_spectrum_data),
campaign_id="campaign",
experiment_id="experiment",
detector_id="detector",
deposit_id="deposit",
location_id="location",
measurement_id="measurement")
@pytest.fixture
def sample_spectrum_2(sample_spectrum_data2):
return FissionFragmentSpectrum(start_time=datetime.datetime(2024, 5, 18, 20, 30, 15),
life_time=10,
real_time=10,
data=pd.DataFrame(sample_spectrum_data2),
campaign_id="campaign",
experiment_id="experiment",
detector_id="detector",
deposit_id="deposit",
location_id="location",
measurement_id="measurement")
@pytest.fixture
def sample_ffsa(sample_spectrum_1, sample_spectrum_2):
data = [sample_spectrum_1, sample_spectrum_2]
return FissionFragmentSpectra(data)
def test_best(sample_ffsa, sample_spectrum_1):
assert sample_ffsa.best is sample_spectrum_1
|
import React, {useEffect, useState} from 'react';
import {useNavigate,Link, useParams} from 'react-router-dom';
import {FiArrowLeft} from 'react-icons/fi';
import api from '../../services/api';
import logoImage from '../../assets/logo.svg';
import './styles.css';
export default function NewBook(){
const [id, setId] = useState(null);
const [author, setAuthor] = useState('');
const [title, setTitle] = useState('');
const [launchDate, setLaunchDate] = useState('');
const [price, setPrice] = useState('');
const {bookId} = useParams();
const navigate = useNavigate();
const accessToken = localStorage.getItem('accessToken');
const authorization = {
headers: {
Authorization: `Bearer ${accessToken}`
}
}
useEffect(() =>{
if(bookId === '0') {
return;
} else{
loadBook();
}
}, bookId);
async function loadBook() {
try{
const response = await api.get(`api/book/v1/${bookId}`, authorization)
let ajustedDate = response.data.launchDate.split("T", 10)[0];
setId(response.data.id);
setTitle(response.data.title);
setAuthor(response.data.author);
setPrice(response.data.price);
setLaunchDate(ajustedDate);
} catch(err){
alert('Error recovering book.')
navigate('/books');
}
}
async function saveOrUpdate(e){
e.preventDefault();
const data = {
title,
author,
launchDate,
price,
}
try{
if(bookId === '0'){
await api.post('api/book/v1', data, authorization);
} else {
data.id = id;
await api.put('api/book/v1', data, authorization);
}
} catch(err){
alert('Error while recording book');
}
navigate('/books');
}
return (
<div className="new-book-container">
<div className="content">
<section className="form">
<img src={logoImage} alt="Erudio"/>
<h1>{bookId === '0'? 'Add new' : 'Update '}Book</h1>
<p>Enter the book informantion and click on {bookId === '0'? `'Add'` : `'Update '`}!</p>
<Link className="back-link" to="/books">
<FiArrowLeft size={16} color="#251FC5"/>
Back to books
</Link>
</section>
<form onSubmit={saveOrUpdate}>
<input
placeholder="Title"
value={title}
onChange={e=> setTitle(e.target.value)}
/>
<input
placeholder="Author"
value={author}
onChange={e=> setAuthor(e.target.value)}
/>
<input
type="date"
value={launchDate}
onChange={e=> setLaunchDate(e.target.value)}
/>
<input
placeholder="Price"
value={price}
onChange={e=> setPrice(e.target.value)}
/>
<button className="button" type="submit">{bookId === '0'? 'Add' : 'Update'}</button>
</form>
</div>
</div>
);
}
|
# Cell Classes
## Introduction
The primary role a cell class is to encapsulate a component of a view.
## Implementation
* Cells go into the "cells" folder of the main Rails app or of an engine.
* Cells should be named `XXXCell` in a file called `xxx_cell.rb`
* Cells should inherit from `Cell::ViewModel`.
* Cells may have a helper method that calls the cell. E.g.,:
```
def flash_box(level, text=nil, help_text=nil)
cell(:flash).(:show, self, level, text, help_text)
end
```
## Legacy notes
Some of the cells that have been ported over from `concertim-emma` are passed
the view context as an explicit argument. This is likley a hold over from a
prior implementation of Cells. It can likely be replaced with using
`#controller` in the cell.
## Further reading
The Cells documentation at
* https://github.com/trailblazer/cells
* https://github.com/trailblazer/cells-rails
* https://trailblazer.to/2.1/docs/cells.html#cells-overview
|
import axios from 'axios';
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { Button, Container, Divider, Icon, Table } from 'semantic-ui-react';
import MenuSistema from '../../MenuSistema';
export default function ListEntregador () {
const [lista, setLista] = useState([]);
useEffect(() => {
carregarLista();
}, [])
function carregarLista() {
axios.get("http://localhost:8081/api/entregador")
.then((response) => {
setLista(response.data)
})
}
function formatarData(dataParam) {
if (dataParam === null || dataParam === '' || dataParam === undefined) {
return ''
}
let arrayData = dataParam.split('-');
return arrayData[2] + '/' + arrayData[1] + '/' + arrayData[0];
}
return(
<div>
<MenuSistema tela={'entregador'} />
<div style={{marginTop: '3%'}}>
<Container textAlign='justified' >
<h2> Entregador </h2>
<Divider />
<div style={{marginTop: '4%'}}>
<Button
label='Novo'
circular
color='orange'
icon='clipboard outline'
floated='right'
as={Link}
to='/form-entregador'
/>
<br/><br/><br/>
<Table color='orange' sortable celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Nome</Table.HeaderCell>
<Table.HeaderCell>CPF</Table.HeaderCell>
<Table.HeaderCell>RG</Table.HeaderCell>
<Table.HeaderCell>DT Nascimento</Table.HeaderCell>
<Table.HeaderCell>Fone Celular</Table.HeaderCell>
<Table.HeaderCell>Fone Fixo</Table.HeaderCell>
<Table.HeaderCell textAlign='center'>Ações</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{ lista.map(entregador => (
<Table.Row key={entregador.id}>
<Table.Cell>{entregador.nome}</Table.Cell>
<Table.Cell>{entregador.cpf}</Table.Cell>
<Table.Cell>{entregador.rg}</Table.Cell>
<Table.Cell>{formatarData(entregador.dtNascimento)}</Table.Cell>
<Table.Cell>{entregador.foneCelular}</Table.Cell>
<Table.Cell>{entregador.foneFixo}</Table.Cell>
<Table.Cell textAlign='center'>
<Button
inverted
circular
color='green'
title='Clique aqui para editar os dados deste entregador'
icon>
<Icon name='edit' />
</Button>
<Button
inverted
circular
color='red'
title='Clique aqui para remover este entregador'
icon>
<Icon name='trash' />
</Button>
</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table>
</div>
</Container>
</div>
</div>
)
}
|
import factory.django
from authentication.models import User
from vacancies.models import Vacancy
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
username = factory.Faker("name") # у фабрики вызываем класс Faker, который принимает в свой конструктор лейбл
# (в нашем случае это имена вымышленных пользователей) фейк имена
password = "12345" # обязательное поле
class VacancyFactory(factory.django.DjangoModelFactory): # аргумент это фабрика
class Meta:
model = Vacancy
slug = "test" # обязательное поле
text = "test text" # обязательное поле
|
---
title: Hoe uw iOS-gebruikers hun apps downloaden
description: Manieren om Windows-apps beschikbaar te stellen voor eindgebruikers
keywords:
author: barlanmsft
ms.author: barlan
manager: angrobe
ms.date: 10/28/2016
ms.topic: article
ms.prod:
ms.service: microsoft-intune
ms.technology:
ms.assetid: 7e3135c1-df26-48c9-aa4c-cdab6168897a
ms.reviewer: jeffgilb
ms.suite: ems
ms.custom: intune-classic
ms.openlocfilehash: 0061d4ecd8d71f8b7363193e36b838741aa56a92
ms.sourcegitcommit: 34cfebfc1d8b81032f4d41869d74dda559e677e2
ms.translationtype: HT
ms.contentlocale: nl-NL
ms.lasthandoff: 07/01/2017
---
# <a name="how-your-ios-users-get-their-apps"></a>Hoe uw iOS-gebruikers hun apps downloaden
[!INCLUDE[both-portals](./includes/note-for-both-portals.md)]
Gebruik deze informatie om te begrijpen hoe en waar uw eindgebruikers de apps downloaden die u distribueert via Microsoft Intune.
**Vereiste apps**: apps die door de beheerder worden vereist en die op het apparaat worden geïnstalleerd met minimale tussenkomst van de gebruiker, afhankelijk van het platform.
**Beschikbare apps**: apps die zijn opgegeven in de lijst van de bedrijfsportal-app en die een gebruiker optioneel kan installeren.
**Beheerde apps**: apps die kunnen worden beheerd via beleid en die zijn 'verpakt' door Intune of met de Intune Mobile Application Management (MAM) Software Development Kit (SDK) zijn gebouwd. Deze apps kunnen worden beheerd door Intune en hierop kan een toepassingsbeleid worden toegepast.
**Niet-beheerde apps**: apps die niet kunnen worden beheerd via beleid en die niet zijn verpakt door Intune of waarin de Intune MAM SDK niet is opgenomen. Het toepassingsbeleid kan niet worden toegepast op deze apps.
Het wordt door Apple verboden om LOB- (Line-Of-Business) en beheerde App Store-apps in de bedrijfsportal-app te vermelden. Dit probleem wordt omzeild doordat gebruikers met tegels in de bedrijfsportal-app voor iOS op één locatie (de bedrijfsportalwebsite) naar verschillende weergaven worden verwezen voor alle apps.
Geregistreerde gebruikers krijgen hun apps door te tikken op de volgende tegels op het scherm Apps van de bedrijfsportal-app:
- **Alle apps** verwijst naar een lijst met alle apps op het tabblad ALLE van de [bedrijfsportalwebsite](https://portal.manage.microsoft.com).
- Gebruikers gaan met **Aanbevolen apps** naar het tabblad AANBEVOLEN van de bedrijfsportalwebsite.
- **Categorieën** verwijst naar het tabblad CATEGORIEËN van de bedrijfsportalwebsite.

In [Apps toevoegen voor geregistreerde apparaten](/intune-classic/deploy-use/add-apps-for-mobile-devices-in-microsoft-intune.md) leest u hoe u apps toevoegt en ze in deze tegels plaatst.
### <a name="see-also"></a>Zie tevens
[Hoe uw Android-gebruikers apps downloaden](end-user-apps-android.md)
[Hoe uw Windows-gebruikers apps downloaden](end-user-apps-windows.md)
|
//给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。
//
//
//
// 示例 1:
//
// 输入: nums = [1,2,3,4,5,6,7], k = 3
// 输出: [5,6,7,1,2,3,4]
// 解释:
// 向右轮转 1 步: [7,1,2,3,4,5,6]
// 向右轮转 2 步: [6,7,1,2,3,4,5]
// 向右轮转 3 步: [5,6,7,1,2,3,4]
// 示例 2:
//
// 输入:nums = [-1,-100,3,99], k = 2
// 输出:[3,99,-1,-100]
// 解释:
// 向右轮转 1 步: [99,-1,-100,3]
// 向右轮转 2 步: [3,99,-1,-100]
//
//
// 提示:
//
// 1 <= nums.length <= 105
// -231 <= nums[i] <= 231 - 1
// 0 <= k <= 105
fn main() {
let mut nums = vec![1, 2, 3, 4, 5, 6, 7];
let k = 3;
rotate2(&mut nums, k);
println!("{:?}", nums);
let mut nums = vec![-1, -100, 3, 99];
let k = 2;
rotate2(&mut nums, k);
println!("{:?}", nums)
}
// 关键 (i+k)%n 就是下标,这个要搞清楚。
// 只适用于k是奇数,好像不仅仅如此,这个不太对。
pub fn rotate(nums: &mut Vec<i32>, k: i32) {
let k = k as usize;
let mut idx = 0;
let mut pre_value = nums[0];
let mut tmp_value = 0;
for _ in 0..nums.len() {
idx = (idx + k) % nums.len();
tmp_value = nums[idx];
nums[idx] = pre_value;
pre_value = tmp_value;
}
}
// 想想成环 todo
pub fn rotate3(nums: &mut Vec<i32>, k: i32) {
let k = k as usize % nums.len();
if nums.len() <= 1 || k == 0 {
return;
}
let mut start_idx = 0usize;
let mut idx = start_idx;
let mut tmp = nums[idx];
for _ in 0..nums.len() {
idx = (idx + k) % nums.len();
let new_tmp = nums[idx];
nums[idx] = tmp;
tmp = new_tmp;
if idx == start_idx {
start_idx += 1;
idx = start_idx;
tmp = nums[idx];
}
}
}
pub fn rotate2(nums: &mut Vec<i32>, k: i32) {
let mut tmp = vec![0; nums.len()];
for i in 0..nums.len() {
tmp[(i + k as usize) % nums.len()] = nums[i]
}
for i in 0..nums.len() {
nums[i] = tmp[i]
}
}
|
import { fetchResourceInformation } from "./interscity.js";
export const renderDispositiveInformation = async (id) => {
window.currentResource = id;
const divInformation = document.getElementById("dispositive-information");
const { air_activated: activated, air_mode: mode, type } = await fetchResourceInformation(id);
const fragment = `<div>
<img src="assets/${matchTypeToImage(type)}-air-${
activated ? "enabled" : "disabled"
}.png" width="250px" height="250px" />
<p>Resource ID: ${id}</p>
<p> Ar Condicionado ${activated ? "Ativado" : "Desativado"}</p>
<p> Modo de operação: ${mode == "AUTOMATIC" ? "Automático 🔄" : "Manual ⚙️"}</p>
<div id="resource-buttons">
<button id="enable-air-button">Ligar Ar Condicionado</button>
<button id="disable-air-button">Desligar Ar Condicionado</button>
<button id="resource-mode-button">Mudar Modo de Operação</button>
</div>
</div>
`;
divInformation.innerHTML = fragment;
handleButtons(id);
};
const handleButtons = (id) => {
const disableAirButton = document.getElementById("disable-air-button");
const enableAirButton = document.getElementById("enable-air-button");
const resourceModeButton = document.getElementById("resource-mode-button");
disableAirButton.addEventListener("click", async () => {
await fetch(`/command`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
command: "off",
uuids: [id],
}),
});
addAwaitToButton(disableAirButton);
});
enableAirButton.addEventListener("click", async () => {
await fetch(`/command`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
command: "on",
uuids: [id],
}),
});
addAwaitToButton(enableAirButton);
});
resourceModeButton.addEventListener("click", async () => {
await fetch(`/command`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
command: "change_mode",
uuids: [id],
}),
});
addAwaitToButton(resourceModeButton);
});
const addAwaitToButton = (button) => {
button.disabled = true;
button.innerHTML = "Aguarde...";
};
};
export function matchTypeToImage(type) {
switch (type) {
case "BUS":
return "bus";
case "SUBWAY_ROOM":
return "room";
case "SUBWAY_TRAIN":
return "train";
}
}
|
import ExpenseItem from "./components/ExpenseItem";
const expenses = [
{
id: 'e1',
title: 'Toilet Paper',
amount: 94.12,
date: new Date(2020, 7, 14),
},
{ id: 'e2', title: 'New TV', amount: 799.49, date: new Date(2021, 2, 12) },
{
id: 'e3',
title: 'Car Insurance',
amount: 294.67,
date: new Date(2021, 2, 28),
},
{
id: 'e4',
title: 'New Desk (Wooden)',
amount: 450,
date: new Date(2021, 5, 12),
},
];
function App() {
return (
<div>
<h2>Let's get started!</h2>
<ExpenseItem
title = {expenses[0].title}
amount ={expenses[0].amount}
date ={expenses[0].date}
></ExpenseItem>
<ExpenseItem
title = {expenses[1].title}
amount ={expenses[1].amount}
date ={expenses[1].date}
></ExpenseItem><ExpenseItem
title = {expenses[2].title}
amount ={expenses[2].amount}
date ={expenses[2].date}
></ExpenseItem><ExpenseItem
title = {expenses[3].title}
amount ={expenses[3].amount}
date ={expenses[3].date}
></ExpenseItem>
</div>
);
}
export default App;
|
<template>
<NavigationBar></NavigationBar>
<div id="section-main" class="open">
<SideBar :is-hidden="false"></SideBar>
<div id="section-main-transparent" class="open"></div>
<div id="section-main-content">
<div class="section-board-root">
<div class="section-board-top">
<div class="section-board-title">등록 자동차 정보</div>
<div class="section-top-right">
101동 102호
</div>
</div>
<div class="section-fee-contents">
<div class="section-inout-cards" v-if="myCars.length > 0">
<InOutCard v-for="item in myCars" :key="item"
:car-num="item.id" :is-visiting="item.is_visiting" :vhcl-type="item.vhcl_type_name"></InOutCard>
</div>
<div class="card background-shadow inout-root">
<div class="section-inout-title">입출차 기록</div>
<v-table class="content-box">
<thead>
<tr>
<th width="100px">구분</th>
<th>차종</th>
<th>목적</th>
<th>날짜</th>
<th>기록시각</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in getTestLog" :key="item.name">
<td v-if="item.type" ><div class="board-item-inout-head head-red">출차</div></td>
<td v-else><div class="board-item-inout-head head-blue">입차</div></td>
<td>{{ item.carType }}</td>
<td>{{ item.purpose }}</td>
<td>{{ item.date }}</td>
<td>{{ item.time }}</td>
</tr>
</tbody>
</v-table>
</div>
</div>
</div>
</div>
<v-dialog
v-model="dialog" z-index="999999" max-width="500px">
<template v-slot:activator="{ props }">
<div class="main-floating-write-button" @click="dialog = true">
<v-icon icon="mdi-plus"></v-icon>
</div>
</template>
<div class="card dialog-root">
<div class="dialog-title">차량 추가</div>
<v-text-field
:placeholder="'12가3456'"
v-model="carIdInput" label="차량번호"></v-text-field>
<v-combobox
v-model="carPurposeInput"
label="목적"
:items="['거주', '방문']"
></v-combobox>
<v-combobox
v-model="carTypeInput"
label="차종"
:items="['소형', '중형', '대형']"
></v-combobox>
<v-btn class="vadd-secc" variant="text" @click="addCar">
추가
</v-btn>
</div>
</v-dialog>
</div>
</template>
<script>
const carpd = ['거주', '방문']
const cartd = ['소형', '중형', '대형']
import NavigationBar from "@/components/NavigationBar";
import SideBar from "@/components/sidebar/SideBar";
import InOutCard from "@/components/InOutCard.vue";
import InOutListView from "@/views/datalawa/InOutListView.vue";
import {computed, ref} from "vue";
import {useStore} from "vuex";
export default {
name: "CarInOutPage",
components: {InOutListView, InOutCard, SideBar, NavigationBar},
data: () => {
return {
selectedCarNum: '12가 3456',
dialog: false,
carIdInput: '',
carPurposeInput: '거주',
carTypeInput: '소형',
myCars: []
}
},
setup() {
const store = useStore()
return {
user: computed(() => store.state.user),
}
},
async mounted() {
this.myCars = await this.getVchlInfo()
console.log(this.myCars)
},
methods: {
async addCar() {
if (this.carIdInput.length < 7) {
alert("번호 7자 이상 입력")
return
}
if (this.user === null) {
alert('로그인 안됨')
return;
}
const idToken = await this.user.getIdToken()
const uid = await this.user.uid
let userData = null
try {
userData = await this.$axios.get(
"https://api.springnote.blog/api/v1/user/" + uid,
{
headers: {
Authorization: "Bearer " + idToken
}
}
)
} catch (e) {
alert('통신 오류0')
return;
}
console.log(userData)
if (userData.status === 200) {
const bodyData = {
id: this.carIdInput,
name: "string",
is_visiting: Boolean(carpd.indexOf(this.carPurposeInput)),
vhcl_type_id: cartd.indexOf(this.carTypeInput) + 1,
house_hold_id: userData.data.household_id,
}
console.log(bodyData)
try {
const response = await this.$axios.post(
"https://api.springnote.blog/api/v1/vhcl/", bodyData, {
headers: {
Authorization: "Bearer " + idToken
}
}
)
if (response.status === 200) {
await this.getVchlInfo()
} else {
console.error(response.data)
alert('통신 오류3')
return;
}
} catch (e) {
console.log(e)
alert('통신 오류2')
return;
}
} else {
alert('통신 오류1')
return;
}
},
async getVchlInfo() {
const idToken = await this.user.getIdToken()
const uid = await this.user.uid
let userData = null
try {
userData = await this.$axios.get(
"https://api.springnote.blog/api/v1/user/" + uid,
{
headers: {
Authorization: "Bearer " + idToken,
}
}
)
} catch (e) {
alert('통신 오류0')
return [];
}
if (userData.status === 200) {
let response = null
try {
response = await this.$axios.get(
"https://api.springnote.blog/api/v1/vhcl?houseHoldId=" + userData.data.household_id,
{
headers: {
Authorization: "Bearer " + idToken
}
}
)
} catch (e) {
alert('통신 오류3')
return;
}
if (response.status === 200) {
return response.data
} else {
alert('통신 오류2')
return [];
}
} else {
alert('통신 오류1')
return [];
}
return [];
}
},
computed: {
getTestLog() {
let articleDatas = []
let writeTime = new Date();
for (let i = 0;i < 20;i++) {
const author = Math.random().toString(36).substring(2, 12)
writeTime = new Date(writeTime - ((Math.random(24 * 60) + 720) * 60000))
articleDatas.push({
type: Math.random() > 0.5,
carType: '경차',
purpose: '방문',
date: writeTime.toISOString().substring(0, 10),
time: writeTime.toISOString().substring(11, 19)
})
}
return articleDatas
}
}
}
</script>
<style>
@import "../css/view-main.css";
@import "../css/inout-main.css";
</style>
<style scoped>
.vadd-secc {
float: right;
color: var(--point-color2);
}
.section-fee-contents {
flex-direction: column !important;
}
.inout-root {
padding: 20px;
width: 100%;
display: flex;
flex-direction: column;
gap: 20px;
}
td {
text-align: center;
}
.board-item-inout-head {
text-align: center;
color: #FFFFFF;
border-radius: 5px;
}
.content-box-root {
display: flex;
flex-direction: row;
background: #FFFFFF;
padding: 18px;
flex-shrink: 0;
flex-grow: 0;
width: 220px;
gap: 18px;
}
.content-box{
display: flex;
flex-direction: column;
gap: 18px;
flex: 1;
}
.car-number {
width: 100%;
/*text-align: center;*/
font-weight: 800;
font-size: 20px;
}
.car-inout-time-root {
display: flex;
flex-direction: column;
}
.car-inout-time-time {
font-weight: 600;
}
.car-inout-time-text {
font-size: 14px;
}
.content-box-buttons {
position: relative;
}
.content-box-buttons-button {
position: relative;
top: 50%;
transform: translateY(-50%);
}
.dialog-root {
padding: 28px;
/*display: flex;*/
/*flex-direction: column;*/
/*gap: 18px;*/
/*max-width: 800px;*/
}
.dialog-title {
width: 100%;
font-style: normal;
font-weight: 700;
font-size: 18px;
line-height: 22px;
display: flex;
align-items: center;
color: var(--secondary-text-color);
margin-bottom: 20px;
}
.dialog-summary {
display: flex;
flex-direction: row;
text-align: center;
}
.dialog-summary-title {
flex: 1;
font-weight: 600;
}
.dialog-summary-sub {
flex: 3;
}
.dialog-root > hr {
border: 0;
height: 1px;
background: rgba(44, 44, 44, 0.22);
margin-bottom: 6px;
margin-top: 6px;
}
</style>
|
import React, { useState, useEffect } from "react";
import api from "./services/api";
import "./styles.css";
function App() {
const [repositories, setRepositories] = useState([]);
useEffect(() => {
api.get("repositories").then((response) => {
setRepositories(response.data);
});
}, []);
async function handleAddRepository() {
const response = await api.post("repositories", {
title: `Rep-${new Date().getTime()}`,
url: `URL-${new Date().getTime()}`,
techs: ["Java", "Node", "GO"],
});
setRepositories([...repositories, response.data]);
}
async function handleRemoveRepository(id) {
await api.delete(`repositories/${id}`);
repositories.splice(
repositories.findIndex((rep) => rep.id === id),
1
);
setRepositories([...repositories]);
}
return (
<div>
<ul data-testid="repository-list">
{repositories.map((repository) => (
<li key={repository.id}>
{repository.title}
<button onClick={() => handleRemoveRepository(repository.id)}>
Remover
</button>
</li>
))}
</ul>
<button onClick={() => handleAddRepository()}>Adicionar</button>
</div>
);
}
export default App;
|
"""
Defines initialized type-casts objects. Use it in Argument type definition
"""
from . import _casts
__all__ = ['Cast', 'ListCast', 'DictCast']
class Cast:
"""Initialized ArgTypeCast casts
:ivar StrCast: Cast to the ``str`` type
:ivar StrCast: Cast to the ``int`` type
:ivar StrCast: Cast to the ``float`` type
:ivar StrCast: Cast to the ``bool`` type (have type of :class:`_casts.BoolCast`)
"""
StrCast = _casts.ArgTypeCast(str)
IntCast = _casts.ArgTypeCast(int)
FloatCast = _casts.ArgTypeCast(float)
BoolCast = _casts.BoolCast()
@staticmethod
def setup_bool_cast_translations(true_list: list[str], false_list: list[str]):
"""Set up the BoolCast type-cast translations
:param true_list: List with the true string variants
:param false_list: List with the false string variants
"""
Cast.BoolCast = _casts.BoolCast(true_list, false_list)
class ListCast:
"""Initialized ListCast casts.
Usage example: ez example value1, value2, value3, ...
:ivar ListStrCast: Cast to the ``list[str]`` type
:ivar ListIntCast: Cast to the ``list[int]`` type
:ivar ListFloatCast: Cast to the ``list[float]`` type
:ivar ListBoolCast: Cast to the ``list[bool]`` type
"""
ListStrCast = _casts.ListCast()
ListIntCast = _casts.ListCast(values_type=Cast.IntCast)
ListFloatCast = _casts.ListCast(values_type=Cast.FloatCast)
ListBoolCast = _casts.ListCast(values_type=Cast.BoolCast)
class DictCast:
"""Initialized DictCast casts.
Usage example: ez example key1=value2, key2=value2, ...
:ivar DictStrStrCast: Cast to the ``dict[str, str]`` type
:ivar DictStrIntCast: Cast to the ``dict[str, int]`` type
:ivar DictStrFloatCast: Cast to the ``dict[str, float]`` type
:ivar DictStrBoolCast: Cast to the ``dict[str, bool]`` type
:ivar DictIntStrCast: Cast to the ``dict[int, str]`` type
:ivar DictIntIntCast: Cast to the ``dict[int, int]`` type
:ivar DictIntFloatCast: Cast to the ``dict[int, float]`` type
:ivar DictIntBoolCast: Cast to the ``dict[int, bool]`` type
"""
DictStrStrCast = _casts.DictCast()
DictStrIntCast = _casts.DictCast(values_type=Cast.IntCast)
DictStrFloatCast = _casts.DictCast(values_type=Cast.FloatCast)
DictStrBoolCast = _casts.DictCast(values_type=Cast.BoolCast)
DictIntStrCast = _casts.DictCast(key_type=Cast.IntCast)
DictIntIntCast = _casts.DictCast(key_type=Cast.IntCast, values_type=Cast.IntCast)
DictIntFloatCast = _casts.DictCast(key_type=Cast.IntCast, values_type=Cast.FloatCast)
DictIntBoolCast = _casts.DictCast(key_type=Cast.IntCast, values_type=Cast.BoolCast)
|
import {NestFactory} from "@nestjs/core";
import {AppModule} from "./app.module";
import {DocumentBuilder, SwaggerModule} from "@nestjs/swagger";
async function start (){
const PORT = process.env.PORT || 5000;
const app = await NestFactory.create(AppModule) // создаем экземпляр приложения и указываем главный модуль в которов настраиваем весь проект
const config = new DocumentBuilder() // позволяет задавать для обьекта параметры
.setTitle("Урок по продвинутому бекэнду")
.setDescription("Документация REST API")
.setVersion("1.0.0")
.addTag("Aibek Koikelov")
.build()
const document = SwaggerModule.createDocument(app,config) // далее создаем документ свагера и в параметрах передаем наше приложение и конфиг переменную
SwaggerModule.setup("/api/docs", app, document) // настраиваем передавая путь по которому могут зайти в докуентацию наш проект и документ
await app.listen(PORT, () => {
console.log(`Server running on porter ${PORT}`)
})
}
start()
|
angular.module('app', [
'ngRoute',
'ngResource',
'search.controller',
'search.service',
'show.controller',
'show.service'
])
.filter('trustHTML', function ($sce) { // $sce service
return function (html) {
return $sce.trustAsHtml(html);
};
})
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/search.html',
controller: 'SearchController'
})
.when('/show/:id', {
templateUrl: 'views/show.html',
controller: 'ShowController',
resolve: {
show:function ($route, ShowService) {
return ShowService.get({ id: $route.current.params.id });
}
}
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);
|
import React, { useEffect, useMemo, useState } from "react";
import "./Register.css";
import axios from "axios";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import { Select } from "antd";
import countryList from "react-select-country-list";
const Register = () => {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [email, setEmail] = useState("");
const [role, setRole] = useState("");
const [cities, setCities] = useState([]);
const [city, setCity] = useState("");
const [phone, setPhone] = useState("");
const [password, setPassword] = useState("");
const [answer, setAnswer] = useState("");
const [providedService, setProvidedService] = useState("");
const [nationality, setNationality] = useState("");
const [photo, setPhoto] = useState("");
//location object
const location = useLocation();
//extract countries
const options = useMemo(() => countryList().getData(), []);
const navigate = useNavigate();
// form submit function
//get cities
const getCities = async () => {
try {
const res = await axios.get("http://localhost:8080/api/v1/cities/get");
console.warn(res);
if (res?.data?.success) {
setCities(res.data.cities);
console.warn(cities);
}
} catch (error) {
console.warn(error);
}
};
const handleSubmitExplorer = async (e) => {
e.preventDefault();
const explorerData = new FormData();
explorerData.append("firstName", firstName);
explorerData.append("lastName", lastName);
explorerData.append("email", email);
explorerData.append("password", password);
explorerData.append("phone", phone);
photo && explorerData.append("photo", photo);
explorerData.append("answer", answer);
explorerData.append("nationality", nationality);
try {
const res = await axios.post(
"http://localhost:8080/api/v1/auth/register",
explorerData
);
if (res && res.data.success) {
toast.success(res?.data?.message);
navigate("/login");
} else {
toast.error(res.data.message);
}
} catch (error) {
console.warn(error);
}
};
//handleSubmitSeller
const handleSubmitSeller = async (e) => {
e.preventDefault();
const sellerData = new FormData();
sellerData.append("firstName", firstName);
sellerData.append("lastName", lastName);
sellerData.append("email", email);
sellerData.append("password", password);
sellerData.append("phone", phone);
photo && sellerData.append("photo", photo);
sellerData.append("answer", answer);
sellerData.append("providedService", providedService);
sellerData.append("city", city);
try {
const res = await axios.post(
"http://localhost:8080/api/v1/seller/become-seller",
sellerData
);
if (res && res.data.success) {
toast.success(res?.data?.message);
navigate("/");
} else {
toast.error(res.data.message);
}
} catch (error) {
console.warn(error);
}
};
useEffect(() => {
if (location.state && location.state.role) {
setRole(location.state.role);
getCities();
}
}, [location.state]);
return (
<>
<div className="container-fluid " style={{ minHeight: "170vh" }}>
<div className="row">
<div
className="col-6 w-50 sign_up__image"
style={{ minHeight: "170vh" }}
></div>
<div
className="col-6 d-flex justify-content-center align-items-center"
style={{ minHeight: "170vh" }}
>
{role === "Seller" ? (
<div className="d-flex flex-column w-50">
<div className="h3 my-1">Sign Up With Saudi Smart ID</div>
<p className="my-1 lh-3 fw-400 ">
Enjoy Saudi Smart ID,your single account to access all Visit
Saudi offerings
</p>
<div className="d-flex flex-column mt-3">
<label className="form-label">
First Name <span className="text-danger">*</span>
</label>
<input
className="form-control my-1"
type="text"
placeholder="eg.John"
value={firstName}
onChange={(e) => {
setFirstName(e.target.value);
}}
/>
<label className="form-label">
Last Name <span className="text-danger">*</span>
</label>
<input
className="form-control my-1"
type="text"
placeholder="eg.John"
value={lastName}
onChange={(e) => {
setLastName(e.target.value);
}}
/>
<label className="form-label">
Email Address <span className="text-danger">*</span>
</label>
<input
className="form-control my-1"
type="email"
placeholder="eg.abc@gmail.com"
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
/>
<label className="form-label">
Phone <span className="text-danger">*</span>
</label>
<input
className="form-control my-1"
type="tel"
placeholder="eg.03416557034"
value={phone}
onChange={(e) => {
setPhone(e.target.value);
}}
/>
<label className="form-label">
City <span className="text-danger">*</span>
</label>
<Select
className="w-50"
placeholder="Select a city"
size="large"
showSearch
onChange={(value) => setCity(value)}
>
{cities?.map((c) => {
return (
<Option key={c._id} value={c._id}>
{c.cityName}
</Option>
);
})}
</Select>
<label className="form-label">
Answer <span className="text-danger">*</span>
</label>
<input
className="form-control my-1"
type="text"
placeholder="What is your favourite sport"
value={answer}
onChange={(e) => {
setAnswer(e.target.value);
}}
/>
<label className="form-label">
Password <span className="text-danger">*</span>
</label>
<input
className="form-control my-1"
type="password"
placeholder="eg.Choose your own password"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
/>
<Select
className="my-2"
placeholder="Select provided service"
size="large"
showSearch
onChange={(value) => setProvidedService(value)}
>
<Select.Option value="Driver">Driver</Select.Option>
<Select.Option value="Guider">Guider</Select.Option>
<Select.Option value="Translator">Translator</Select.Option>
</Select>
<div className="my-3">
<label className="form-label ">
{photo ? photo.name : "Upload Photo"}
<input
className="form-control my-2 "
type="file"
accept="image/*"
onChange={(e) => setPhoto(e.target.files[0])}
/>
</label>
</div>
<div className="my-3 text-center">
{photo && (
<div>
<img
src={URL.createObjectURL(photo)}
alt="attraction photo"
height={"200px"}
className="w-50 rounded-circle"
/>
</div>
)}
</div>
<button
className="btn text-light mt-2"
style={{ background: "#1dbf73" }}
onClick={handleSubmitSeller}
>
Sign up
</button>
</div>
<Link to="/login" className="text-primary mx-auto mt-2">
Or Sign in instead
</Link>
</div>
) : (
<div className="d-flex flex-column w-50">
<div className="h3 my-1">Sign Up With Saudi Smart ID</div>
<p className="my-1 lh-3 fw-400 ">
Enjoy Saudi Smart ID,your single account to access all Visit
Saudi offerings
</p>
<div className="d-flex flex-column mt-3 ">
<label className="form-label">
First Name <span className="text-danger">*</span>
</label>
<input
className="form-control my-1"
type="text"
placeholder="eg.John"
value={firstName}
onChange={(e) => {
setFirstName(e.target.value);
}}
/>
<label className="form-label">
Last Name <span className="text-danger">*</span>
</label>
<input
className="form-control my-1"
type="text"
placeholder="eg.John"
value={lastName}
onChange={(e) => {
setLastName(e.target.value);
}}
/>
<label className="form-label">
Email Address <span className="text-danger">*</span>
</label>
<input
className="form-control my-1"
type="email"
placeholder="eg.abc@gmail.com"
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
/>
<label className="form-label">
Phone <span className="text-danger">*</span>
</label>
<input
className="form-control my-1"
type="tel"
placeholder="eg.03416557034"
value={phone}
onChange={(e) => {
setPhone(e.target.value);
}}
/>
<label className="form-label">
Answer <span className="text-danger">*</span>
</label>
<input
className="form-control my-1"
type="text"
placeholder="What is your favourite sport"
value={answer}
onChange={(e) => {
setAnswer(e.target.value);
}}
/>
<label className="form-label">
Password <span className="text-danger">*</span>
</label>
<input
className="form-control my-1"
type="password"
placeholder="eg.Choose your own password"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
/>
<Select
className="my-2"
placeholder="Select Country "
size="large"
showSearch
onChange={(value) => setNationality(value)}
>
{options?.map((o) => (
<Select.Option key={o.value} value={o.label}>
{options?.label}
</Select.Option>
))}
</Select>
<div className="my-3">
<label className="form-label ">
{photo ? photo.name : "Upload Photo"}
<input
className="form-control my-2 "
type="file"
accept="image/*"
onChange={(e) => setPhoto(e.target.files[0])}
/>
</label>
</div>
<div className="my-3 text-center">
{photo && (
<div>
<img
src={URL.createObjectURL(photo)}
alt="attraction photo"
height={"200px"}
className="w-50 rounded-circle"
/>
</div>
)}
</div>
<button
className="btn text-light mt-2"
style={{ background: "#1dbf73" }}
onClick={handleSubmitExplorer}
>
Sign up
</button>
</div>
<Link
to="/login"
className="text-primary mx-auto mt-2 text-decoration-none"
>
or Sign in instead
</Link>
</div>
)}
</div>
</div>
</div>
</>
);
};
export default Register;
|
import { useQuery, gql } from "@apollo/client";
import styled from "@emotion/styled";
const FETCH_BOARDS = gql`
query fetchBoards {
fetchBoards {
_id
writer
title
contents
}
}
`;
const MyRow = styled.div`
display: flex;
flex-direction: row;
`;
const MyColumn = styled.div`
width: 25%;
`;
export default function BasketPage() {
const { data } = useQuery(FETCH_BOARDS);
console.log(data);
const onClickBasket = (el: any) => () => {
console.log(el);
const baskets = JSON.parse(localStorage.getItem("baskets") || "[]");
const temp = baskets.filter((basketEl) => basketEl._id === el._id);
if (temp.length === 1) {
alert("이미 담으신 물품입니다!");
return;
}
const { __typename, ...newEl } = el;
baskets.push(newEl);
localStorage.setItem("baskets", JSON.stringify(baskets));
};
return (
<div>
{data?.fetchBoards.map((el: any) => (
<MyRow key={el._id}>
<MyColumn>{el.writer}</MyColumn>
<MyColumn>{el.title}</MyColumn>
<button onClick={onClickBasket(el)}>장바구니 담기</button>
</MyRow>
))}
</div>
);
}
|
-- import lspconfig plugin safely
local lspconfig_status, lspconfig = pcall(require, "lspconfig")
if not lspconfig_status then
return
end
-- import cmp-nvim-lsp plugin safely
local cmp_nvim_lsp_status, cmp_nvim_lsp = pcall(require, "cmp_nvim_lsp")
if not cmp_nvim_lsp_status then
return
end
-- import typescript plugin safely
local typescript_setup, typescript = pcall(require, "typescript")
if not typescript_setup then
return
end
local keymap = vim.keymap -- for concision
-- enable keybinds only for when lsp server available
local on_attach = function(client, bufnr)
-- keybind options
local opts = { noremap = true, silent = true, buffer = bufnr }
-- set keybinds
keymap.set("n", "gf", "<cmd>Lspsaga lsp_finder<CR>", opts) -- show definition, references
--keymap.set("n", "gD", "<Cmd>lua vim.lsp.buf.declaration()<CR>", opts) -- got to declaration
keymap.set("n", "gD", "<Cmd>lua vim.lsp.buf.definition()<CR>", opts) -- got to declaration
keymap.set("n", "gd", "<cmd>Lspsaga peek_definition<CR>", opts) -- see definition and make edits in window
keymap.set("n", "gi", "<cmd>lua vim.lsp.buf.implementation()<CR>", opts) -- go to implementation
keymap.set("n", "<leader>ca", "<cmd>Lspsaga code_action<CR>", opts) -- see available code actions
keymap.set("n", "<leader>rn", "<cmd>Lspsaga rename<CR>", opts) -- smart rename
keymap.set("n", "<leader>D", "<cmd>Lspsaga show_line_diagnostics<CR>", opts) -- show diagnostics for line
keymap.set("n", "<leader>d", "<cmd>Lspsaga show_cursor_diagnostics<CR>", opts) -- show diagnostics for cursor
keymap.set("n", "[d", "<cmd>Lspsaga diagnostic_jump_prev<CR>", opts) -- jump to previous diagnostic in buffer
keymap.set("n", "]d", "<cmd>Lspsaga diagnostic_jump_next<CR>", opts) -- jump to next diagnostic in buffer
keymap.set("n", "K", "<cmd>Lspsaga hover_doc<CR>", opts) -- show documentation for what is under cursor
keymap.set("n", "<leader>o", "<cmd>LSoutlineToggle<CR>", opts) -- see outline on right hand side
-- typescript specific keymaps (e.g. rename file and update imports)
if client.name == "tsserver" then
keymap.set("n", "<leader>rf", ":TypescriptRenameFile<CR>") -- rename file and update imports
keymap.set("n", "<leader>oi", ":TypescriptOrganizeImports<CR>") -- organize imports (not in youtube nvim video)
keymap.set("n", "<leader>ru", ":TypescriptRemoveUnused<CR>") -- remove unused variables (not in youtube nvim video)
end
end
-- used to enable autocompletion (assign to every lsp server config)
local capabilities = cmp_nvim_lsp.default_capabilities()
-- Change the Diagnostic symbols in the sign column (gutter)
-- (not in youtube nvim video)
local signs = { Error = " ", Warn = " ", Hint = "ﴞ ", Info = " " }
for type, icon in pairs(signs) do
local hl = "DiagnosticSign" .. type
vim.fn.sign_define(hl, { text = icon, texthl = hl, numhl = "" })
end
-- configure html server
lspconfig["html"].setup({
capabilities = capabilities,
on_attach = on_attach,
})
-- configure typescript server with plugin
typescript.setup({
server = {
capabilities = capabilities,
on_attach = on_attach,
filetypes = { "ts", "tsx" },
},
})
lspconfig["tsserver"].setup({
capabilities = capabilities,
on_attach = on_attach,
filetypes = { "ts", "tsx" },
})
-- configure css server
lspconfig["cssls"].setup({
capabilities = capabilities,
on_attach = on_attach,
})
-- configure tailwindcss server
lspconfig["tailwindcss"].setup({
capabilities = capabilities,
on_attach = on_attach,
})
-- configure emmet language server
lspconfig["emmet_ls"].setup({
capabilities = capabilities,
on_attach = on_attach,
filetypes = { "html", "typescriptreact", "javascriptreact", "css", "sass", "scss", "less", "svelte" },
})
-- lspconfig["pyright"].setup({
-- capabilities = capabilities,
-- on_attach = on_attach,
-- filetypes = { "python", "py" },
-- })
lspconfig["pyright"].setup({
capabilities = capabilities,
on_attach = on_attach,
filetypes = { "python", "py" },
settings = {
pyright = {
organizeimports = {
provider = "isort",
},
disableDiagnostics = true,
inlayHints = {
variableTypes = false,
},
},
python = {
analysis = {
extraPaths = {
"./lib/audit-logs",
"./lib/authenticator",
"./lib/billing",
"./lib/datalayer-v2",
"./lib/dd-db",
"./lib/dd-internal-authentication",
"./lib/dd-resilience",
"./lib/dd-util",
"./lib/dd-util-consul",
"./lib/dogpound",
"./lib/dogweb-model",
"./lib/dogweb-lib",
"./lib/integration-base",
"./lib/json-api-common",
"./lib/pylint-dogweb",
"./lib/redis-v2",
"./lib/ddgrpc",
"./dd/pb",
"./lib/dd-util-context",
},
},
linting = {
enabled = true,
pylintEnabled = true,
},
},
},
})
lspconfig["gopls"].setup({
capabilities = capabilities,
on_attach = on_attach,
filetypes = { "go" },
})
lspconfig["rust_analyzer"].setup({
capabilities = capabilities,
on_attach = on_attach,
filetypes = { "rs" },
})
-- configure lua server (with special settings)
lspconfig["lua_language_server"].setup({
capabilities = capabilities,
on_attach = on_attach,
settings = { -- custom settings for lua
Lua = {
-- make the language server recognize "vim" global
diagnostics = {
globals = { "vim" },
},
workspace = {
-- make language server aware of runtime files
library = {
[vim.fn.expand("$VIMRUNTIME/lua")] = true,
[vim.fn.stdpath("config") .. "/lua"] = true,
},
},
},
},
})
|
import { useRouter } from 'next/router';
import { MongoClient, ObjectId } from 'mongodb';
import Head from 'next/head';
import MeetupDetail from '../../components/meetups/MeetupDetail';
import { Fragment } from 'react';
const MeetupDetailPage = (props) => {
const router = useRouter();
return (
<Fragment>
<Head>
<title>{props.meetupData.title}</title>
</Head>
<MeetupDetail
image={props.meetupData.image}
description={props.meetupData.description}
address={props.meetupData.address}
title={props.meetupData.title}
/>
</Fragment>
);
};
export const getStaticPaths = async () => {
const client = await MongoClient.connect(
'mongodb+srv://huutai1612:Kieutrang0711@cluster0.rdo2f.mongodb.net/myFirstDatabase?retryWrites=true&w=majority',
);
const db = client.db();
const meetupsCollection = db.collection('meetups');
const meetupIdList = await meetupsCollection.find({}, { _id: 1 }).toArray();
client.close();
return {
paths: meetupIdList.map((meetup) => ({
params: { meetupId: meetup._id.toString() },
})),
fallback: false,
};
};
export const getStaticProps = async (context) => {
const meetupId = context.params.meetupId;
const client = await MongoClient.connect(
'mongodb+srv://huutai1612:Kieutrang0711@cluster0.rdo2f.mongodb.net/myFirstDatabase?retryWrites=true&w=majority',
);
const db = client.db();
const meetupsCollection = db.collection('meetups');
const meetupDetail = await meetupsCollection.findOne({
_id: ObjectId(meetupId),
});
return {
revalidate: 1,
props: {
meetupData: {
id: meetupDetail._id.toString(),
title: meetupDetail.title,
address: meetupDetail.address,
description: meetupDetail.description,
image: meetupDetail.image,
},
},
};
};
export default MeetupDetailPage;
|
package day14.SingletonTest;
import com.sun.org.apache.xpath.internal.operations.Or;
public class SingletonTest2 {
public static void main(String[] args) {
Order order1 = Order.getInstance();
Order order2 = Order.getInstance();
System.out.println(order1==order2);
}
}
//懒汉式,区别在于是否初始化
class Order{
// 私有化类的构造器
private Order(){
}
//申明类的对象,没有初始化
//此对象也必须申明为static
private static Order instance = null;
//声明public、static返回当前类对象的方法;
public static Order getInstance(){
if(instance ==null){
instance = new Order();
}
return instance;
}
}
|
// store.js
import { createStore } from "vuex";
export default createStore({
state: {
users: [],
search: "",
currentPage: 1,
itemsPerPage: 5,
},
mutations: {
setUsers(state, users) {
state.users = users;
},
setSearch(state, search) {
state.search = search;
},
setCurrentPage(state, page) {
state.currentPage = page;
},
},
getters: {
filteredUsers: (state) => {
return state.users.filter((user) =>
Object.values(user).some(
(value) =>
typeof value === "string" &&
value.toLowerCase().includes(state.search.toLowerCase())
)
);
},
totalPages: (state, getters) => {
return Math.ceil(getters.filteredUsers.length / state.itemsPerPage);
},
displayedUsers: (state, getters) => {
const startIndex = (state.currentPage - 1) * state.itemsPerPage;
const endIndex = startIndex + state.itemsPerPage;
/* returning users directly from filteredUsers getters,
and creating shallow copy of an array */
return getters.filteredUsers.slice(startIndex, endIndex);
},
},
actions: {
async fetchUsers({ commit }) {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
const users = await response.json();
commit("setUsers", users);
commit("setCurrentPage", 1); // reset to the first page after fetching
} catch (error) {
console.error("Error fetching users:", error);
}
},
},
});
|
//region Imports
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:onboarding_module/screens/sign_in.dart';
import 'package:onboarding_module/theme_provider/theme_provider_ld.dart';
import 'package:onboarding_module/util/app_colors.dart';
import 'package:onboarding_module/util/global_methods_and_variables.dart';
import 'package:onboarding_module/util/my_text_styles.dart';
//endregion
class Settings extends StatefulWidget {
const Settings({super.key});
@override
State<StatefulWidget> createState() => SettingsState();
}
class SettingsState extends State<Settings> {
//region CreateMaterialPropertyForThumbIcon
//Switch button code
final MaterialStateProperty<Icon?> thumbIcon =
MaterialStateProperty.resolveWith<Icon?>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return const Icon(
Icons.nightlight,
color: Colors.blue,
);
}
return const Icon(Icons.sunny, color: Colors.yellow);
},
);
//endregion
//region BuildMethod
@override
Widget build(BuildContext context) {
bool isDark = context.watch<ThemeProvider>().isDark;
getThemeColorAccordingLitDrk(context, isDark);
return SafeArea(
bottom: false,
child: Scaffold(
backgroundColor: ColorConstant.bgColor,
//region SetFrames
body: Padding(
padding: const EdgeInsets.all(11.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Settings",
style: mTextStyle25(
mWeight: FontWeight.bold,
mFontColor: ColorConstant.textOnBGColor),
),
const Divider(),
Row(
children: [
Switch(
thumbIcon: thumbIcon,
value: isDark,
onChanged: (value) {
isDark = value;
context.read<ThemeProvider>().setThemeValue(value);
}),
Text(
isDark == true ? "Dark Theme" : "Light Theme",
style: mTextStyle12(
mWeight: FontWeight.bold,
mFontColor: ColorConstant.textOnBGColor),
),
],
),
const Divider(),
Row(
children: [
IconButton(
onPressed: () {
// addIsLoggedInUserSF(isLoggedIn);
//login page me move karna h
bool isLoggedIn = false;
int uid = 0;
String email = "";
setUserDataInSP(isLoggedIn, uid,email);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => const SignInScreen()));
},
icon: const Icon(Icons.logout)),
InkWell(
onTap: () {
//addIsLoggedInUserSF(isLoggedIn);
//login page me move karna h
bool isLoggedIn = false;
int uid = 0;
String email = "";
setUserDataInSP(isLoggedIn, uid, email);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => const SignInScreen()));
},
child: Text(
"Sign Out",
style: mTextStyle12(
mWeight: FontWeight.bold,
mFontColor: ColorConstant.textOnBGColor),
),
),
],
),
const Divider(),
],
),
),
//endregion
),
);
}
//endregion
}
|
import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {MatPaginator} from "@angular/material/paginator";
import {MatTableDataSource} from "@angular/material/table";
import {Router} from "@angular/router";
import {MatDialog, MatDialogConfig} from "@angular/material/dialog";
import {MatSort, Sort} from "@angular/material/sort";
import {Teacher} from "../../models/teacher";
import {TeacherService} from "../../services/teacher.service";
import {TeacherAddComponent} from "../teacher-add/teacher-add.component";
import {TeacherDetailComponent} from "../teacher-detail/teacher-detail.component";
import {TeacherDeleteComponent} from "../teacher-delete/teacher-delete.component";
import {Subject, takeUntil} from "rxjs";
function compare(a: number | string, b: number | string, isAsc: boolean) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
@Component({
selector: 'app-teacher-list',
templateUrl: './teacher-list.component.html',
styleUrls: ['./teacher-list.component.scss']
})
export class TeacherListComponent implements OnInit, OnDestroy {
destroy$: Subject<boolean> = new Subject<boolean>();
@ViewChild(MatPaginator, {static: true}) paginator!: MatPaginator;
dataSourceTeachers: any;
isLoaded: boolean = true;
teachers: Teacher[] = []
displayedColumns: string[] = ['id', 'firstName', 'lastName', 'contact', 'EDIT', 'DELETE']
constructor(private service: TeacherService,
private router: Router,
private dialog: MatDialog) {
}
@ViewChild(MatSort, {static: true}) sort!: MatSort;
private loadTeachers() {
this.isLoaded = true;
this.service.getTeachers().pipe(takeUntil(this.destroy$)).subscribe({
next:(data => {
this.teachers = data;
this.teachers.sort(function (obj1, obj2) {
// Descending: first id less than the previous
return obj2.id - obj1.id;
});
this.isLoaded = false;
this.dataSourceTeachers = new MatTableDataSource(this.teachers);
this.dataSourceTeachers.sort = this.sort;
this.dataSourceTeachers.paginator = this.paginator;
}),
error : err => {
alert(`Error ${err}!`);
this.isLoaded = false;
}
});
}
onCreate(){
this.service.initializeFormGroup()
const dialogConfig = new MatDialogConfig()
dialogConfig.disableClose = true
dialogConfig.autoFocus = true
dialogConfig.width= "30%"
const dialogRef = this.dialog.open(TeacherAddComponent, dialogConfig)
dialogRef.afterClosed().pipe(takeUntil(this.destroy$)).subscribe(result=>{
this.loadTeachers()
})
}
onEdit(id: number, firstName: string, lastName: string, contact: string){
const dialogConfig = new MatDialogConfig()
dialogConfig.disableClose = true
dialogConfig.autoFocus = true
dialogConfig.width = "30%"
const dialogRef = this.dialog.open(TeacherDetailComponent, {
data: {id: id, firstName: firstName, lastName: lastName, contact: contact}
})
dialogRef.afterClosed().pipe(takeUntil(this.destroy$)).subscribe(result =>{
this.loadTeachers()
})
}
ngOnInit(): void {
this.loadTeachers()
}
ngOnDestroy(): void {
this.destroy$.next(true);
this.destroy$.unsubscribe();
}
getTeachers(): void {
this.service.getTeachers().pipe(takeUntil(this.destroy$)).subscribe(teachers => this.teachers = teachers)
}
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSourceTeachers.filter = filterValue.trim().toLowerCase();
}
sortData(sort: Sort) {
const data = this.teachers.slice();
if (!sort.active || sort.direction === '') {
this.teachers = data;
return;
}
this.teachers = data.sort((a, b) => {
const isAsc = sort.direction === 'asc';
switch (sort.active) {
case 'id':
return compare(a.id, b.id, isAsc);
case 'firstName':
return compare(a.firstName, b.firstName, isAsc);
case 'lastName':
return compare(a.lastName, b.lastName, isAsc);
default:
return 0;
}
});
}
onDelete(id: number) {
console.log(id)
const dialogRef = this.dialog.open(TeacherDeleteComponent, {
data: {id: id},
width: '250px'
})
dialogRef.afterClosed().pipe(takeUntil(this.destroy$)).subscribe(result => {
if(result!= 0)
this.loadTeachers()
});
}
}
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import '../../../../../core/app_color/app_color.dart';
import '../../../../../core/shared_widget/custom_text_field.dart';
import 'first_and_last_name.dart';
// ignore: must_be_immutable
class StepRegister extends StatefulWidget {
final TextEditingController firstNameController;
final TextEditingController lastNameController;
final TextEditingController emailController;
final TextEditingController passwordController;
final TextEditingController confirmPassword;
PageController pageController;
int userTyp;
StepRegister({
Key? key,
required this.firstNameController,
required this.lastNameController,
required this.emailController,
required this.passwordController,
required this.confirmPassword,
required this.pageController,
required this.userTyp,
}) : super(key: key);
@override
State<StepRegister> createState() => _StepRegisterState();
}
class _StepRegisterState extends State<StepRegister> {
final formKey = GlobalKey<FormState>(debugLabel: 'sadsad');
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: Form(
key: formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FirstAndLastName(
firstNameController: widget.firstNameController,
lastNameController: widget.lastNameController,
),
const SizedBox(height: 10),
const Text('Email Address'),
const SizedBox(height: 10),
CustomTextField(
controller: widget.emailController,
hintText: 'Enter Your email',
),
const SizedBox(height: 10),
const Text('Password'),
const SizedBox(height: 10),
CustomTextField(
controller: widget.passwordController,
hintText: 'Enter Your Password',
),
const SizedBox(height: 10),
const Text('Confirm Password'),
const SizedBox(height: 10),
CustomTextField(
controller: widget.confirmPassword,
hintText: 'Confirm Password',
),
const SizedBox(height: 20),
const Text('User Typ'),
const SizedBox(height: 10),
Row(
children: [
Row(
children: [
Radio(
value: 0,
groupValue: widget.userTyp,
onChanged: (v) {
setState(() {
widget.userTyp = v!;
});
},
),
const Text('Seller'),
],
),
Row(
children: [
Radio(
value: 1,
groupValue: widget.userTyp,
onChanged: (v) {
setState(() {
widget.userTyp = v!;
});
},
),
const Text('Buyer'),
],
),
Row(
children: [
Radio(
value: 2,
groupValue: widget.userTyp,
onChanged: (v) {
setState(() {
widget.userTyp = v!;
});
},
),
const Text('Both'),
],
),
],
),
Align(
alignment: Alignment.bottomRight,
child: ElevatedButton(
onPressed: () {
if (formKey.currentState!.validate()) {
widget.pageController.nextPage(
duration: const Duration(milliseconds: 100),
curve: Curves.easeInOut,
);
}
},
style: ElevatedButton.styleFrom(
backgroundColor: AppColor.mainColor,
minimumSize: const Size(150, 40),
),
child: const Text(
'Next',
style: TextStyle(
color: Colors.white,
),
),
),
)
],
),
),
),
);
}
}
|
import React, { useState } from 'react';
const Forgot = ({ onBackToLogin }) => {
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [errorMessage, setErrorMessage] = useState('');
const [successMessage, setSuccessMessage] = useState('');
const handleChangePassword = () => {
// Validate if new password and confirm password match
if (newPassword !== confirmPassword) {
setErrorMessage('Passwords do not match');
return;
}
// Simulated success message
setSuccessMessage('Password changed successfully!');
// Clear fields
setNewPassword('');
setConfirmPassword('');
};
return (
<div className="forgot-password-container">
<div className="forgot-password-form">
<h2>Forgot Password</h2>
<input
type="password"
placeholder="Enter New Password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
/>
<input
type="password"
placeholder="Re-enter New Password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
/>
<button onClick={handleChangePassword}>Change Password</button>
{errorMessage && <p className="error-message">{errorMessage}</p>}
{successMessage && <p className="success-message">{successMessage}</p>}
<div className="back-to-login" onClick={onBackToLogin}>
Back to Login
</div>
</div>
</div>
);
};
export default Forgot;
|
package com.programming.springboot.controller;
import com.programming.springboot.model.request.InputUserAuthenticate;
import com.programming.springboot.model.request.InputUserInfo;
import com.programming.springboot.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping("/api")
public class AuthenticationController {
public static final String AUTH_BASE_PATH = "/auth";
public static final String REGISTER_PATH = AUTH_BASE_PATH + "/register";
public static final String LOGIN_PATH = AUTH_BASE_PATH + "/login";
@Autowired
private AuthenticationService authenticationService;
@PostMapping(path = REGISTER_PATH , consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Object> register(@RequestBody @Valid InputUserInfo inputUserInfo) {
return authenticationService.register(inputUserInfo);
}
@PostMapping(path = LOGIN_PATH , consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Object> login(@RequestBody @Valid InputUserAuthenticate inputUserAuthenticate) {
return authenticationService.authenticate(inputUserAuthenticate);
}
}
|
import { bundle } from "assets";
import {
BaseInteraction,
type BaseMessageOptions,
type MessageCreateOptions,
type MessageEditOptions,
type CacheType,
Message,
ActionRowBuilder,
EmbedBuilder,
ButtonBuilder,
TextBasedChannel,
InteractionCollector,
ButtonInteraction,
SelectMenuInteraction,
ButtonStyle,
SelectMenuBuilder,
APIButtonComponent,
APISelectMenuOption,
ComponentType,
MessageComponentInteraction,
} from "discord.js";
import { KotlinLike } from "../../utils";
type Files = Exclude<BaseMessageOptions["files"], undefined>;
export type ManagerConstructOptions = {
content?: string;
embeds?: EmbedBuilder[];
components?: ActionRowBuilder<SelectMenuBuilder | ButtonBuilder>[];
triggers?: Map<string, ComponentTrigger>;
files?: Exclude<BaseMessageOptions["files"], undefined>;
lastManager?: Manager;
interaction: BaseInteraction;
};
type MenuSelectOptions<T> = {
list: T[] | (() => T[]);
reducer?: (elem: T, index: number) => APISelectMenuOption;
placeholder?: string;
};
type ComponentTrigger = (
interaction: MessageComponentInteraction,
manager: Manager
) => void;
/**
* 임베드와 컴포넌트의 생성, 통신, 상호작용을 총괄함
*/
class Manager extends KotlinLike<Manager> {
public content?: string;
public embeds: EmbedBuilder[] = [];
public components: ActionRowBuilder<SelectMenuBuilder | ButtonBuilder>[] = [];
public triggers: Map<string, ComponentTrigger> = new Map();
public files: Files = [];
public readonly locale: string;
public readonly interaction: BaseInteraction;
protected message?: Message | undefined;
protected collector?: InteractionCollector<
SelectMenuInteraction<CacheType> | ButtonInteraction<CacheType>
>;
protected readonly lastManager?: Manager;
public constructor({
content,
embeds = [],
components = [],
files = [],
interaction,
triggers = new Map(),
lastManager,
}: ManagerConstructOptions) {
super();
this.components = components;
this.triggers = triggers;
this.embeds = embeds;
this.files = files;
this.content = content;
this.interaction = interaction;
this.locale = interaction.locale;
this.lastManager = lastManager;
}
private updateCollector() {
this.collector ??= this.message
?.createMessageComponentCollector()
.on("collect", async (interaction) => {
const trigger = this.triggers.get(interaction.customId);
if (trigger) {
if (!interaction.deferred) {
this.message = await interaction.deferUpdate({ fetchReply: true });
}
trigger(interaction, this);
}
});
}
/**
* 현재 데이터를 갱신합니다.
* 메시지가 있다면 그 메시지로, 없다면 상호작용의 메시지를 수정하여 갱신합니다.
* @param channel - 송신할 채널
*/
public async update(
channel: TextBasedChannel | null = this.interaction.channel
): Promise<Message> {
if (!channel) throw new Error("channel does not exist");
const options: MessageEditOptions = {
content: this.content,
embeds: this.embeds,
components: this.components,
files: this.files,
};
const sent = await (() => {
if (this.message?.editable) return this.message.edit(options);
else if (this.interaction.isRepliable())
return this.interaction.editReply(options);
else return this.send(channel);
})();
this.message = sent;
this.updateCollector();
return sent;
}
/**
* 현재 데이터를 송신하고 message를 갱신합니다.
* @param channel - 송신할 채널
*/
public async send(
channel: TextBasedChannel | null = this.interaction.channel
): Promise<Message> {
if (!channel) throw new Error("channel does not exist");
const options: MessageCreateOptions = {
content: this.content,
embeds: this.embeds,
components: this.components,
files: this.files,
};
const sent = await channel.send(options);
this.message = sent;
this.updateCollector();
return sent;
}
/**
* 이 메시지와의 상호작용을 종료합니다.
* 이전 매니저가 존재할 경우 이전 매니저로 즉시 전환합니다.
* 이전 매니저가 존재하지 않을 경우 이벤트가 종료되고 삭제 버튼이 생성됩니다.
*/
public async endManager(timeout = 5000): Promise<void> {
if (this.lastManager) {
this.collector?.stop();
await this.lastManager.update();
} else {
//this.user.gameManager.endEvent();
this.setComponents();
this.addRemoveButton(timeout);
await this.update();
}
}
/**
* 보냈을 때 업데이트한 메시지를 삭제합니다.
*/
public async remove(): Promise<void> {
this.collector?.stop();
if (!this.message) throw new Error("message is empty");
else await this.message.delete();
}
public addComponent(
name: string,
row: number,
component: SelectMenuBuilder | ButtonBuilder,
callback: ComponentTrigger
) {
this.resizeSelection(row);
this.components[row].addComponents(component);
this.setTrigger(name, callback);
return this;
}
/**
* 버튼 컴포넌트를 추가합니다.
*
* @param name - 컴포넌트 이름
* @param row - 컴포넌트 열 (0~4)
* @param callback - 선택 콜백함수(버튼 interaction, 버튼 manager)
*/
public addButtonSelection(
name: string,
row: number,
callback: ComponentTrigger,
option: Partial<Omit<APIButtonComponent, "label" | "customId">> = {
style: ButtonStyle.Primary,
}
) {
this.addComponent(
name,
row,
new ButtonBuilder(option)
.setLabel(bundle.find(this.locale, `select.${name}`))
.setCustomId(name),
callback
);
return this;
}
/**
* 선택메뉴 컴포넌트를 추가합니다.
*
* @param name - 컴포넌트 이름
* @param row - 컴포넌트 열 (0~4)
* @param callback - 선택 콜백함수
* @param list - 아이템 리스트
* @param reducer - 아이템 리스트 매퍼
* @param placeholder - 선택 전 힌트
*/
public addMenuSelection<T>(
name: string,
row: number,
callback: (
interaction: MessageComponentInteraction,
manager: Manager,
item: T
) => void,
{ list, reducer, placeholder = "select..." }: MenuSelectOptions<T>
) {
this.resizeSelection(row);
const getList = () => (typeof list === "function" ? list() : list);
let currentPage = 0;
const reoption = () => {
const currentList = getList();
const options = currentList
.reduce<APISelectMenuOption[]>(
(acc, elem, index) =>
index < currentPage * 8 || index > (currentPage + 1) * 8
? acc
: [
...acc,
reducer
? reducer(elem, index)
: {
label: `#${index} item`,
value: index.toString(),
},
],
currentPage == 0
? []
: [
{
label: `<-- ${currentPage}/${
Math.floor(currentList.length / 8) + 1
}`,
value: "-1",
},
]
)
.concat(
currentPage == Math.floor(currentList.length / 8)
? []
: [
{
label: `${currentPage + 1}/${
Math.floor(currentList.length / 8) + 1
} -->`,
value: "-2",
},
]
);
return options.length === 0
? [{ label: "empty", value: "-10" }]
: options;
};
const refreshOptions = () => {
(this.components[row]?.components[0] as SelectMenuBuilder).setOptions(
reoption()
);
return this;
};
this.components[row].addComponents(
new SelectMenuBuilder()
.setCustomId(name)
.setPlaceholder(placeholder)
.setOptions(reoption())
);
this.setTrigger(name, async (interaction, manager) => {
if (
!(
interaction.isSelectMenu() &&
interaction.component.type == ComponentType.SelectMenu
)
)
return;
const id = interaction.values[0];
const list = getList();
switch (id) {
case "-1":
if (currentPage == 0)
Manager.newErrorEmbed(
this.interaction,
bundle.find(this.locale, "error.first_page")
);
else currentPage--;
break;
case "-2":
if (currentPage + 1 > Math.floor(list.length / 8))
Manager.newErrorEmbed(
this.interaction,
bundle.find(this.locale, "error.last_page")
);
else currentPage++;
break;
case "-10":
break;
default:
callback(interaction, manager, list[Number(id)]);
}
await refreshOptions().update();
});
return refreshOptions;
}
/**
* 최대 5 열까지 컴포넌트 열 컴포넌트를 추가합니다.
* @param row 갱신할 열 길이
*/
private resizeSelection(row: number) {
if (row >= 5) throw new Error("component row cannot be more than 5!");
while (this.components.length <= row) {
this.components.push(new ActionRowBuilder({ components: [] }));
}
}
public addBackButton(): this {
if (!this.lastManager)
throw new Error(
"last manager does not exist but trying to add back button?"
);
this.addButtonSelection(
"back_select",
0,
() => {
if (!this.lastManager)
throw new Error(
"last manager does not exist but trying to add back button?"
);
this.collector?.stop();
this.lastManager.update();
},
{ style: ButtonStyle.Secondary }
);
return this;
}
public addRemoveButton(timeout = 5000): this {
const id = setTimeout(() => timeout != -1 && this.remove(), timeout);
this.addComponents(
new ActionRowBuilder<ButtonBuilder>().addComponents([
new ButtonBuilder()
.setCustomId("remove_embed")
.setLabel("Cancel")
.setStyle(ButtonStyle.Secondary),
])
);
this.setTrigger("remove_embed", () => {
clearTimeout(id);
this.remove();
});
return this;
}
public addContent(content: string): this {
this.content += content;
return this;
}
public setContent(content: string): this {
this.content = content;
return this;
}
public setEmbeds(...embeds: EmbedBuilder[]): this {
this.embeds = embeds;
return this;
}
public addEmbeds(...embeds: EmbedBuilder[]): this {
this.embeds.push(...embeds);
return this;
}
public setComponents(
...components: ActionRowBuilder<SelectMenuBuilder | ButtonBuilder>[]
): this {
this.components = components;
return this;
}
public addComponents(
...components: ActionRowBuilder<SelectMenuBuilder | ButtonBuilder>[]
): this {
this.components.push(...components);
return this;
}
public setTrigger(customId: string, trigger: ComponentTrigger): this {
this.triggers.set(customId, trigger);
return this;
}
public setFiles(...files: Files): this {
this.files = files;
return this;
}
public addFiles(...files: Files): this {
this.files.push(...files);
return this;
}
public static async newErrorEmbed(
interaction: BaseInteraction,
description: string,
update: boolean = false
) {
const manager = new Manager({
interaction,
embeds: [
new EmbedBuilder().setTitle("ERROR").setDescription(description),
],
});
manager.addRemoveButton();
if (update) await manager.update(interaction.channel);
else await manager.send(interaction.channel);
return manager;
}
public static async newTextEmbed(
interaction: BaseInteraction,
description: string,
title = "",
update: boolean = false
) {
const manager = new Manager({
interaction,
embeds: [new EmbedBuilder().setTitle(title).setDescription(description)],
});
manager.addRemoveButton();
if (update) await manager.update(interaction.channel);
else await manager.send(interaction.channel);
return manager;
}
}
export default Manager;
|
// Dependencias Globales
import * as React from "react";
import { withRouter, RouteComponentProps } from "react-router";
import { Subscription } from "rxjs";
// Layouts
import NavBar from "../nav-bar";
// Assets
import logo from "../../../assets/img/logo-topbar.png";
// Helpers
import { CredentialsHelper, AuthenticatedUsuarioInfo } from "../../../helpers/credentials-helper";
// Components
import { UsuarioMenuDropdown } from "./components";
import { TopBarBrand } from "./components/top-bar-brand";
export interface DropdownType {
catalogsDropdown: boolean;
notificationDropdown: boolean;
userMenuDropdown: boolean;
workshopCapacityModal: boolean;
}
interface TopBarState {
activeWindow: string;
userName: string;
userRole: string;
logoBase64: string;
workshopCapacityDate: Date;
workOrderModal: WorkOrderModalType;
}
enum WorkOrderModalTab {
Details,
Invalidation
}
interface WorkOrderModalType {
currentWorkOrderId: number;
isOpen: boolean;
}
/**
* Barra superior para la aplicación
*/
class TopBar extends React.Component<RouteComponentProps, TopBarState> {
state: TopBarState = {
activeWindow: null,
workOrderModal: {
currentWorkOrderId: null,
isOpen: false
},
workshopCapacityDate: new Date(),
userName: "",
userRole: "",
logoBase64: undefined
};
componentDidMount() {
const credentials: AuthenticatedUsuarioInfo = CredentialsHelper.getRoleAndUsuarioFromTokenInCookie();
if (credentials != null) {
this.setState({
userName: credentials.userName,
userRole: credentials.userRole
});
}
this.getLogo();
}
private removeNotification(notificationId: number) {
}
private onCloseSession = () => {
CredentialsHelper.deleteSessionToken();
};
private onClickNotification = (id, workOrderId?) => {
if (workOrderId != null) {
this.setState({
workOrderModal: {
...this.state.workOrderModal,
currentWorkOrderId: workOrderId,
isOpen: !this.state.workOrderModal.isOpen
}
});
}
};
private getLogo = () => {
this.setState({
logoBase64: logo
})
};
private onToggleWorkorderModal = () => {
this.setState({
workOrderModal: {
...this.state.workOrderModal,
isOpen: !this.state.workOrderModal.isOpen
}
});
};
private onClickActionButton = (activeWindow: string) => {
if (this.state.activeWindow === activeWindow) {
this.setState({ activeWindow: null });
} else {
this.setState({ activeWindow });
}
};
private onClickWorkshopCapacityModal = () => this.onClickActionButton("workshopCapacityModal");
private onClickNotificationDropdown = () => this.onClickActionButton("notificationDropdown");
private onClickUsuarioMenuDropdown = () => this.onClickActionButton("userMenuDropdown");
private onClickCatalogsDropdown = () => this.onClickActionButton("catalogsDropdown");
render() {
const { activeWindow, logoBase64, userName, userRole } = this.state;
return (
<div className="top-bar">
<div className="top-bar__container">
<TopBarBrand logoBase64={logoBase64} history={this.props.history} />
<div className="top-bar--collapse">
<div className="user-menu">
<UsuarioMenuDropdown
activeWindow={activeWindow}
onCloseSession={this.onCloseSession}
onClickActionButton={this.onClickUsuarioMenuDropdown}
userName={userName}
userRole={userRole}
/>
</div>
</div>
</div>
<div className="top-bar__container">
<NavBar activeWindow={activeWindow} onClickActionButton={this.onClickCatalogsDropdown} />
</div>
</div>
);
}
}
export default withRouter(TopBar);
|
import { expectType, expectAssignable } from 'tsd-lite';
const mixins1 = {
data: {
b: 1,
},
} as MiniProgram.Mixin.IMixin4Legacy<
{
b: number;
},
{},
{}
>;
Component({
mixins: [mixins1, { didMount() {}, methods: { mixinMethod() {} } }], // mixins 方便复用代码
data: { x: 1 }, // 组件内部数据
props: { y: 1 }, // 可给外部传入的属性添加默认值
didMount() {
expectType<number>(this.data.x);
expectAssignable<Function>(this.mixinMethod);
expectAssignable<number>(this.data.b);
}, // 生命周期函数
didUpdate() {},
didUnmount() {},
methods: {
// 自定义方法
handleTap() {
this.setData({ x: this.data.x + 1 }); // 可使用 setData 改变内部属性
},
},
});
|
import React, { useState } from "react";
import Button from "@mui/material/Button";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import Card from "@mui/material/Card";
import CardHeader from "@mui/material/CardHeader";
import CardMedia from "@mui/material/CardMedia";
import CardContent from "@mui/material/CardContent";
import CardActions from "@mui/material/CardActions";
import Avatar from "@mui/material/Avatar";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import FavoriteIcon from "@mui/icons-material/Favorite";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import ThumbUpIcon from "@mui/icons-material/ThumbUp";
import CommentIcon from "@mui/icons-material/Comment";
import { useNavigate } from "react-router-dom";
import CloseIcon from "@mui/icons-material/Close";
import { comment, post } from "./interface";
import { useQuery } from "@tanstack/react-query";
import EditIcon from "@mui/icons-material/Edit";
const Post = ({
title,
text,
image,
id,
fav,
numberOfLikes,
updated,
name,
}: post) => {
const [clicked, setClicked] = useState<boolean>(false);
const navigate = useNavigate();
const [showCom, setShowCom] = useState<boolean>(false);
const [textComm, setTextComm] = useState<string>("");
const [updateCom, setUpdateCom] = useState<boolean>(false);
const [upId, setUpId] = useState<number>(0);
const [ckickMenu, setClickMenue] = useState<boolean>(false);
const handleAddToFavorites = async () => {
fav = !fav;
await fetch(`http://localhost:3200/postes/${id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ fav }),
});
};
const handleNumberOfLikes = async () => {
numberOfLikes = numberOfLikes + 1;
await fetch(`http://localhost:3200/postes/${id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ numberOfLikes }),
});
};
const handleAddComments = async () => {
setClicked(false);
const postId = id;
await fetch(`http://localhost:3200/comments/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ textComm, postId }),
}).then(() => navigate("/home"));
};
const changUpdates = () => {
updated = true;
};
const handleChangeUpdate = async () => {
changUpdates();
await fetch(`http://localhost:3200/postes/${id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ updated }),
}).then(() => navigate("/update"));
};
const handleDelete = async () => {
await fetch(`http://localhost:3200/postes/${id}`, {
method: "DELETE",
});
};
const handleOnClick = () => {
setUpdateCom(true);
setClicked(true);
};
const getData = async (): Promise<comment[]> => {
return await fetch("http://localhost:3200/comments").then((response) =>
response.json()
);
};
const { data: dataOfComments } = useQuery(["dataOfCom"], getData);
return (
<Card sx={{ margin: "10px", maxWidth: 340 }}>
{/* start card header */}
<CardHeader
avatar={<Avatar alt="Remy Sharp" src="/images/avatar-01.jpg" />}
action={
<Box>
<IconButton
aria-label="settings"
onClick={() => setClickMenue(!ckickMenu)}
>
<MoreVertIcon />
</IconButton>
<IconButton sx={{ position: "absolute" }}>
{ckickMenu && (
<Box
sx={{
display: "flex",
flexDirection: "column",
backgroundColor: "#eee",
ml: "10px",
padding: "10px",
borderRadius: "4px",
}}
>
{/* Update Post*/}
<Button
sx={{ mr: "10px", mt: "10px" }}
// variant="contained"
size="small"
onClick={() => handleChangeUpdate()}
>
update
</Button>
{/* Delete Post */}
<Button
sx={{ mt: "10px" }}
// variant="contained"
size="small"
onClick={() => handleDelete()}
>
delete
</Button>
</Box>
)}
</IconButton>
</Box>
}
title={name}
subheader="September 14, 2016"
/>
{/* end card header */}
{/* start card picture */}
<CardMedia component="img" height="194" image={image} alt="Paella dish" />
{/*end card picture */}
{/* start card content */}
<CardContent>
<Typography variant="h5" color="text.primary">
{title}
</Typography>
<Typography
variant="body2"
color="text.secondary"
sx={{ overflowWrap: "break-word" }}
>
{text}
</Typography>
</CardContent>
{/* end card content */}
{/* start card actions */}
<CardActions
disableSpacing
sx={{ display: "flex", justifyContent: "space-between" }}
>
<Box>
{/* favorites */}
<IconButton
aria-label="add to favorites"
color={fav ? "error" : "default"}
onClick={() => handleAddToFavorites()}
>
<FavoriteIcon />
</IconButton>
{/* Like */}
<IconButton
aria-label="Like"
color={numberOfLikes > 0 ? "primary" : "default"}
onClick={() => handleNumberOfLikes()}
>
<ThumbUpIcon />
<div
style={{
position: "absolute",
color: "black",
width: "20px",
height: "20px",
bottom: 0,
right: 0,
transform: "translate(25%,25%)",
zIndex: 1,
fontSize: "15px",
}}
>
{numberOfLikes}
</div>
</IconButton>
{/* Comments */}
<IconButton
aria-label="comment"
sx={{ mr: "10px" }}
onClick={() => setClicked(!clicked)}
>
<CommentIcon />
<div
style={{
position: "absolute",
color: "black",
width: "20px",
height: "20px",
bottom: 0,
right: 0,
transform: "translate(25%,25%)",
zIndex: 1,
fontSize: "15px",
}}
>
{/* {numberOfComments} */}
</div>
</IconButton>
{clicked === true &&
(updateCom === false ? (
<div>
<TextField
size="small"
onChange={(e) => {
setTextComm(e.target.value);
}}
placeholder="comment.."
sx={{ mb: "10px", mr: "10px" }}
/>
<Button variant="outlined" onClick={() => handleAddComments()}>
OK
</Button>{" "}
</div>
) : (
<div>
{dataOfComments &&
dataOfComments.map((it) => {
return (
<Box>
{it.id === upId && (
<Box>
<TextField
size="small"
defaultValue={it.textComm}
onChange={(e) => {
setTextComm(e.target.value);
}}
placeholder="comment.."
sx={{ mb: "10px", mr: "10px" }}
/>
<Button
variant="outlined"
onClick={async () => {
setClicked(false);
await fetch(
`http://localhost:3200/comments/${it.id}`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ textComm }),
}
).then(() => navigate("/home"));
}}
>
OK
</Button>
</Box>
)}
</Box>
);
})}
</div>
))}
</Box>
</CardActions>
{/* end card actions */}
{/* start comments section */}
<Box sx={{ display: "flex", mb: "10px", justifyContent: "center" }}>
<Button
variant="outlined"
onClick={() => {
setShowCom(!showCom);
}}
>
Show Comments
</Button>
</Box>
{showCom === true && (
<Box sx={{ mb: "10px" }}>
{dataOfComments &&
dataOfComments.map((i) => {
return (
<Box>
{id === i.postId && (
<Typography
key={i.id}
paragraph
color="text.secondary"
sx={{
display: "flex",
ml: "10px",
mr: "10px",
border: "1px solid blue",
mb: "10px",
justifyContent: "space-between",
padding: "10px",
borderRadius: "4px",
}}
>
{i.textComm}
<Box>
<IconButton
sx={{ padding: 0 }}
onClick={() => {
handleOnClick();
setUpId(i.id);
}}
>
<EditIcon />
</IconButton>
<IconButton
sx={{ padding: 0 }}
color="error"
onClick={async () => {
await fetch(
`http://localhost:3200/comments/${i.id}`,
{
method: "DELETE",
}
);
}}
>
<CloseIcon />
</IconButton>
</Box>
</Typography>
)}
</Box>
);
})}
</Box>
)}
{/* end comments section */}
</Card>
);
};
export default Post;
|
package com.daily_school.daily_school.ui.plan
import FirebaseManager
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.graphics.Paint
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.daily_school.daily_school.R
import com.daily_school.daily_school.databinding.FragmentPlanListBinding
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.text.SimpleDateFormat
import java.util.*
class PlanListFragment : BottomSheetDialogFragment() {
private lateinit var binding : FragmentPlanListBinding
private var currentDate: String? = ""
private var todoListArray: List<Map<String, Any>> = mutableListOf()
private val firebaseManager = FirebaseManager()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_plan_list, container, false)
// 프래그먼트를 종료하는 함수 호출
finishFragment()
// 데이터 저장 함수 호출
todoListDataInit()
// 현재 날짜 요일 셋업 함수 호출
currentDateInit()
// 할 일 목록을 보여주는 함수 호출
showTodoList()
// 다시 보지 않기 설정 함수 호출
neverShowGuideText()
// 다시 보기 상태 가져오는 함수 호출
getNeverShowGuideText()
return binding.root
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog: Dialog = super.onCreateDialog(savedInstanceState)
dialog.setOnShowListener {
val bottomSheetDialog = it as BottomSheetDialog
setupRatio(bottomSheetDialog)
}
return dialog
}
// BottomSheetDialog Interface를 view에 전달하는 함수
private fun setupRatio(bottomSheetDialog: BottomSheetDialog) {
val bottomSheet = bottomSheetDialog.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) as View
val behavior = BottomSheetBehavior.from<View>(bottomSheet)
val layoutParams = bottomSheet!!.layoutParams
layoutParams.height = getBottomSheetDialogDefaultHeight()
bottomSheet.layoutParams = layoutParams
behavior.state = BottomSheetBehavior.STATE_EXPANDED
}
// BottomSheetDialog 높이 조절 함수
private fun getBottomSheetDialogDefaultHeight(): Int {
return getWindowHeight()
}
// Window 크기 조절 함수
private fun getWindowHeight(): Int {
val displayMetrics = DisplayMetrics()
(context as Activity?)!!.windowManager.defaultDisplay.getMetrics(displayMetrics)
return displayMetrics.heightPixels
}
// 프래그먼트를 종료하는 함수
private fun finishFragment(){
binding.planListIcBack.setOnClickListener {
dismiss()
}
}
// 데이터 저장 함수
private fun todoListDataInit() {
val gson = Gson()
val filteredTodoListJson = arguments?.getString("todoInfo")
currentDate = arguments?.getString("todoDate")
todoListArray = gson.fromJson(filteredTodoListJson, object : TypeToken<List<Map<String, Any>>>() {}.type)
}
// 현재 날짜 요일 셋업 함수
private fun currentDateInit() {
val inputDateFormat = SimpleDateFormat("yyyy-MM-d", Locale.getDefault())
val date = inputDateFormat.parse(currentDate)
val outputDateFormat = SimpleDateFormat("yyyy년 M월 d일 (E)", Locale.getDefault())
binding.planListDateTextView.text = outputDateFormat.format(date)
}
// 할 일 목록을 보여주는 함수
private fun showTodoList() {
val planTodoLayout = binding.planTodoLayout
val inflater = LayoutInflater.from(requireContext())
planTodoLayout.removeAllViews()
for (todoItem in todoListArray) {
val planTodoItem = inflater.inflate(R.layout.plan_todo_item, planTodoLayout, false)
val planTodoColorImageView = planTodoItem.findViewById<ImageView>(R.id.planTodoColorImageView)
val planTodoTextView = planTodoItem.findViewById<TextView>(R.id.planTodoTextView)
val todoName = todoItem["todoName"] as? String
val todoColor = todoItem["todoColor"] as? String
val todoComplete = todoItem["todoComplete"] as? Boolean
todoColor?.let {
val colorResourceId = getTodoColorResourceId(it)
planTodoColorImageView.setBackgroundResource(colorResourceId)
}
if(todoComplete == true) {
val textColorResourceId = R.color.gray_6
val textColor = ContextCompat.getColor(requireContext(), textColorResourceId)
planTodoTextView.paintFlags = planTodoTextView.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
planTodoTextView.setTextColor(textColor)
}
planTodoItem.setOnClickListener {
// 완료 다이얼로그 호출
showTodoCompleteDialog(todoName.toString())
}
planTodoTextView.text = todoName
planTodoLayout.addView(planTodoItem)
}
}
// 달성 완료 다이얼로그 함수
private fun showTodoCompleteDialog(todoName: String) {
val completeDialog = TodoCompleteDialog()
completeDialog.setCompleteDialogListener(object : TodoCompleteDialog.TodoCompleteDialog {
// 아니요 버튼 클릭 시 동작
override fun onNoButtonClicked() {
}
// 예 버튼 클릭 시 동작
override fun onYesButtonClicked() {
dismiss()
firebaseManager.updateTodoComplete(todoName)
}
})
completeDialog.show(requireActivity().supportFragmentManager, completeDialog.tag)
}
// 할 일 목록 색상 지정 함수
private fun getTodoColorResourceId(todoColor: String): Int {
return when (todoColor) {
TodoColor.RED.name -> R.color.red_color
TodoColor.BLUE.name -> R.color.main_color
TodoColor.YELLOW.name -> R.color.yellow_color
TodoColor.ORANGE.name -> R.color.orange_color
TodoColor.GREEN.name -> R.color.light_green_color
TodoColor.PURPLE.name -> R.color.pink_color
else -> R.color.main_color
}
}
// 다시 보지 않기 설정 함수
private fun neverShowGuideText() {
binding.planTodoNeverShowTextView.setOnClickListener {
binding.planTodoGuideArea.visibility = View.GONE
setNeverShowAgainStatus(true)
}
}
// 다시 보기 상태 가져오는 함수
private fun getNeverShowGuideText() {
val neverShowAgainStatus = getNeverShowAgainStatus()
if (neverShowAgainStatus) {
binding.planTodoGuideArea.visibility = View.GONE
}
else {
binding.planTodoGuideArea.visibility = View.VISIBLE
}
}
// SharedPreferences Set 함수
private fun setNeverShowAgainStatus(status: Boolean) {
val sharedPreferences = requireContext().getSharedPreferences("todoGuide", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putBoolean("show", status)
editor.apply()
}
// SharedPreferences Get 함수
private fun getNeverShowAgainStatus(): Boolean {
val sharedPreferences = requireContext().getSharedPreferences("todoGuide", Context.MODE_PRIVATE)
return sharedPreferences.getBoolean("show", false)
}
}
|
---
permalink: sm-storage/assign-volumes.html
sidebar: sidebar
keywords: SANtricity, System Manager, E-Series, assign volumes
summary: È necessario assegnare un volume a un host o a un cluster di host in modo che possa essere utilizzato per le operazioni di i/O. Questa assegnazione consente a un host o a un cluster host di accedere a uno o più volumi in un array di storage.
---
= Assegnare volumi agli host
:allow-uri-read:
:experimental:
:icons: font
:imagesdir: ../media/
[role="lead"]
È necessario assegnare un volume a un host o a un cluster di host in modo che possa essere utilizzato per le operazioni di i/O. Questa assegnazione consente a un host o a un cluster host di accedere a uno o più volumi in un array di storage.
.A proposito di questa attività
Tenere presenti queste linee guida quando si assegnano volumi agli host:
* È possibile assegnare un volume a un solo host o cluster di host alla volta.
* I volumi assegnati vengono condivisi tra i controller dell'array di storage.
* Lo stesso numero di unità logica (LUN) non può essere utilizzato due volte da un host o da un cluster host per accedere a un volume. È necessario utilizzare un LUN univoco.
* Per i nuovi gruppi di volumi, se si attende la creazione e l'inizializzazione di tutti i volumi prima di assegnarli a un host, il tempo di inizializzazione del volume viene ridotto. Tenere presente che una volta mappato un volume associato al gruppo di volumi, _tutti_ i volumi torneranno all'inizializzazione più lenta. È possibile controllare l'avanzamento dell'inizializzazione dal menu:Home[operazioni in corso].
L'assegnazione di un volume non riesce nelle seguenti condizioni:
* Vengono assegnati tutti i volumi.
* Il volume è già assegnato a un altro host o cluster di host.
La possibilità di assegnare un volume non è disponibile nelle seguenti condizioni:
* Non esistono host o cluster di host validi.
* Non sono stati definiti identificatori di porta host per l'host.
* Sono state definite tutte le assegnazioni dei volumi.
Durante questa attività vengono visualizzati tutti i volumi non assegnati, ma le funzioni per gli host con o senza Data Assurance (da) si applicano come segue:
* Per un host da-capable, è possibile selezionare i volumi che sono da-enabled o non da-enabled.
* Per un host che non supporta da, se si seleziona un volume abilitato da, viene visualizzato un avviso che indica che il sistema deve disattivare automaticamente da sul volume prima di assegnarlo all'host.
.Fasi
. Selezionare menu:Storage[Hosts] (Storage[host]).
. Selezionare l'host o il cluster host a cui si desidera assegnare i volumi, quindi fare clic su *Assign Volumes* (Assegna volumi).
+
Viene visualizzata una finestra di dialogo che elenca tutti i volumi che è possibile assegnare. È possibile ordinare qualsiasi colonna o digitare qualcosa nella casella *Filter* per semplificare la ricerca di volumi specifici.
. Selezionare la casella di controllo accanto a ciascun volume che si desidera assegnare oppure selezionare la casella di controllo nell'intestazione della tabella per selezionare tutti i volumi.
. Fare clic su *Assegna* per completare l'operazione.
.Risultati
Dopo aver assegnato correttamente uno o più volumi a un host o a un cluster di host, il sistema esegue le seguenti operazioni:
* Il volume assegnato riceve il successivo numero LUN disponibile. L'host utilizza il numero LUN per accedere al volume.
* Il nome del volume fornito dall'utente viene visualizzato negli elenchi dei volumi associati all'host. Se applicabile, il volume di accesso configurato in fabbrica viene visualizzato anche negli elenchi dei volumi associati all'host.
|
import Embed from '@editorjs/embed'
import Table from '@editorjs/table'
import List from '@editorjs/list'
// import Image from '@editorjs/image'
import Header from '@editorjs/header'
import Quote from '@editorjs/quote'
import Marker from '@editorjs/marker'
import CheckList from '@editorjs/checklist'
import InlineCode from '@editorjs/inline-code'
import Warning from './Warning';
import Success from './Success'
import Error from './Error';
import Info from './Info';
import Divider from './Divider';
import MyLinkTool from './MyLinkTool';
import MyImageTool from './MyImageTool';
import LineBreak from './LineBreak';
import Hyperlink from 'editorjs-hyperlink';
import CodeEditor from './CodeEditor'
import { SprintPlanningAPI } from '../../api/apiConfig'
const EDITOR_JS_TOOLS = {
// NOTE: Paragraph is default tool. Declare only when you want to change paragraph option.
checklist: {
inlineToolbar: true,
class: CheckList
},
code: CodeEditor,
divider: Divider,
linebreak: LineBreak,
embed: {
class: Embed,
inlineToolbar: false,
config: {
services: {
youtube: true,
codepen: true,
instagram: true,
imgur: true,
twitter: true
}
}
},
header: {
inlineToolbar: true,
class: Header,
config: {
placeholder: 'Enter your content here...'
}
},
image: {
class: MyImageTool,
inlineToolbar: false,
config: {
uploader: {
uploadByFile(file, congigs = {onPreview: (src) => {
console.log("uploadByFile onPreview src:", src)
}}){
return SprintPlanningAPI.POST.uploadFile({ fileObj: file }).then(res => {
return {
success: res.data?.success,
file: {
url: `${res.data?.data?.key}`
}
}
});
}
},
additionalRequestHeaders: {
authorization: `Bearer ${localStorage.getItem("token")}`,
}
}
},
inlineCode: InlineCode,
hyperlink: {
class: Hyperlink
},
list: List,
marker: {
inlineToolbar: true,
class: Marker
},
quote: {
inlineToolbar: true,
class: Quote
},
table: {
inlineToolbar: true,
class: Table
},
warning: {
inlineToolbar: true,
class: Warning
},
info: {
inlineToolbar: true,
class: Info
},
success: {
inlineToolbar: true,
class: Success
},
error: {
inlineToolbar: true,
class: Error
}
};
export default EDITOR_JS_TOOLS;
|
open System_defs
open Component_defs
(* Générateur d'uid *)
let uid =
let cpt = ref (-1) in
fun () ->
begin
if !cpt >= 2048 then cpt := -1;
incr cpt;
!cpt
end
(* Création d'asteroid *)
let rec create_asteroid x y id level =
let l = Global.asteroid_size in
let l =
[| int_of_float (float l *. 0.6); int_of_float (float l *. 0.8); l |].(level)
in
let mass = [| 120.; 160.; 200. |].(level) in
let drag = 0. in
let rebound = 0.25 in
let is_bonus = Random.int 100 < Global.bonus_drop_rate () in
let f_bonus, kind_texture =
if is_bonus then Bonus.get_bonus () else ((fun () -> ()), Asteroid)
in
let ctx = Gfx.get_context (Global.window ()) in
let surface = Gfx.get_resource (Texture.get kind_texture) in
let texture = Texture.image_from_surface ctx surface 0 0 32 32 l l in
let ast = Box.create id x y l l mass drag rebound Asteroid texture in
let f = ast#remove#get in
ast#hp#set [| 1; 2; 4 |].(level);
ast#level#set level;
ast#under_gravity#set (Global.is_ast_under_gravity level);
ast#remove#set (fun () ->
f ();
if ast#is_dead#get then begin
f_bonus ();
let lvl = ast#level#get - 1 in
if lvl >= 0 && not !Global.no_spawn then
let ast_size = Global.asteroid_size in
let x = int_of_float ast#pos#get.x in
let y = int_of_float ast#pos#get.y in
let lvl = ast#level#get - 1 in
let factor = [| 10.; 1. |].(lvl) in
let vx = 0.5 /. factor in
let vy = 1. /. factor in
if lvl >= 0 then begin
create_asteroid_with_sumforces (x - ast_size) (y - ast_size)
(id ^ "_0")
Vector.{ x = -1. *. vx; y = -0.75 *. vy }
lvl;
create_asteroid_with_sumforces (x + ast_size) (y - ast_size)
(id ^ "_1")
Vector.{ x = vx; y = -0.75 *. vy }
lvl;
create_asteroid_with_sumforces (x - ast_size) (y + ast_size)
(id ^ "_2")
Vector.{ x = -1. *. vx; y = vy }
lvl;
create_asteroid_with_sumforces (x + ast_size) (y + ast_size)
(id ^ "_3")
Vector.{ x = vx; y = vy }
lvl
end
end );
Entities.asteroids#replace id ast;
ast
and create_asteroid_with_velocity x y id velocity level =
let ast = create_asteroid x y id level in
ast#velocity#set velocity
and create_asteroid_with_sumforces x y id sum_forces level =
let ast = create_asteroid x y id level in
ast#sum_forces#set sum_forces
(* Les différents paterns des asteroids *)
(* Single line *)
let pattern_1 () =
let space = (Global.ovni_w / 2) + 10 + Global.asteroid_size in
let nb = Global.width / space in
let rand = Random.int nb in
let speed =
Vector.{ x = 0.; y = 3.75 +. (0.4 *. float (Scoring.get_wave ())) }
in
let speed = Vector.mult 0.25 speed in
let x = ref ((10 + Global.asteroid_size) / 2) in
for i = 0 to nb - 1 do
if i <> rand then begin
let id = Printf.sprintf "asteroids_%d" (uid ()) in
create_asteroid_with_sumforces
(!x + Random.int 5)
(Random.int 25 - 25 - Global.asteroid_size)
id speed 2
end;
x := !x + space
done
(* Zig-Zag pattern *)
let pattern_2 () =
let decal () = (float (Random.int 50) -. 25.) /. 100. in
let space = 2 * Global.asteroid_size in
let nb = Global.width / space in
let factor = 8. +. (0.4 *. float (Scoring.get_wave ())) in
let x1 = ref (-Global.width / 2) in
let y1 = ref (-Global.height / 4) in
let x2 = ref (Global.width + (Global.width / 8)) in
let y2 = ref (-Global.height / 2) in
for _ = 1 to nb do
let id1 = Printf.sprintf "asteroids_%d" (uid ()) in
let speed1 =
Vector.mult
(factor +. decal ())
(Vector.normalize Vector.{ x = 1.; y = 1. })
in
let speed1 = Vector.mult 0.25 speed1 in
create_asteroid_with_sumforces !x1 !y1 id1 speed1 2;
let id2 = Printf.sprintf "asteroids_%d" (uid ()) in
let speed2 =
Vector.mult
(factor +. decal ())
(Vector.normalize Vector.{ x = -3.; y = 1. })
in
let speed2 = Vector.mult 0.25 speed2 in
create_asteroid_with_sumforces !x2 !y2 id2 speed2 2;
x1 := !x1 + space;
x2 := !x2 + space;
y2 := !y2 + space
done
(* Single line with difference of speed *)
let pattern_3 () =
let space = (Global.ovni_w / 2) + 10 + Global.asteroid_size in
let nb = Global.width / space in
let rand = Random.int 2 in
let x = ref ((10 + Global.asteroid_size) / 2) in
for i = 0 to nb - 1 do
let id = Printf.sprintf "asteroids_%d" (uid ()) in
let speed =
Vector.
{ x = 0.
; y =
(if i mod 2 = rand then 3.75 else 7.5)
+. (0.4 *. float (Scoring.get_wave ()))
+. Random.float 2.0
}
in
let speed = Vector.mult 0.25 speed in
create_asteroid_with_sumforces
(!x + Random.int 5)
(Random.int 25 - 25 - Global.asteroid_size)
id speed 2;
x := !x + space
done
(* double little T pattern *)
let pattern_4 () =
let space = (Global.ovni_w / 2) + 10 + Global.asteroid_size in
let width = (5 * space) + 10 in
let x = ref (Random.int ((Global.width / 2) - width)) in
for v = 0 to 1 do
for i = 0 to 4 do
let id = Printf.sprintf "asteroids_%d" (uid ()) in
let speed1 =
Vector.{ x = 0.; y = 3.75 +. (0.4 *. float (Scoring.get_wave ())) }
in
let speed1 = Vector.mult 0.25 speed1 in
create_asteroid_with_sumforces (!x + (i * space)) (-space * 4) id speed1 2
done;
x := !x + (2 * space);
for i = 0 to 2 do
let id = Printf.sprintf "asteroids_%d" (uid ()) in
let speed2 =
Vector.{ x = 0.; y = 3.75 +. (0.4 *. float (Scoring.get_wave ())) }
in
let speed2 = Vector.mult 0.25 speed2 in
create_asteroid_with_sumforces !x
((-space * 4) + ((i + 1) * space))
id speed2 2
done;
x := Random.int ((Global.width / 2) - width) + (Global.width / 2)
done
(* Z pattern *)
let pattern_5 () =
let size = Global.asteroid_size in
let factor = 7 in
let space = (Global.ovni_w / 2) + 10 + size in
let nb = Global.width / space in
let limit = 1 + Random.int (nb - 2) in
let speed =
Vector.{ x = 0.; y = 3.75 +. (0.4 *. float (Scoring.get_wave ())) }
in
let speed = Vector.mult 0.25 speed in
let x = ref ((10 + size) / 2) in
for i = 0 to nb - 1 do
if i = limit then begin
let decal_top = ref (size + (factor * size)) in
let decal_bot = ref size in
for j = 0 to factor / 4 do
let id1 = Printf.sprintf "asteroids_%d" (uid ()) in
create_asteroid_with_sumforces
(!x + Random.int 10 - 5)
(Random.int 5 - !decal_top - size)
id1 speed 2;
decal_top := !decal_top - size - 25;
let id2 = Printf.sprintf "asteroids_%d" (uid ()) in
create_asteroid_with_sumforces
(!x + Random.int 10 - 5)
(Random.int 5 - !decal_bot - size)
id2 speed 2;
decal_bot := !decal_bot + size + 25
done
end
else begin
let id = Printf.sprintf "asteroids_%d" (uid ()) in
let decal = size + if i < limit then factor * size else 0 in
create_asteroid_with_sumforces
(!x + Random.int 5)
(Random.int 25 - decal - size)
id speed 2
end;
x := !x + space
done
(* big T pattern *)
let pattern_6 () =
let size = Global.asteroid_size in
let factor = Global.height / size / 2 in
let decal = (factor * (size + (size / 2))) + size in
let space = (Global.ovni_w / 2) + 10 + size in
let nb = Global.width / space in
let limit = (nb / 2) - (nb / 4) + Random.int (nb / 2) in
let rand =
if Random.int 2 = 0 then Random.int limit
else limit + 1 + Random.int (nb - limit - 1)
in
let speed =
Vector.{ x = 0.; y = 3.75 +. (0.4 *. float (Scoring.get_wave ())) }
in
let speed = Vector.mult 0.25 speed in
let x = ref ((10 + size) / 2) in
for i = 0 to nb - 1 do
if i = limit then begin
let decal_tmp = ref decal in
for _ = 0 to factor do
let id = Printf.sprintf "asteroids_%d" (uid ()) in
create_asteroid_with_sumforces
(!x + Random.int 5)
(Random.int 25 - 25 - !decal_tmp)
id speed 2;
decal_tmp := !decal_tmp - size - (size / 2)
done
end
else if i <> rand then begin
let id = Printf.sprintf "asteroids_%d" (uid ()) in
create_asteroid_with_sumforces
(!x + Random.int 5)
(Random.int 25 - 25 - decal)
id speed 2
end;
x := !x + space
done
let paterns =
[| pattern_1; pattern_2; pattern_3; pattern_4; pattern_5; pattern_6 |]
(* Lance l'init des asteroids *)
let init_asteroids () =
Scoring.incr_wave ();
let rand = Random.int (Array.length paterns) in
paterns.(rand) ()
(* Maj les asteorids *)
let remove_old_asteroids =
let valid_pos =
Box.invisible "valid_pos" (-Global.width / 2) (-Global.height)
(2 * Global.width) (2 * Global.height)
in
let bot_mid_screen =
Box.invisible "bot_mid_screen" 0
(3 * Global.height / 4)
Global.width (Global.height / 4)
in
(* si collision avec zone d'affichage, alors ils sont encore visibles donc on les garde
sinon ils sont hors écrans et on les vire *)
fun () ->
if !Global.no_spawn then ()
else begin
let asteroids_required =
min (max 1 (int_of_float (Global.gravity ()))) 32
in
let cpt = ref Entities.asteroids#length in
let old =
Hashtbl.fold
(fun k v init ->
if
Rect.intersect v#pos#get v#rect#get bot_mid_screen#pos#get
bot_mid_screen#rect#get
then decr cpt;
if
Rect.intersect v#pos#get v#rect#get valid_pos#pos#get
valid_pos#rect#get
then init
else (k, v) :: init )
Entities.asteroids#table []
in
List.iter
(fun (k, v) ->
Entities.asteroids#remove k;
v#is_offscreen#set true )
old;
if !cpt < asteroids_required then init_asteroids ()
end
|
import {
ConnectWallet,
MediaRenderer,
useContract,
useContractMetadata,
useUser,
useOwnedNFTs,
useAddress,
useClaimNFT, Web3Button
} from "@thirdweb-dev/react";
import { ThirdwebSDK } from "@thirdweb-dev/sdk";
import { useRouter } from "next/router";
import { useEffect } from "react";
import { getUser } from "../../auth.config";
import { contractAddress } from "../../const/yourDetails";
import { Header } from "../components/Header";
import styles from "../styles/Home.module.css";
import checkBalance from "../util/checkBalance";
import { ethers } from 'ethers';
import ExclusiveContent from "./exclusiveContent";
export default function Home() {
const { isLoggedIn, isLoading } = useUser();
const router = useRouter();
const { contract } = useContract(contractAddress);
const { data: contractMetadata, isLoading: contractLoading } =
useContractMetadata(contract);
const address = useAddress();
const { data: nfts } = useOwnedNFTs(contract, address);
const {
mutate: claimNFT,error} = useClaimNFT(contract);
if (error) {
console.error("failed to claim nft", error);
}
useEffect(() => {
console.log("adderss ",address,isLoggedIn)
if (!address) {
router.push("/login");
}
}, [isLoading, isLoggedIn, router]);
return (
<div className={styles.container}>
<Header />
<br /><br />
{ address?
(<span>Welcome, {address.slice(0,6)}... </span>
):
<p></p>
}
{!nfts?.length && !contractLoading ? (
<div>
<div className={styles.card}>
<p>To access this content, you need:</p>
{contractMetadata && (
<div className={styles.nft}>
<MediaRenderer
src={contractMetadata.image}
alt={contractMetadata.name}
width="70px"
height="70px"
/>
<div className={styles.nftDetails}>
<h4>{contractMetadata.name}</h4>
<p>Please support our work by buying this NFT</p>
</div>
</div>
)}
{contractLoading && <p>Loading...</p>}
<Web3Button
contractAddress={contractAddress}
action={() =>
claimNFT({
to: address, // Use useAddress hook to get current wallet address
quantity: ethers.BigNumber.from(1),
tokenId: 0
})
}>
Buy NFT
</Web3Button>
</div>
</div>
) :
contractLoading ? (
// User has NFTs but contractMetadata is not ready yet
<p>Loading...</p>
) :
<div className={styles.card}>
<h3>Thank You for your support, here's the Premium content!</h3>
<p>Your NFT unlocked access to this content.</p>
{contractMetadata && (
<div className={styles.nft}>
<MediaRenderer
src={contractMetadata.image}
alt={contractMetadata.name}
width="70px"
height="70px"
/>
<div className={styles.nftDetails}>
<h4>{contractMetadata.name}</h4>
<p>{contractMetadata.description}</p>
</div>
</div>
)}
<ExclusiveContent/>
{contractLoading && <p>Loading...</p>}
<ConnectWallet theme="dark" className={styles.connect } btnTitle="mamama" />
</div>
}
</div>
);
}
// This gets called on every request
export async function getServerSideProps(context) {
const user = await getUser(context.req);
if (!user) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}
const secretKey = process.env.TW_SECRET_KEY;
if (!secretKey) {
console.log("Missing env var: TW_SECRET_KEY");
throw new Error("Missing env var: TW_SECRET_KEY");
}
// Ensure we are able to generate an auth token using our private key instantiated SDK
const PRIVATE_KEY = process.env.THIRDWEB_AUTH_PRIVATE_KEY;
if (!PRIVATE_KEY) {
throw new Error("You need to add an PRIVATE_KEY environment variable.");
}
// Instantiate our SDK
const sdk = ThirdwebSDK.fromPrivateKey(
process.env.THIRDWEB_AUTH_PRIVATE_KEY,
"mumbai",
{ secretKey }
);
// Check to see if the user has an NFT
// const hasNft = await checkBalance(sdk, user.address);
// console.log("has nft ",hasNft)
// // If they don't have an NFT, redirect them to the login page
// if (!hasNft) {
// console.log("no nfts,redirecting")
// return {
// redirect: {
// destination: "/claim",
// permanent: false,
// },
// };
// }
// Finally, return the props
return {
props: {},
};
}
|
import os
import cv2
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models
from sklearn.model_selection import train_test_split
from tensorflow.keras.preprocessing.image import ImageDataGenerator
def load_and_preprocess_data(data_dir, image_size=(128, 128)):
images, labels = [], []
for label in os.listdir(data_dir):
label_path = os.path.join(data_dir, label)
for filename in os.listdir(label_path):
img_path = os.path.join(label_path, filename)
img = cv2.imread(img_path)
img = cv2.resize(img, image_size)
img = img / 255.0
images.append(img)
labels.append(int(label))
return np.array(images), np.array(labels)
data_dir = "E:\dataset\logos2"
images, labels = load_and_preprocess_data(data_dir)
train_images, test_images, train_labels, test_labels = train_test_split(images, labels, test_size=0.2, random_state=42)
data_augmentation = ImageDataGenerator(
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest'
)
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(data_augmentation.flow(train_images, train_labels, batch_size=32), epochs=20, validation_data=(test_images, test_labels))
test_loss, test_accuracy = model.evaluate(test_images, test_labels)
print(f"Test Accuracy: {test_accuracy * 100:.2f}%")
model.save("fake_logo_detection_model.h5")
|
/** \file gps.h
* \ingroup hwmodule
* \brief Serial SLUGS Module
*
* SLUGS Module for RHD.
*
* Based on HAKOD by Asbjørn Mejnertsen and Anders Reeske Nielsen
* and AuGps by Lars Mogensen and Christian Andersen
* GPS module by Anders Billesø Beck
*
* \author Jonathan Løwert
* $Rev: 59 $
* $Date: 2009-12-21 14:12:33 +0200 (Mon, 21 Dec 2009) $
*/
/***************************************************************************
* Copyright 2009 Jonathan Løwert *
* jonathan@lowert.dk *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation; either version 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 Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser 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. *
***************************************************************************/
This is the definition file for the the UCSC AP code
it creates all the common defines, unions, enumerations
and data types.
Code by: Mariano I. Lizarraga
First Revision: Aug 18 2008 @ 17:42
#ifndef SLUGS_H
#define SLUGS_H
int initXML(char *filename);
#ifdef __cplusplus
extern "C"{
#endif
// Circular Buffer Size
#ifdef __cplusplus
#define BSIZE 1024
#else
#define BSIZE 512
#endif
// GPS Checksum Messages
#define GGACS 86
#define RMCCS 75
// GPS Header IDs
#define GGAID 1
#define RMCID 2
#define UNKID 254
// GPS Circular Buffers
#define MSIZE 150
//#define CSIZE 26 //[newBytes payload remaingBytes] (comms buffer out of readGPS)
// Data Logger Values
#define LOGSEND 8
#define MAXSEND 103
#define MAXLOGSEND 56
#ifdef __cplusplus
#define MAXLOGLEN 500
#else
#define MAXLOGLEN 99
#endif
// Define log raw data at 100 hz. Comment out to have
// XYZ data come at 100 Hz instead. COMMENT not Change to 0 (using #ifdef)
//#define LOGRAW100 1
// Define diagnostic data at 100 hz. Comment out to have
// XYZ data come at 100 Hz instead. COMMENT not Change to 0 (using #ifdef)
#define DIAG100 1
// Message Protocol Lengths and IDs
// SENSOR MCU
// ==========
#define GPS_START 0
#define GPSMSG_ID 1
#define GPSMSG_LEN 27
#define LOAD_START 27
#define LOADMSG_ID 2
#define LOADMSG_LEN 4
#define RAW_START 31
#define RAWMSG_ID 3
#define RAWMSG_LEN 26
#define ATT_START 49
#define ATTMSG_ID 4
#define ATTMSG_LEN 26
#define XYZ_START 75
#define XYZMSG_ID 11
#define XYZMSG_LEN 24
#define DYN_START 99
#define DYNMSG_ID 5
#define DYNMSG_LEN 10
#define BIA_START 109
#define BIAMSG_ID 6
#define BIAMSG_LEN 24
#define DIA_START 133
#define DIAMSG_ID 7
#define DIAMSG_LEN 18
#define HIL_START 151
#define PIL_START 152
#define PILMSG_ID 9
#define PILMSG_LEN 10
#define SENMSG_ID 25
#define SENMSG_LEN 24
#define LOGMSG_ID 26
#define LOGMSG_LEN 24
// CONTROL MCU
#define AKNMSG_ID 105
#define AKNMSG_LEN 6
#define PWMMSG_ID 100
#define PWMMSG_LEN 20
#define CALMSG_ID 102
#define CALMSG_LEN 17
#define APSMSG_ID 101
#define APSMSG_LEN 20
#define NAVMSG_ID 120
#define NAVMSG_LEN 30
// Identifier values for messages that have a type ID
// Calibration and Query type IDs
#define PIDTYPE_ID 1
#define WPSTYPE_ID 2
#define PASTYPE_ID 3
#define COMTYPE_ID 4
// Control Types
#define CTRL_TYPE_MANUAL 1 // Pilot in full control of aircraft
#define CTRL_TYPE_AP_COMM 2 // Low level commands: airspeed, height and turnrate
#define CTRL_TYPE_AP_WP 3 // Waypoint following
#define CTRL_TYPE_PASS 4 // Passthrough the commands from the pilot console
#define CTRL_TYPE_SEL_PIL 5 // Pass some from the pilot and some from the AP
#define CTRL_TYPE_SEL_AP 6
#define PIL_FAILSAFE 6000 // IC direct reading from the pilot console when failsafe is
// is turned ON i.e. the pilot is in control.
// Commands to AP ids
#define COMM_TYPE_HEIGHT 1
#define COMM_TYPE_TURNRATE 2
#define COMM_TYPE_AIRSPEED 3
#define COMM_TYPE_GOTO_WP 4
// ERROR MESSAGES
// PID EEPROM Error Messages
#define PIDEEP_WRITE_FAIL 11
#define PIDEEP_PAGE_EXP 12
#define PIDEEP_MEMORY_CORR 13
// WP EEPROM Error Messages
#define WPSEEP_WRITE_FAIL 21
#define WPSEEP_PAGE_EXP 22
#define WPSEEP_MEMORY_CORR 23
// EEPROM Emulation Address Offsets
#define PID_OFFSET 0
#define WPS_OFFSET 60
// Communication Protocol Merging Offsets
#define GSMSG_IDX 99
#define AKMSG_IDX 202
// Standard characters used in the parsing of messages
#define DOLLAR 36
#define STAR 42
#define CR 13
#define LF 10
#define AT 64
// Interprocessor Communication
#define BEGINSPI 0xFFFF
#define ENDSPI 0xBEEF
#define SPIBUFSIZE 46
// Standard Units
#define KTS2MPS 0.514444444
#define PI 3.141592653589793
#define DEG2RAD 0.017453292519943
#define RAD2DEG 57.29577951308232
// Periphereal Configurations
#define APFCY 40000000
#define GPSBAUDF 19200
#define GPSBAUDI 4800
#define UCSCAP_UBRGF 129
#define UCSCAP_UBRGI 520
#define LOGBAUD 115200
#define LOG_UBRG 21
#define LOGMAT_BAUD 57600
#define LOGOMAT_UBRG 42
// ifdef switches for debugging and conditional inclusion
#define __IN_DSPIC__ 1 // switch for use in PC
#if __IN_DSPIC__
#ifdef DEBUG
#undef DEBUG
#endif
#else
#define DEBUG 1
#endif
// Uncomment if there is no magentometers
//#define NO_MAGNETO
// Uncomment to allow full gyro calibration
#define DO_FULL_CALL
//Type definitions for standard unions used in sending
// and receiving data
typedef union{
unsigned char chData[2];
unsigned short usData;
} tUnsignedShortToChar;
typedef union{
unsigned char chData[2];
short shData;
} tShortToChar;
typedef union{
unsigned char chData[4];
unsigned int uiData;
} tUnsignedIntToChar;
typedef union{
unsigned char chData[4];
int inData;
} tIntToChar;
typedef union{
unsigned char chData[4];
float flData;
unsigned short shData[2];
} tFloatToChar;
typedef struct tGpsData{
unsigned char year;
unsigned char month;
unsigned char day;
unsigned char hour;
unsigned char min;
unsigned char sec;
tFloatToChar lat;
tFloatToChar lon;
tFloatToChar height;
tUnsignedShortToChar cog;
tUnsignedShortToChar sog;
tUnsignedShortToChar hdop;
unsigned char fix;
unsigned char sats;
unsigned char newValue;
}tGpsData;
typedef struct tRawData{
tShortToChar gyroX;
tShortToChar gyroY;
tShortToChar gyroZ;
tShortToChar accelX;
tShortToChar accelY;
tShortToChar accelZ;
tShortToChar magX;
tShortToChar magY;
tShortToChar magZ;
// included in SLUGS MKII
tShortToChar baro;
tShortToChar pito;
tShortToChar powr;
tShortToChar ther;
}tRawData;
typedef struct tAttitudeData{
tFloatToChar roll;
tFloatToChar pitch;
tFloatToChar yaw;
tFloatToChar p;
tFloatToChar q;
tFloatToChar r;
tUnsignedShortToChar timeStamp;
}tAttitudeData;
typedef struct tSensStatus{
char load;
char vdetect;
tUnsignedShortToChar bVolt;
}tSensStatus;
typedef struct tDynTempData{
tFloatToChar dynamic;
tFloatToChar stat;
tShortToChar temp;
}tDynTempData;
typedef struct tBiasData{
tFloatToChar axb;
tFloatToChar ayb;
tFloatToChar azb;
tFloatToChar gxb;
tFloatToChar gyb;
tFloatToChar gzb;
}tBiasData;
typedef struct tDiagData{
tFloatToChar fl1;
tFloatToChar fl2;
tFloatToChar fl3;
tShortToChar sh1;
tShortToChar sh2;
tShortToChar sh3;
}tDiagData;
typedef struct tXYZData{
tFloatToChar Xcoord;
tFloatToChar Ycoord;
tFloatToChar Zcoord;
tFloatToChar VX;
tFloatToChar VY;
tFloatToChar VZ;
}tXYZData;
typedef struct tAknData{
unsigned char WP;
unsigned char commands;
unsigned char pidCal;
unsigned char sensorReboot;
unsigned char filOnOff;
unsigned char reboot;
}tAknData;
typedef struct tPilotData{
tUnsignedShortToChar dt ;
tUnsignedShortToChar dla;
tUnsignedShortToChar dra;
tUnsignedShortToChar dr ;
tUnsignedShortToChar de ;
}tPilotData;
typedef struct tPWMData{
tUnsignedShortToChar dt_c;
tUnsignedShortToChar dla_c;
tUnsignedShortToChar dra_c;
tUnsignedShortToChar dr_c;
tUnsignedShortToChar dle_c;
tUnsignedShortToChar dre_c;
tUnsignedShortToChar dlf_c;
tUnsignedShortToChar drf_c;
tUnsignedShortToChar da1_c;
tUnsignedShortToChar da2_c;
}tPWMData;
typedef struct tPIDData{
tFloatToChar P[10];
tFloatToChar I[10];
tFloatToChar D[10];
}tPIDData;
typedef struct tQueryData{
unsigned char pendingRequest;
unsigned char idReq;
unsigned char indxReq;
}tQueryData;
typedef struct tWPData{
tFloatToChar lat[11];
tFloatToChar lon[11];
tFloatToChar hei[11];
unsigned char typ[11];
tShortToChar val[11];
unsigned char wpCount;
}tWPData;
typedef struct tCommandsData{
tFloatToChar hCommand;
tFloatToChar airspeedCommand;
tFloatToChar phiCommand;
tFloatToChar thetaCommand;
tFloatToChar psiCommand;
tFloatToChar pCommand;
tFloatToChar qCommand;
tFloatToChar rCommand;
char currWPCommand;
char nextWPCommand;
}tCommandsData;
typedef struct tAPStatusData{
unsigned char controlType;
unsigned char beaconStatus;
unsigned char hilStatus;
unsigned char dt_pass;
unsigned char dla_pass;
unsigned char dra_pass;
unsigned char dr_pass;
unsigned char dle_pass;
unsigned char dre_pass;
unsigned char dlf_pass;
unsigned char drf_pass;
}tAPStatusData;
typedef struct tCubeBuffer {
tShortToChar ax[4];
tShortToChar ay[4];
tShortToChar az[4];
tShortToChar gx[4];
tShortToChar gy[4];
tShortToChar gz[4];
unsigned char sampleCount;
}tCubeBuffer;
typedef struct tNavData {
tFloatToChar uMeasured;
tFloatToChar thetaCommanded;
tFloatToChar psiDotCommanded;
tFloatToChar phiCommanded;
tFloatToChar rHighPass;
tFloatToChar totRun;
tFloatToChar distance2Go;
unsigned char fromWp;
unsigned char toWp;
}tNavData;
typedef struct tSensData{
tFloatToChar Ax;
tFloatToChar Ay;
tFloatToChar Az;
tFloatToChar Mx;
tFloatToChar My;
tFloatToChar Mz;
}tSensData;
typedef struct tLogFloats{
tFloatToChar fl1;
tFloatToChar fl2;
tFloatToChar fl3;
tFloatToChar fl4;
tFloatToChar fl5;
tFloatToChar fl6;
}tLogFloats;
*/
//----------CircBuffer.h------------------
# if __IN_DSPIC__
typedef struct CircBuffer{
unsigned char buffer[BSIZE];
int head;
int tail;
unsigned int size;
unsigned char overflowCount;
}CircBuffer;
#else
typedef struct CircBuffer{
unsigned char* buffer;
int head;
int tail;
unsigned int size;
unsigned char overflowCount;
}CircBuffer;
#endif
// Exported Types
typedef struct CircBuffer* CBRef;
// Constructors - Destructors
// this Function returns a pointer to a new Circular Buffer of size pm_size
#if __IN_DSPIC__
void newCircBuffer (CBRef cB);
#else
CBRef newCircBuffer (int pm_size);
#endif
// this function frees the Circular Buffer CB Ref
void freeCircBuffer (CBRef* cB);
// Accesor Methods
// returns the amount of unread bytes in the circular buffer
unsigned int getLength (CBRef cB);
// returns the actual index of the head
int readHead (CBRef cB);
// returns the actual index of the tail
int readTail (CBRef cB);
// returns the byte (actual value) that the head points to. this
// does not mark the byte as read, so succesive calls to peak will
// always return the same value
unsigned char peak(CBRef cB);
// Manipulation Procedures
// returns the front of the circular buffer and marks the byte as read
unsigned char readFront (CBRef cB);
// writes one byte at the end of the circular buffer, returns 1 if overflow occured
unsigned char writeBack (CBRef cB, unsigned char data);
// empties the circular buffer. It does not change the size. use with caution!!
void makeEmpty (CBRef cB);
// returns the amount of times the CB has overflown;
unsigned char getOverflow(CBRef cB);
//Convertions
//Type definitions for standard unions used in sending
// and receiving data
typedef union{
unsigned char chData[2];
unsigned short usData;
} tUnsignedShortToChar;
typedef union{
unsigned char chData[2];
short shData;
} tShortToChar;
typedef union{
unsigned char chData[4];
unsigned int uiData;
} tUnsignedIntToChar;
typedef union{
unsigned char chData[4];
int inData;
} tIntToChar;
typedef union{
unsigned char chData[4];
float flData;
unsigned short shData[2];
} tFloatToChar;
#if DEBUG
// Other Functions
// prints the circular buffer, used for debug
void printCircBuf(CBRef cB);
#endif /* DEBUG */
#ifdef __cplusplus
}
#endif
#endif
|
import { ChangeEvent, useCallback, useState } from "react"
export const useInput = (validate: (value: string) => boolean) => {
const [value, setValue] = useState('')
const [isTouched, setIsTouched] = useState(false);
const isValid = validate(value)
const hasError = !isValid && isTouched;
const changeHandler = useCallback((e: ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value)
}, [])
const blurHandler = useCallback(() => {
setIsTouched(true)
}, []);
const reset = useCallback(() => {
setValue('');
setIsTouched(false)
}, []);
return { value, isValid, hasError, changeHandler, blurHandler, reset }
}
|
/// <reference types="@nasl/types" />
namespace nasl.ui {
@Component({
title: '穿梭框',
icon: 'transfer',
description: '双栏穿梭选择框,常用于将多个项目从一边移动到另一边。',
group: 'Selector',
})
export class Transfer<T, V> extends ViewComponent {
// @Method({
// title: 'undefined',
// description: '从左向右转移数据。',
// })
// forward(
// @Param({
// title: 'undefined',
// description: '指定转移选项值的列表。如果不填,则为按左列表框选中项值的列表。',
// })
// values: Array<nasl.core.String>,
// ): void {}
// @Method({
// title: 'undefined',
// description: '从右向左转移数据。',
// })
// reverse(
// @Param({
// title: 'undefined',
// description: '指定转移选项值的列表。如果不填,则为按右列表框选中项值的列表。',
// })
// values: Array<nasl.core.String>,
// ): void {}
// @Method({
// title: 'undefined',
// description: '转移指定项的数据。',
// })
// transfer(
// @Param({
// title: 'undefined',
// description: '方向',
// })
// direction: 'forward' | 'reverse' = 'forward',
// @Param({
// title: 'undefined',
// description: '指定转移选项值的列表。',
// })
// values: Array<nasl.core.String>,
// ): void {}
constructor(options?: Partial<TransferOptions<T, V>>) {
super();
}
}
export class TransferOptions<T, V> extends ViewComponentOptions {
@Prop({
title: '过滤匹配方法',
description: '过滤时的匹配方法',
})
private matchMethod: nasl.core.String = 'includes';
@Prop({
title: '分页',
description: '是否需要分页',
setter: {
concept: 'SwitchSetter',
},
})
private pagination: nasl.core.Boolean = false;
// @Prop({
// title: '分页大小',
// setter: {
// concept: 'NumberInputSetter',
// },
// })
// private pageSize: nasl.core.Integer = 50;
@Prop({
group: '数据属性',
title: '原始数据',
description: '原数据列表',
sync: true,
docDescription: '支持动态绑定集合类型变量(List<T>)或输出参数为集合类型的逻辑。',
})
source: nasl.collection.List<T>;
@Prop({
group: '数据属性',
title: '目标数据',
description: '目标数据列表',
sync: true,
docDescription: '支持动态绑定集合类型变量(List<T>)或输出参数为集合类型的逻辑。',
})
target: nasl.collection.List<T>;
@Prop({
group: '数据属性',
title: '文本字段',
description: '选项文本的字段名',
docDescription: '集合的元素类型中,用于显示文本的属性名称,支持自定义变更。',
})
textField: (item: T) => any = ((item: any) => item.text) as any;
@Prop({
group: '数据属性',
title: '值字段',
description: '选项值的字段名',
docDescription: '集合的元素类型中,用于指定数据唯一值的字段,支持自定义变更',
})
valueField: (item: T) => V = ((item: any) => item.text) as any;
@Prop({
group: '数据属性',
title: '筛选',
description: '显示筛选(搜索框)',
docDescription: '是否开启过滤输入框和过滤功能。默认关闭',
setter: {
concept: 'SwitchSetter',
},
})
showSearch: nasl.core.Boolean = false;
// @Prop<TransferOptions<T, V>, 'caseSensitive'>({
// group: '数据属性',
// title: '大小写敏感',
// description: '设置是否区分大小写',
// docDescription: '搜索是否大小写敏感。默认关闭。在过滤属性开启后有效。',
// setter: {
// concept: 'SwitchSetter',
// },
// if: _ => _.filterable === true,
// })
// caseSensitive: nasl.core.Boolean = false;
// @Prop<TransferOptions<T, V>, 'clearable'>({
// group: '数据属性',
// title: '可清除筛选',
// description: '可点击清除按钮一键清除搜索框内容',
// docDescription: '过滤输入框是否开启清除按钮。默认开启。在过滤属性开启后有效',
// setter: {
// concept: 'SwitchSetter',
// },
// if: _ => _.filterable === true,
// })
// clearable: nasl.core.Boolean = false;
@Prop({
group: '主要属性',
title: '显示头部',
docDescription: '开启后会显示头部全选栏。默认开启',
setter: {
concept: 'SwitchSetter',
},
})
showSelectAll: nasl.core.Boolean = true;
@Prop({
group: '主要属性',
title: '左侧列表标题',
docDescription: '- 左侧头部全选框右侧展示的文字。默认为“左列表”。',
})
sourceTitle: nasl.core.String = '列表';
@Prop({
group: '主要属性',
title: '右侧列表标题',
docDescription: '右侧头部全选框右侧展示的文字。默认为“右列表”',
})
targetTitle: nasl.core.String = '列表';
// @Prop<TransferOptions<T, V>, 'placeholder'>({
// group: '主要属性',
// title: '占位符',
// description: '为空时显示的占位符文本',
// docDescription: '过滤输入框无内容时的提示信息,支持自定义编辑,默认为请选择。在过滤属性开启后有效',
// if: _ => _.filterable === true,
// })
// placeholder: nasl.core.String = '请输入';
// @Prop({
// group: '状态属性',
// title: '只读',
// description: '正常显示,但禁止选择/输入',
// docDescription: '正常显示,但禁止选择或输入',
// setter: {
// concept: 'SwitchSetter',
// },
// })
// readonly: nasl.core.Boolean = false;
@Prop({
group: '状态属性',
title: '禁用',
description: '置灰显示,且禁止任何交互(焦点、点击、选择、输入等)',
docDescription: '置灰显示,且禁止任何交互(焦点、点击、选择、输入等)',
setter: {
concept: 'SwitchSetter',
},
})
disabled: nasl.core.Boolean = false;
@Event({
title: '数据转移时',
description: '数据转移时触发',
})
onChange: (event: { targetKeys: nasl.collection.List<T>; direction: nasl.collection.List<T>; moveKeys: nasl.collection.List<T> }) => any;
@Slot({
title: '默认',
description: '插入文本或 HTML',
})
slotDefault: () => Array<ViewComponent>;
@Slot({
title: '项',
description: '自定义选项的结构和样式',
})
slotRender: (current: Current<T>) => Array<ViewComponent>;
}
}
|
"""
Skeleton code for Project 1 of Columbia University's AI EdX course (8-puzzle).
Python 3
"""
import queue as Q
import time
import resource
import sys
import math
import heapq
class PuzzleState(object):
"""docstring for PuzzleState"""
def __init__(self, config, n, parent=None, action="Initial", cost=0):
if n*n != len(config) or n < 2:
raise Exception("the length of config is not correct!")
self.n = n
self.cost = cost
self.parent = parent
self.action = action
self.dimension = n
self.config = config
self.children = []
for i, item in enumerate(self.config):
if item == 0:
self.blank_row = i // self.n
self.blank_col = i % self.n
break
def __lt__(self, other):
return calculate_total_cost(self) < calculate_total_cost(other)
def display(self):
for i in range(self.n):
line = []
offset = i * self.n
for j in range(self.n):
line.append(self.config[offset + j])
print(line)
def move_left(self):
if self.blank_col == 0:
return None
else:
blank_index = self.blank_row * self.n + self.blank_col
target = blank_index - 1
new_config = list(self.config)
new_config[blank_index], new_config[target] = new_config[target], new_config[blank_index]
return PuzzleState(tuple(new_config), self.n, parent=self, action="Left", cost=self.cost + 1)
def move_right(self):
if self.blank_col == self.n - 1:
return None
else:
blank_index = self.blank_row * self.n + self.blank_col
target = blank_index + 1
new_config = list(self.config)
new_config[blank_index], new_config[target] = new_config[target], new_config[blank_index]
return PuzzleState(tuple(new_config), self.n, parent=self, action="Right", cost=self.cost + 1)
def move_up(self):
if self.blank_row == 0:
return None
else:
blank_index = self.blank_row * self.n + self.blank_col
target = blank_index - self.n
new_config = list(self.config)
new_config[blank_index], new_config[target] = new_config[target], new_config[blank_index]
return PuzzleState(tuple(new_config), self.n, parent=self, action="Up", cost=self.cost + 1)
def move_down(self):
if self.blank_row == self.n - 1:
return None
else:
blank_index = self.blank_row * self.n + self.blank_col
target = blank_index + self.n
new_config = list(self.config)
new_config[blank_index], new_config[target] = new_config[target], new_config[blank_index]
return PuzzleState(tuple(new_config), self.n, parent=self, action="Down", cost=self.cost + 1)
def expand(self):
"""expand the node"""
# add child nodes in order of UDLR
if len(self.children) == 0:
up_child = self.move_up()
if up_child is not None:
self.children.append(up_child)
down_child = self.move_down()
if down_child is not None:
self.children.append(down_child)
left_child = self.move_left()
if left_child is not None:
self.children.append(left_child)
right_child = self.move_right()
if right_child is not None:
self.children.append(right_child)
return self.children
def writeOutput(path, cost, nodes, depth, max_depth, run_time, memory):
lines = []
lines.append("path_to_goal: " + str(path))
lines.append("\ncost_of_path: " + str(cost))
lines.append("\nnodes_expanded: " + str(nodes))
lines.append("\nsearch_depth: " + str(depth))
lines.append("\nmax_search_depth: " + str(max_depth))
lines.append("\nrunning_time: " + str(run_time))
lines.append("\nmax_ram_usage: " + str(memory))
output = open("output.txt", "w")
output.writelines(lines)
output.close()
def get_path(state):
actions = []
while state.action is not 'Initial':
actions.insert(0, state.action)
state = state.parent
return actions
def bfs_search(initial_state):
start_time = time.time()
start_mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
curr_mem = 0
max_mem = 0
frontier = [initial_state]
frontier_set = {initial_state.config}
explored = set()
max_depth = 0
while len(frontier) > 0:
curr_mem = (resource.getrusage(
resource.RUSAGE_SELF).ru_maxrss) - start_mem
if curr_mem > max_mem:
max_mem = curr_mem
state = frontier.pop(0)
frontier_set.remove(state.config)
explored.add(state.config)
if goal_test(state):
run_time = time.time() - start_time
path = get_path(state)
depth = state.cost
return writeOutput(path, state.cost, len(explored)-1, depth, max_depth, run_time, max_mem / 1000000)
for neighbor in state.expand():
if neighbor.config not in explored and neighbor.config not in frontier_set:
if neighbor.cost > max_depth:
max_depth = neighbor.cost
frontier.append(neighbor)
frontier_set.add(neighbor.config)
return print("Failure")
def dfs_search(initial_state):
start_time = time.time()
start_mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
curr_mem = 0
max_mem = 0
frontier = [initial_state]
frontier_set = {initial_state.config}
explored = set()
max_depth = 0
while len(frontier) > 0:
curr_mem = (resource.getrusage(
resource.RUSAGE_SELF).ru_maxrss) - start_mem
if curr_mem > max_mem:
max_mem = curr_mem
state = frontier.pop()
frontier_set.remove(state.config)
explored.add(state.config)
if goal_test(state):
run_time = time.time() - start_time
path = get_path(state)
depth = state.cost
return writeOutput(path, state.cost, len(explored)-1, depth, max_depth, run_time, max_mem / 1000000)
neighbors = state.expand()
neighbors.reverse()
for neighbor in neighbors:
if neighbor.cost > max_depth:
max_depth = neighbor.cost
if neighbor.config not in explored and neighbor.config not in frontier_set:
frontier.append(neighbor)
frontier_set.add(neighbor.config)
return print("Failure")
def A_star_search(initial_state):
start_time = time.time()
start_mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
curr_mem = 0
max_mem = 0
frontier = []
heapq.heappush(frontier, initial_state)
frontier_set = {initial_state.config}
explored = set()
max_depth = 0
while len(frontier) > 0:
curr_mem = (resource.getrusage(
resource.RUSAGE_SELF).ru_maxrss) - start_mem
if curr_mem > max_mem:
max_mem = curr_mem
state = heapq.heappop(frontier)
frontier_set.remove(state.config)
explored.add(state.config)
if goal_test(state):
run_time = time.time() - start_time
path = get_path(state)
depth = state.cost
return writeOutput(path, state.cost, len(explored)-1, depth, max_depth, run_time, max_mem / 1000000)
for neighbor in state.expand():
if neighbor.cost > max_depth:
max_depth = neighbor.cost
if neighbor.config not in explored and neighbor.config not in frontier_set:
heapq.heappush(frontier, neighbor)
frontier_set.add(neighbor.config)
elif neighbor.config in frontier_set:
# calc new total cost and replace in heap if less than existing cost
existing_state = next(
(x for x in frontier if x.config == neighbor.config), None)
if (calculate_total_cost(neighbor) < calculate_total_cost(existing_state)):
frontier.remove(existing_state)
heapq.heappush(frontier, neighbor)
return print("Failure")
def calculate_total_cost(state):
return state.cost + calculate_manhattan_dist(state)
def calculate_manhattan_dist(state):
initial_config = state.config
dist = 0
i = 0
while i < len(initial_config):
curr_row = int(i / 3)
curr_col = i % 3
goal_row = int(initial_config[i] / 3)
goal_col = initial_config[i] % 3
dist += abs(curr_row - goal_row) + abs(curr_col - goal_col)
i += 1
return dist
def goal_test(puzzle_state):
"""test the state is the goal state or not"""
if puzzle_state.config == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return True
else:
return False
# Main Function that reads in Input and Runs corresponding Algorithm
def main():
sm = sys.argv[1].lower()
begin_state = sys.argv[2].split(",")
begin_state = tuple(map(int, begin_state))
size = int(math.sqrt(len(begin_state)))
hard_state = PuzzleState(begin_state, size)
if sm == "bfs":
bfs_search(hard_state)
elif sm == "dfs":
dfs_search(hard_state)
elif sm == "ast":
A_star_search(hard_state)
else:
print("Enter valid command arguments !")
if __name__ == '__main__':
main()
|
import { INCREMENT, DECREMENT, RESET, GET_POST, RECEIVE_POST } from "./actionsTypes";
import axios from 'axios';
export function increment() {
return { type: INCREMENT };
}
export function decrement() {
return { type: DECREMENT };
}
export function reset() {
return { type: RESET };
}
export function getPost() {
return { type: GET_POST };
}
export function receivePost(dato) { //* accion sincrona
return { type: RECEIVE_POST, payload: dato };
}
export function fetchPost(valor) { //* accion asincrona
return function(dispatch) {
dispatch(getPost());
axios(`https://jsonplaceholder.typicode.com/todos/${valor}`)
.then(({data}) => {
// console.log(data)
return dispatch(receivePost(data))
})
}
}
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# password_digest :string(255)
# remember_token :string(255)
# admin :boolean default(FALSE)
#
require 'spec_helper'
describe User do
before {@user = User.new(name: 'Example user', email: 'user@example.com',
password: 'foobar', password_confirmation: 'foobar')}
subject {@user}
it {should respond_to :name}
it {should respond_to :email}
it {should respond_to :password_digest}
it {should respond_to :password}
it {should respond_to :password_confirmation}
it {should respond_to :remember_token}
it {should respond_to :admin}
it {should respond_to :authenticate}
it {should respond_to :microposts}
it {should respond_to :feed}
it {should respond_to :relationships}
it {should respond_to :followed_users}
it {should respond_to :reverse_relationships}
it {should respond_to :followers}
it {should respond_to :following?}
it {should respond_to :follow!}
it {should respond_to :unfollow!}
it {should be_valid}
it {should_not be_admin}
describe 'whith admin atribute set to true' do
before do
@user.save!
@user.toggle!(:admin)
end
it {should be_admin}
end
describe "when name is not present" do
before {@user.name = " "}
it {should_not be_valid}
end
describe "when name is to long" do
before {@user.name = "a" * 51}
it {should_not be_valid}
end
describe "when email is not present" do
before {@user.email = " "}
it {should_not be_valid}
end
describe "when email format is invalid" do
it "should be invalid" do
addresses = %w[user@foo,com user_at_foo.org example.user@foo.
foo@bar_baz.com foo@bar+baz.com]
addresses.each do |invalid_address|
@user.email = invalid_address
@user.should_not be_valid
end
end
end
describe "when email format is valid" do
it "should be valid" do
addresses = %w[user@foo.COM A_US-ER@f.b.org frst.lst@foo.jp a+b@baz.cn]
addresses.each do |valid_address|
@user.email = valid_address
@user.should be_valid
end
end
end
describe "when email address is already taken" do
before do
user_with_the_same_email = @user.dup
user_with_the_same_email.save
end
it {should_not be_valid}
end
describe "when email address is already taken" do
before do
user_with_the_same_email = @user.dup
user_with_the_same_email.email = @user.email.upcase
user_with_the_same_email.save
end
it {should_not be_valid}
end
describe "when password is not present" do
before {@user.password = @user.password_confirmation = " "}
it {should_not be_valid}
end
describe "when password confirmation is nil" do
before {@user.password_confirmation = nil}
it {should_not be_valid}
end
describe "when a password is to short" do
before {@user.password = @user.password_confirmation = "a" * 5}
it {should be_invalid}
end
describe "return value of authenticate method" do
before {@user.save}
let(:found_user) {User.find_by_email @user.email}
describe "with valid email" do
it {should == found_user.authenticate(@user.password)}
end
describe "with invalid password" do
let(:user_for_invalid_password) {found_user.authenticate "invalid"}
it {should_not == user_for_invalid_password}
specify {user_for_invalid_password.should be_false}
end
end
describe "email address with mixed case" do
let(:mixed_case_email) { "Foo@ExAMPle.CoM" }
it "should be saved as all lower-case" do
@user.email = mixed_case_email
@user.save
@user.reload.email.should == mixed_case_email.downcase
end
end
describe "remember token" do
before {@user.save}
its(:remember_token) {should_not be_blank}
end
describe 'micropost associations' do
before {@user.save}
let!(:older_micropost) do
FactoryGirl.create(:micropost, user: @user, created_at: 1.day.ago)
end
let!(:newer_micropost) do
FactoryGirl.create(:micropost, user: @user, created_at: 1.hour.ago)
end
it 'should have the right microposts in the right order' do
@user.microposts.should == [newer_micropost, older_micropost]
end
it 'should destroy associated microposts' do
microposts = @user.microposts.dup
@user.destroy
microposts.should_not be_empty
microposts.each do |micropost|
Micropost.find_by_id(micropost.id).should be_nil
end
end
describe 'status' do
let(:unfollowed_post) do
FactoryGirl.create(:micropost, user: FactoryGirl.create(:user))
end
let(:followed_user) {FactoryGirl.create :user}
before do
@user.follow!(followed_user)
3.times {followed_user.microposts.create!(content: 'Lorem ipsum')}
end
its(:feed) {should include newer_micropost}
its(:feed) {should include older_micropost}
its(:feed) {should_not include unfollowed_post}
its(:feed) do
followed_user.microposts.each do |micropost|
should include(micropost)
end
end
end
end
describe 'following' do
let(:other_user) {FactoryGirl.create :user}
before do
@user.save
@user.follow!(other_user)
end
it {should be_following other_user}
its(:followed_users) {should include(other_user)}
describe 'followed user' do
subject {other_user}
its(:followers) {should include(@user)}
end
describe 'and unfollowing' do
before {@user.unfollow! other_user}
it {should_not be_following other_user}
its(:followed_users) {should_not include other_user}
end
end
end
|
import { createContext, useContext, useEffect, useState } from "react";
export const context = createContext();
export const UserContext = ({ children }) => {
const [user, setUser] = useState(null);
const [userImage, setUserImage] = useState(null);
useEffect(() => {
const isLoggedIn = localStorage.getItem("isLoggedIn");
const username = localStorage.getItem("username");
const image = localStorage.getItem("image")
if (isLoggedIn && username) {
setUser(username);
}
if (image) {
setUserImage(image);
}
}, []);
const logIn = (userData) => {
setUser(userData.username);
setUserImage(userData.image);
localStorage.setItem("isLoggedIn", true);
localStorage.setItem("username", userData.username);
localStorage.setItem("image", userData.image)
};
const logOut = () => {
setUser(null);
setUserImage(null);
localStorage.removeItem("isLoggedIn");
localStorage.removeItem("username");
localStorage.removeItem("image");
};
return (
<context.Provider value={{ user, logIn, logOut, userImage }}>
{children}
</context.Provider>
);
};
export const useAuth = () => {
return useContext(context);
};
|
package com.example.demo.service;
import com.example.demo.domain.Member;
import com.example.demo.repository.MemberRepository;
import com.example.demo.repository.MemoryMemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
public class MemberService {
private final MemberRepository memberRepository;
@Autowired
public MemberService(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
/**
* 회원가입
*/
public Long join(Member member) {
//이름 중복 확인
//ctrl+alt+v = 'Optional<Member> byName =' 까지 자동생성
//ctrl+alt+위화살표+L = 줄정렬
//ctrl+alt+m 메서드로 소스코드 따로 분리
validateDuplicateMember(member);
memberRepository.save(member);
return member.getId();
}
private void validateDuplicateMember(Member member) {
memberRepository.findByName(member.getName())
.ifPresent(m -> {
throw new IllegalStateException("이미 존재하는 회원입니다.");
});
}
/**
* 전체 회원 조회
* */
public List<Member> findMembers(){
return memberRepository.findAll();
}
public Optional<Member> findOne(Long memberId){
return memberRepository.findById(memberId);
}
}
|
use ndarray::{linalg, Array2, ArrayD, Axis, Dimension, IxDyn, s, ShapeError};
use num_traits::zero;
use std::any::Any;
use thiserror::Error;
use crate::{activation::Activation, initialization::InitializerType};
/// The `Layer` trait need to be implemented by any nn layer
//
/// a layer is defined as input nodes x and output nodes y, and have two main functions,
/// `feed_forward()` and `propagate_backward()`
///
/// Layer implementations in this library support batch processing, (i.e. processing more than one
/// data point at once).
/// The convention chosen in the layer implementations is (n, features) where n is the number of
/// sample in the batch
pub trait Layer {
fn feed_forward_save(&mut self, input: &ArrayD<f64>) -> Result<ArrayD<f64>, LayerError>;
fn feed_forward(&self, input: &ArrayD<f64>) -> Result<ArrayD<f64>, LayerError>;
fn propagate_backward(
&mut self,
output_gradient: &ArrayD<f64>,
) -> Result<ArrayD<f64>, LayerError>;
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
}
pub trait Trainable {
fn get_parameters(&self) -> Vec<ArrayD<f64>>;
fn get_parameters_mut(&mut self) -> Vec<&mut ArrayD<f64>>;
fn get_gradients(&self) -> Vec<ArrayD<f64>>;
}
pub struct DenseLayer {
weights: ArrayD<f64>,
bias: ArrayD<f64>,
last_batch_input: Option<ArrayD<f64>>,
// store those for optimizer access (from the trait Trainable)
weights_gradient: Option<ArrayD<f64>>,
biases_gradient: Option<ArrayD<f64>>,
input_size: usize,
output_size: usize,
}
impl DenseLayer {
/// Create a new `DenseLayer` filling it with random value. see `InitializerType` for
/// initialization parameters
pub fn new(input_size: usize, output_size: usize, init: InitializerType) -> Self {
Self {
weights: init.initialize(input_size, output_size, &[input_size, output_size]),
bias: init.initialize(input_size, output_size, &[output_size]),
last_batch_input: None,
weights_gradient: None,
biases_gradient: None,
input_size,
output_size,
}
}
}
impl Layer for DenseLayer {
/// Return the output matrices of this `DenseLayer` (shape (n, j)), while storing the input matrices
/// (shape (n, i))
///
/// where **n** is the number of samples, **j** is the layer output size and **i** is the layer
/// input size.
///
/// # Arguments
/// * `input` - shape (n, i)
fn feed_forward_save(&mut self, input: &ArrayD<f64>) -> Result<ArrayD<f64>, LayerError> {
// TODO find a without clone method, like in place mutation
self.last_batch_input = Some(input.clone());
self.feed_forward(input)
}
/// Return the output matrices of this `DenseLayer` (shape (n, j))
///
/// where **n** is the number of samples, **j** is the layer output size.
///
/// # Arguments
/// * `input` - shape (n, i)
fn feed_forward(&self, input: &ArrayD<f64>) -> Result<ArrayD<f64>, LayerError> {
let batch_size = input.shape()[0];
let input_2d = input.view().into_shape((batch_size, self.input_size))?;
let weight_2d = self
.weights
.view()
.into_shape((self.input_size, self.output_size))?;
Ok((input_2d.dot(&weight_2d) + &self.bias).into_dyn())
}
/// Return the input gradient vector (shape (n, i)), by processing the output gradient vector
/// (shape (n, j)).
///
/// This function also compute and store the current batch weights and biases gradient in the layer.
///
/// # Arguments
/// * `input` - (shape (n, i))
/// * `output_gradient` - (shape (n, j))
fn propagate_backward(
&mut self,
output_gradient: &ArrayD<f64>,
) -> Result<ArrayD<f64>, LayerError> {
let input_gradient = match self.last_batch_input.as_ref() {
Some(input) => {
let batch_size = output_gradient.shape()[0];
let output_grad_2d = output_gradient
.view()
.into_shape((batch_size, self.output_size))?;
let input_2d = input.view().into_shape((batch_size, self.input_size))?;
let weight_2d = self
.weights
.view()
.into_shape((self.input_size, self.output_size))?;
// mean relative to the batch
let weights_gradient = input_2d.t().dot(&output_grad_2d) / batch_size as f64;
let biases_gradient = output_grad_2d.sum_axis(Axis(0)) / batch_size as f64;
self.weights_gradient = Some(weights_gradient.to_owned().into_dyn());
self.biases_gradient = Some(biases_gradient.into_dyn());
Ok((output_grad_2d.dot(&weight_2d.t())).into_dyn())
}
None => Err(LayerError::IllegalInputAccess),
};
input_gradient
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
impl Trainable for DenseLayer {
fn get_parameters(&self) -> Vec<ArrayD<f64>> {
vec![
self.weights.clone().into_dyn(),
self.bias.clone().into_dyn(),
]
}
fn get_parameters_mut(&mut self) -> Vec<&mut ArrayD<f64>> {
vec![&mut self.weights, &mut self.bias]
}
fn get_gradients(&self) -> Vec<ArrayD<f64>> {
vec![
self.weights_gradient
.as_ref()
.expect("Illegal access to unset weights gradient")
.clone()
.into_dyn(),
self.biases_gradient
.as_ref()
.expect("Illegal access to unset biases gradient")
.clone()
.into_dyn(),
]
}
}
/// The `ActivationLayer` apply a activation function to it's input node to yield the output nodes.
pub struct ActivationLayer {
pub activation: Activation,
pub input: Option<ArrayD<f64>>,
}
impl ActivationLayer {
pub fn from(activation: Activation) -> Self {
Self {
activation,
input: None,
}
}
}
impl Layer for ActivationLayer {
/// Return a matrices (shape (n, i)) with the activation function applied to a batch
///
/// # Arguments
/// * `input` - shape (n, i)
fn feed_forward_save(&mut self, input: &ArrayD<f64>) -> Result<ArrayD<f64>, LayerError> {
self.input = Some(input.clone());
self.feed_forward(input)
}
/// Return a matrices (shape (n, i)) with the activation function applied to a batch
/// while storing the input for later use in backpropagation process
///
/// # Arguments
/// * `input` - shape (n, i)
fn feed_forward(&self, input: &ArrayD<f64>) -> Result<ArrayD<f64>, LayerError> {
Ok(self.activation.apply(input))
}
/// Return the input gradient (shape (n, i)) of this `ActivationLayer` by processing the output gradient.
/// # Arguments
/// * `output_gradient` shape (n, j)
fn propagate_backward(
&mut self,
output_gradient: &ArrayD<f64>,
) -> Result<ArrayD<f64>, LayerError> {
let input_gradient = match self.input.as_ref() {
Some(input) => Ok(output_gradient * self.activation.apply_derivative(input)),
None => Err(LayerError::IllegalInputAccess),
};
input_gradient
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
pub struct ConvolutionalLayer {
kernels: ArrayD<f64>,
bias: ArrayD<f64>,
input: Option<ArrayD<f64>>,
kernel_gradient: Option<ArrayD<f64>>,
bias_gradient: Option<ArrayD<f64>>,
input_size: (usize, usize, usize),
output_size: (usize, usize, usize),
kernels_size: (usize, usize, usize, usize),
}
impl ConvolutionalLayer {
pub fn new(
input_size: (usize, usize, usize),
kernel_size: (usize, usize),
number_of_kernel: usize,
init: InitializerType,
) -> Self {
let (kernel_height, kernel_width): (usize, usize) = kernel_size;
let (input_height, input_width, input_channel): (usize, usize, usize) = input_size;
let output_size: (usize, usize, usize) = (
input_height - kernel_height + 1,
input_width - kernel_width + 1,
number_of_kernel,
);
let (output_height, output_width, output_channel): (usize, usize, usize) = output_size;
Self {
kernels: init.initialize(
input_height * input_width * input_channel,
output_height * output_width * output_channel,
&[kernel_height, kernel_width, input_channel, number_of_kernel],
),
bias: init.initialize(
input_height * input_width * input_channel,
output_height * output_width * output_channel,
&[number_of_kernel],
),
input: None,
kernel_gradient: None,
bias_gradient: None,
input_size,
output_size,
kernels_size: (kernel_height, kernel_width, input_channel, number_of_kernel),
}
}
fn flip_kernels(&self) -> ArrayD<f64> {
// Ensure the kernels array is 4D
assert_eq!(self.kernels.ndim(), 4);
let kernel_h = self.kernels.shape()[0];
let kernel_w = self.kernels.shape()[1];
let kernel_d = self.kernels.shape()[2];
let num_kernels = self.kernels.shape()[3];
let mut flipped_kernels =
ArrayD::zeros(IxDyn(&[kernel_h, kernel_w, kernel_d, num_kernels]));
for ky in 0..kernel_h {
for kx in 0..kernel_w {
for c in 0..kernel_d {
for nk in 0..num_kernels {
let flipped_ky = kernel_h - 1 - ky;
let flipped_kx = kernel_w - 1 - kx;
flipped_kernels[[flipped_ky, flipped_kx, c, nk]] =
self.kernels[[ky, kx, c, nk]];
}
}
}
}
flipped_kernels
}
fn im2col(&self, input: ArrayD<f64>) -> Array2<f64> {
assert_eq!(input.ndim(), 4);
let batch_size = input.shape()[0];
let (input_h, input_w, input_channels) = self.input_size;
let (kernel_h, kernel_w, kernel_d, _num_kernels) = self.kernels_size;
let (output_h, output_w, _output_channels) = self.output_size;
assert_eq!(input.shape()[1], input_h);
assert_eq!(input.shape()[2], input_w);
assert_eq!(input.shape()[3], input_channels);
assert_eq!(kernel_d, input_channels); // kernel_depth should match input_channels
let output_size = output_h * output_w * batch_size;
let kernel_size = kernel_h * kernel_w * kernel_d;
let mut output = Array2::zeros((output_size, kernel_size));
for b in 0..batch_size {
for y in 0..output_h {
for x in 0..output_w {
for ky in 0..kernel_h {
for kx in 0..kernel_w {
for c in 0..kernel_d {
let in_y = y + ky;
let in_x = x + kx;
let output_row = b * output_h * output_w + y * output_w + x;
let output_col = ky * kernel_w * kernel_d + kx * kernel_d + c;
output[[output_row, output_col]] = input[[b, in_y, in_x, c]];
}
}
}
}
}
}
output
}
fn im2col_full(&self, output: ArrayD<f64>) -> Array2<f64> {
assert_eq!(output.ndim(), 4);
let batch_size = output.shape()[0];
let (input_h, input_w, input_channels) = self.input_size;
let (kernel_h, kernel_w, kernel_d, num_kernels) = self.kernels_size;
let (output_h, output_w, output_channels) = self.output_size;
assert_eq!(output.shape()[1], output_h);
assert_eq!(output.shape()[2], output_w);
assert_eq!(output.shape()[3], output_channels);
assert_eq!(num_kernels, output_channels);
// Calculate padding
let pad_h = kernel_h - 1;
let pad_w = kernel_w - 1;
// Calculate the total output size as the product of output height, output width, and batch size
let input_size = input_h * input_w * batch_size;
let kernel_size = kernel_h * kernel_w * num_kernels;
// Initialize the output matrix with zeros, with shape (output_size, kernel_size)
let mut result = Array2::zeros((input_size, kernel_size));
// Pad the input tensor
let mut padded_input: ArrayD<f64> = ArrayD::zeros(IxDyn(&[
batch_size,
output_h + 2 * pad_h,
output_w + 2 * pad_w,
output_channels,
]));
for b in 0..batch_size {
for c in 0..output_channels {
for y in 0..output_h {
for x in 0..output_w {
padded_input[[b, y + pad_h, x + pad_w, c]] = output[[b, y, x, c]];
}
}
}
}
// Iterate over each element in the batch
for b in 0..batch_size {
for y in 0..input_h {
for x in 0..input_w {
for ky in 0..kernel_h {
for kx in 0..kernel_w {
for c in 0..num_kernels {
let in_y = y + ky;
let in_x = x + kx;
let input_row = b * input_h * input_w + y * input_w + x;
let input_col = ky * kernel_w * num_kernels + kx * num_kernels + c;
result[[input_row, input_col]] = padded_input[[b, in_y, in_x, c]];
}
}
}
}
}
}
result
}
fn convolve(&self, input: &ArrayD<f64>) -> ArrayD<f64> {
let col = self.im2col(input.clone());
let (kernel_h, kernel_w, kernel_d, num_kernels) = self.kernels_size;
let (output_h, output_w, output_channels) = self.output_size;
let batch_size = input.shape()[0];
let kernel_size = kernel_h * kernel_w * kernel_d;
let kernels_reshaped = self
.kernels
.clone()
.into_shape((num_kernels, kernel_size))
.unwrap();
let col_reshaped = col
.into_shape((batch_size * output_h * output_w, kernel_size))
.unwrap();
let mut result = Array2::zeros((batch_size * output_h * output_w, output_channels));
linalg::general_mat_mul(1.0, &col_reshaped, &kernels_reshaped.t(), 0.0, &mut result);
result
.into_shape(IxDyn(&[batch_size, output_h, output_w, output_channels]))
.unwrap()
}
fn convolve_full(&self, output: &ArrayD<f64>) -> ArrayD<f64> {
let col = self.im2col_full(output.clone());
let (kernel_h, kernel_w, kernel_d, num_kernels) = self.kernels_size;
let (input_h, input_w, input_channels) = self.input_size;
let batch_size = output.shape()[0];
let kernel_size = kernel_h * kernel_w * num_kernels;
let kernels_reshaped = self
.flip_kernels()
.clone()
.into_shape((kernel_d, kernel_size))
.unwrap();
let col_reshaped = col
.into_shape((batch_size * input_h * input_w, kernel_size))
.unwrap();
let mut result = Array2::zeros((batch_size * input_h * input_w, input_channels));
linalg::general_mat_mul(1.0, &col_reshaped, &kernels_reshaped.t(), 0.0, &mut result);
result
.into_shape(IxDyn(&[batch_size, input_h, input_w, input_channels]))
.unwrap()
}
}
impl Layer for ConvolutionalLayer {
fn feed_forward_save(&mut self, input: &ArrayD<f64>) -> Result<ArrayD<f64>, LayerError> {
self.input = Some(input.clone());
self.feed_forward(input)
}
fn feed_forward(&self, input: &ArrayD<f64>) -> Result<ArrayD<f64>, LayerError> {
let output = self.convolve(&input.clone());
Ok(output)
}
fn propagate_backward(
&mut self,
output_gradient: &ArrayD<f64>,
) -> Result<ArrayD<f64>, LayerError> {
let input = self
.input
.as_ref()
.expect("Input not set. Call feed_forward first.");
let (kernel_h, kernel_w, kernel_d, num_kernels) = self.kernels_size;
let (output_h, output_w, output_channels) = self.output_size;
let batch_size = input.shape()[0];
let mut col_input = self.im2col(input.clone());
let kernel_size = kernel_h * kernel_w * kernel_d;
let output_gradient_flat = output_gradient
.clone()
.into_shape((batch_size * output_h * output_w, output_channels))
.unwrap();
// Calculate the gradient with respect to the input (dL/dX) using the convolve function with flipped kernels
let d_input = self.convolve_full(output_gradient);
col_input = col_input
.into_shape((batch_size * output_h * output_w, kernel_size))
.unwrap();
// Calculate the gradient with respect to the filters (dL/dW)
let mut d_kernels = Array2::zeros((num_kernels, kernel_size));
linalg::general_mat_mul(
1.0,
&output_gradient_flat.t(),
&col_input,
0.0,
&mut d_kernels,
);
let d_kernels = d_kernels
.into_shape(IxDyn(&[kernel_h, kernel_w, kernel_d, num_kernels]))
.unwrap();
self.kernel_gradient = Some(d_kernels);
// Calculate the gradient with respect to the biases (dL/db)
let d_biases = output_gradient
.sum_axis(Axis(0))
.sum_axis(Axis(0))
.sum_axis(Axis(0));
self.bias_gradient = Some(d_biases);
Ok(d_input)
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
impl Trainable for ConvolutionalLayer {
fn get_parameters(&self) -> Vec<ArrayD<f64>> {
vec![
self.kernels.clone().into_dyn(),
self.bias.clone().into_dyn(),
]
}
fn get_parameters_mut(&mut self) -> Vec<&mut ArrayD<f64>> {
vec![&mut self.kernels, &mut self.bias]
}
fn get_gradients(&self) -> Vec<ArrayD<f64>> {
vec![
self.kernel_gradient
.as_ref()
.expect("Illegal access to unset weights gradient")
.clone()
.into_dyn(),
self.bias_gradient
.as_ref()
.expect("Illegal access to unset biases gradient")
.clone()
.into_dyn(),
]
}
}
pub struct MaxPoolingLayer {
input: Option<ArrayD<f64>>,
max_indices: Option<ArrayD<usize>>,
input_size: (usize, usize, usize),
output_size: (usize, usize, usize),
pool_size: (usize, usize),
}
impl MaxPoolingLayer {
pub fn new(input_size: (usize, usize, usize), pool_size: (usize, usize)) -> Self {
let (input_height, input_width, input_channel): (usize, usize, usize) = input_size;
let (pool_height, pool_width): (usize, usize) = pool_size;
let output_size: (usize, usize, usize) = (
input_height / pool_height,
input_width / pool_width,
input_channel,
);
Self {
input: None,
max_indices: None,
input_size,
output_size,
pool_size,
}
}
fn find_max_indices(&mut self) {
let input = self
.input
.as_ref()
.expect("Input not set. Call feed_forward first.");
let batch_size: usize = input.shape()[0];
let (pool_height, pool_width): (usize, usize) = self.pool_size;
let (output_height, output_width, output_channel) = self.output_size;
let mut max_indices: ArrayD<usize> = ArrayD::zeros(IxDyn(&[batch_size, output_height, output_width, output_channel]));
for batch_index in 0..batch_size {
for channel in 0..output_channel {
for y in 0..output_height {
for x in 0..output_width {
let height_start: usize = y * pool_height;
let width_start: usize = x * pool_width;
let window = input.slice(s![
batch_index,
height_start..height_start + pool_height,
width_start..width_start + pool_width,
channel
]);
let (max_index, _) = window.indexed_iter().fold((0, f64::MIN), |(max_idx, max_value), (idx, &val)| {
if val > max_value {
(idx.0 * window.ncols() + idx.1, val)
} else {
(max_idx, max_value)
}
});
max_indices[[batch_index, y, x, channel]] = max_index;
}
}
}
}
self.max_indices = Some(max_indices);
}
}
impl Layer for MaxPoolingLayer {
fn feed_forward_save(&mut self, input: &ArrayD<f64>) -> Result<ArrayD<f64>, LayerError> {
self.input = Some(input.clone());
self.find_max_indices();
self.feed_forward(input)
}
fn feed_forward(&self, input: &ArrayD<f64>) -> Result<ArrayD<f64>, LayerError> {
let batch_size: usize = input.shape()[0];
let (pool_height, pool_width): (usize, usize) = self.pool_size;
let (output_height, output_width, output_channel) = self.output_size;
let max_indices = self
.max_indices
.as_ref()
.expect("Max_indices not set. Call feed_forward first.");
let mut output: ArrayD<f64> = ArrayD::zeros(IxDyn(&[batch_size, output_height, output_width, output_channel]));
for batch_index in 0..batch_size {
for channel in 0..output_channel {
for y in 0..output_height {
for x in 0..output_width {
let index = max_indices[[batch_index, y, x, channel]];
let height_start = y * pool_height;
let width_start = x * pool_width;
let dy = index / pool_height;
let dx = index % pool_width;
output[[batch_index, y, x, channel]] = input[[batch_index, height_start + dy, width_start + dx, channel]];
}
}
}
}
Ok(output)
}
fn propagate_backward(
&mut self,
output_gradient: &ArrayD<f64>,
) -> Result<ArrayD<f64>, LayerError> {
let input = self
.input
.as_ref()
.expect("Input not set. Call feed_forward first.");
let max_indices = self
.max_indices
.as_ref()
.expect("Max_indices not set. Call feed_forward first");
let batch_size: usize = input.shape()[0];
let (input_height, input_width, input_channel): (usize, usize, usize) = self.input_size;
let (output_height, output_width, output_channel) = self.output_size;
let (pool_height, pool_width): (usize, usize) = self.pool_size;
let mut input_gradient: ArrayD<f64> = ArrayD::zeros(IxDyn(&[batch_size, input_height, input_width, input_channel]));
for batch_index in 0..batch_size {
for channel in 0..output_channel {
for y in 0..output_height {
for x in 0..output_width {
let index = max_indices[[batch_index, y, x, channel]];
let height_start = y * pool_height;
let width_start = x * pool_width;
let dy = index / pool_height;
let dx = index % pool_width;
input_gradient[[batch_index, height_start + dy, width_start + dx, channel]] += output_gradient[[batch_index, y, x, channel]];
}
}
}
}
Ok(input_gradient)
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
pub struct ReshapeLayer {
input: Option<ArrayD<f64>>,
input_shape: IxDyn,
output_shape: IxDyn,
}
impl ReshapeLayer {
pub fn new(input_shape: &[usize], output_shape: &[usize]) -> Result<Self, LayerError> {
let input_elements: usize = input_shape.iter().product();
let output_elements: usize = output_shape.iter().product();
if input_elements != output_elements {
return Err(LayerError::ReshapeError(ShapeError::from_kind(
ndarray::ErrorKind::IncompatibleShape,
)));
}
Ok(Self {
input: None,
input_shape: IxDyn(input_shape),
output_shape: IxDyn(output_shape),
})
}
}
impl Layer for ReshapeLayer {
fn feed_forward_save(&mut self, input: &ArrayD<f64>) -> Result<ArrayD<f64>, LayerError> {
self.input = Some(input.clone());
self.feed_forward(input)
}
fn feed_forward(&self, input: &ArrayD<f64>) -> Result<ArrayD<f64>, LayerError> {
let batch_size: usize = input.shape()[0];
let mut shape: Vec<usize> = Vec::with_capacity(self.output_shape.ndim() + 1);
shape.push(batch_size);
shape.extend_from_slice(self.output_shape.as_array_view().as_slice().unwrap());
if input.shape().iter().product::<usize>() != shape.iter().product() {
return Err(LayerError::ReshapeError(ShapeError::from_kind(
ndarray::ErrorKind::IncompatibleShape,
)));
}
Ok(input.clone().into_shape(shape).unwrap())
}
fn propagate_backward(
&mut self,
output_gradient: &ArrayD<f64>,
) -> Result<ArrayD<f64>, LayerError> {
let batch_size: usize = output_gradient.shape()[0];
let mut shape: Vec<usize> = Vec::with_capacity(self.output_shape.ndim() + 1);
shape.push(batch_size);
shape.extend_from_slice(self.input_shape.as_array_view().as_slice().unwrap());
if output_gradient.shape().iter().product::<usize>() != shape.iter().product() {
return Err(LayerError::ReshapeError(ShapeError::from_kind(
ndarray::ErrorKind::IncompatibleShape,
)));
}
Ok(output_gradient.clone().into_shape(shape).unwrap())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
#[derive(Error, Debug)]
pub enum LayerError {
#[error("Access to stored input of the layer before stored happened")]
IllegalInputAccess,
#[error("Error reshaping array: {0}")]
ReshapeError(#[from] ShapeError),
#[error("Dimension don't match")]
DimensionMismatch,
}
|
<?php
namespace App;
use App\Traits\uuidPrimary;
use Carbon\Carbon;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use Notifiable, uuidPrimary;
/**
* The "booting" function of model
*
* @return void
*/
protected static function boot() {
parent::boot();
static::created(function ($model) {
$model->generateOtpCode();
});
}
/**
* Get the primary key for the model.
*
* @return string
*/
public function getKeyName()
{
return 'user_id';
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'role_id', 'photo', 'email_verified_at'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles()
{
return $this->belongsTo("App\Roles", "role_id", 'role_id');
}
public function otp_codes()
{
return $this->hasOne("App\Otp_codes", "user_id", "user_id");
}
public function chats()
{
return $this->hasMany(Chat::class, 'user_id', 'user_id');
}
public function isAdmin()
{
if ($this->role_id == Roles::where('role', 'admin')->first()->role_id) {
return true;
}
return false;
}
public function generateOtpCode()
{
do {
$otp_code = rand(100000, 999999);
$check = Otp_codes::where('otp_code', $otp_code)->first();
} while ($check);
$now = Carbon::now();
$otp = Otp_codes::updateOrCreate(
['user_id' => $this->user_id],
['otp_code' => $otp_code, 'valid_until' => $now->addMinutes(5)]
);
}
// Rest omitted for brevity
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
|
const express = require('express');
const multer = require('multer');
const { handlePdfUpload } = require('../services/pdfService'); // make sure to export simplifyText
const {simplifyText} = require('../services/openaiService')
const router = express.Router();
const upload = multer({ dest: 'uploads/' }); // Configure as needed
router.post('/', upload.single('file'), async (req, res) => {
try {
// First handle the PDF upload
const extractedText = await handlePdfUpload(req, res);
// Then simplify the text using OpenAI
const simplifiedText = await simplifyText(extractedText);
console.log("This is OpenAI text: /n", simplifiedText)
// Finally, send the simplified text back in the response
res.json({ simplifiedText });
} catch (error) {
// Handle any errors
console.error('Error in PDF upload or text simplification:', error);
res.status(500).send('Error in PDF upload or text simplification.');
}
});
module.exports = router;
|
package selenium_with_JUnit;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class CG16_SeleniumWaits {
//2. Iki tane metod olusturun : implicitWait() , explicitWait()
// Iki metod icin de asagidaki adimlari test edin.
//3. https://the-internet.herokuapp.com/dynamic_controls adresine gidin.
//4. Remove butonuna basin.
//5. “It’s gone!” mesajinin goruntulendigini dogrulayin.
//6. Add buttonuna basin
//7. It’s back mesajinin gorundugunu test edin
@Test
public void test01(){
WebDriverManager.chromedriver().setup();
WebDriver driver =new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); // sureyi 2 sn yapinca Test failed oluyor.
//3. https://the-internet.herokuapp.com/dynamic_controls adresine gidin.
driver.get("https://the-internet.herokuapp.com/dynamic_controls");
//4. Remove butonuna basin
driver.findElement(By.xpath("//*[text()='Remove']")).click();
//5. “It’s gone!” mesajinin goruntulendigini dogrulayin.
WebElement actualText = driver.findElement(By.xpath("//*[text()=\"It's gone!\"]"));
Assert.assertTrue(actualText.isDisplayed());
//6. Add buttonuna basin
driver.findElement(By.xpath("//*[text()='Add']")).click();
//7. It’s back mesajinin gorundugunu test edin
Assert.assertTrue(driver.findElement(By.xpath("//*[text()=\"It's back!\"]")).isDisplayed());
driver.close();
}
@Test
public void explicitlyWaitTest(){
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
//3. https://the-internet.herokuapp.com/dynamic_controls adresine gidin.
driver.get("https://the-internet.herokuapp.com/dynamic_controls");
//4. Remove butonuna basin.
driver.findElement(By.xpath("//*[text()='Remove']")).click();
//5. “It’s gone!” mesajinin goruntulendigini dogrulayin.
WebDriverWait wait =new WebDriverWait(driver,Duration.ofSeconds(30));
WebElement itsGoneElementi =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[text()=\"It's gone!\"]")));
Assert.assertTrue(itsGoneElementi.isDisplayed());
//6. Add buttonuna basin
driver.findElement(By.xpath("//*[text()='Add']")).click();
//7. It’s back mesajinin gorundugunu test edin
WebElement itsBackElement=
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[text()=\"It's back!\"]")));
Assert.assertTrue(itsBackElement.isDisplayed());
}
}
|
//
// MenuScene.swift
// Colorix
//
// Created by Kejvi Peti on 2021-07-22.
//
import SpriteKit
class MenuScene: SKScene {
override func didMove(to view: SKView) {
backgroundColor = Colors.space_cadet
addLogo()
addLabels()
}
func addLogo(){
let logo = SKSpriteNode(imageNamed: "logo")
logo.size = CGSize(width: frame.width/4, height: frame.width/4)
logo.position = CGPoint(x: frame.midX, y: frame.midY + frame.size.height/4)
addChild(logo)
}
func addLabels(){
let highScore = UserDefaults.standard.integer(forKey: "highScore")
let recentScore = UserDefaults.standard.integer(forKey: "recentScore")
let playLabel = SKLabelNode(text: "Tap to play")
playLabel.fontName = "AvenirNext-Bold"
playLabel.fontSize = 50.0
playLabel.fontColor = Colors.beige
playLabel.position = CGPoint(x: frame.midX, y: frame.midY)
addChild(playLabel)
animate(label: playLabel)
let highScoreLabel = SKLabelNode(text: "Highscore: \(highScore)")
highScoreLabel.fontName = "AvenirNext-Bold"
highScoreLabel.fontSize = 40.0
highScoreLabel.fontColor = Colors.beige
highScoreLabel.position = CGPoint(x: frame.midX, y: frame.midY - highScoreLabel.frame.size.height * 4)
addChild(highScoreLabel)
let recentScoreLabel = SKLabelNode(text: "Recent Score: \(recentScore)")
recentScoreLabel.fontName = "AvenirNext-Bold"
recentScoreLabel.fontSize = 40.0
recentScoreLabel.fontColor = Colors.beige
recentScoreLabel.position = CGPoint(x: frame.midX, y: frame.midY - recentScoreLabel.frame.size.height * 4)
addChild(recentScoreLabel)
}
func animate(label: SKLabelNode){
let fadeOut = SKAction.fadeOut(withDuration: 0.5)
let fadeIn = SKAction.fadeIn(withDuration: 0.5)
let sequence = SKAction.sequence([fadeOut,fadeIn])
label.run(SKAction.repeatForever(sequence))
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let gameScene = GameScene(size: view!.bounds.size)
view!.presentScene(gameScene)
}
}
|
// author : Mauricio Gomes
// license: MIT (https://opensource.org/licenses/MIT)
#ifndef CSKPROGRAM_HPP
#define CSKPROGRAM_HPP
#include "../cpplib/name.hpp"
#include "../cpplib/string_def.hpp"
#include <list>
#include <string>
namespace pensar_digital
{
namespace csk
{
using namespace cpplib;
class Type: public Name
{
public:
inline static const VersionPtr VERSION = pd::Version::get (1, 1, 1);
Type (const String& aname = ""): Name (aname) {};
static Type NULL_TYPE;
Type (const Type& t): Name (t) {}
Type& assign (const Type& t)
{
Name::assign (t.get_name());
Object::assign (t);
return *this;
}
Type& operator = (const Type& t) {return assign(t);}
protected:
virtual std::istream& read (std::istream& is)
{
Name::read (is);
switch (VERSION->get_public ())
{
case 1:;
};
return is;
};
virtual std::ostream& write (std::ostream& os, const IO_Mode& amode = TEXT, const std::endian& byte_order = std::endian::native) const
{
Name::write(os);
switch (VERSION->get_public())
{
case 1:;
};
return os;
};
public:
std::istream& operator >> (std::istream& is) { return read (is);};
std::ostream& operator << (std::ostream& os) const { return write (os);};
};
csk::Type Type::NULL_TYPE = Type ();
class Class: Type
{
public:
inline static const VersionPtr VERSION = pd::Version::get (1, 1, 1);
Class () {};
Class (const Class& o): Type(o) {};
Class& assign (const Class& c) {Name::assign (c.get_name()); Object::assign (c); return *this;};
Class& operator = (const Class& c) {return assign(c);}
protected:
virtual std::istream& read (std::istream& is)
{
Type::read (is);
switch (VERSION->get_public())
{
case 1:;
};
return is;
};
virtual std::ostream& write (std::ostream& os) const
{
Type::write(os);
switch (VERSION->get_public())
{
case 1:;
};
return os;
};
public:
std::istream& operator >> (std::istream& is) { return read (is);};
std::ostream& operator << (std::ostream& os) const { return write (os);};
};
//extern std::istream& operator
class Parameter: Object
{
public:
Parameter(const Type& atype = Type::NULL_TYPE, std::string aname = ""): type(atype), name(aname) {};
Parameter(const Parameter& p) {assign (p);};
virtual Parameter& assign (const Parameter& p) {type = p.type; name = p.name; return *this;};
Parameter& operator = (const Parameter& p) {return assign (p);};
protected:
virtual std::istream& read (std::istream& is)
{
Object::read (is);
switch (VERSION->get_public())
{
default:
type.operator >> (is);
is >> name;
};
return is;
};
virtual std::ostream& write (std::ostream& os) const
{
Object::write (os);
switch (VERSION->get_public())
{
case 1:
os << name;
type.operator << (os);
};
return os;
};
public:
std::istream& operator >> (std::istream& is) { return read (is);};
std::ostream& operator << (std::ostream& os) const { return write (os);};
private:
Type type;
Name name;
};
typedef std::list<Parameter> ParametersList;
class Method: Object
{
Method () {};
//Method (Type: areturn_type, std::string aname, Parameters: aparams): return_type (areturn_type), name(aname), params(aparams) {};
Method (const Method& m) { assign (m);};
Method& assign (const Method& m) {Object::assign (m); return *this;}
private:
Type return_type;
std::string name;
ParametersList params;
};
typedef std::list<Method> MethodsList;
class CSKProgram: Object
{
public:
/** Default constructor */
CSKProgram(): private_methods(), protected_methods(), public_methods() {};
/** Default destructor */
virtual ~CSKProgram();
/** Copy constructor
* \param other Object to copy from
*/
CSKProgram(const CSKProgram& other);
/** Assignment operator
* \param other Object to assign from
* \return A reference to this
*/
CSKProgram& operator=(const CSKProgram& other);
protected:
private:
MethodsList private_methods;
MethodsList protected_methods;
MethodsList public_methods;
};
}
}
#endif // CSKPROGRAM_HPP
|
from reportlab.graphics import shapes
from reportlab.lib import colors
from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER, TA_RIGHT
from reportlab.lib.pagesizes import letter, landscape
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import mm, inch
from reportlab.platypus import (
Paragraph,
PageBreak,
Spacer,
Image,
Table,
TableStyle,
ListFlowable,
)
from reportlab.platypus import SimpleDocTemplate
from reportlab_qrcode import QRCodeImage
import datetime as dt
from io import BytesIO
import pandas as pd
import math
import json
from flask import session
import app.scripts.utils as utils
from app.scripts import scripts, files_df
from app.scripts.date_to_marking_period import return_mp_from_date
from app.scripts.privileges.attendance_benchmark import attendance_benchmark
from app.api_1_0.students import return_student_info
styles = getSampleStyleSheet()
styles.add(
ParagraphStyle(
name="Normal_RIGHT",
parent=styles["Normal"],
alignment=TA_RIGHT,
)
)
styles.add(
ParagraphStyle(
name="Body_Justify",
parent=styles["BodyText"],
alignment=TA_JUSTIFY,
)
)
letter_head = [
Paragraph("High School of Fashion Industries", styles["Normal"]),
Paragraph("225 W 24th St", styles["Normal"]),
Paragraph("New York, NY 10011", styles["Normal"]),
Paragraph("Principal, Daryl Blank", styles["Normal"]),
]
closing = [
Spacer(width=0, height=0.25 * inch),
Paragraph("Warmly,", styles["Normal_RIGHT"]),
Paragraph("Derek Stampone", styles["Normal_RIGHT"]),
Paragraph("Assistant Principal, Attendance", styles["Normal_RIGHT"]),
]
def return_student_letter(form, request):
school_year = session["school_year"]
StudentID = int(form.StudentID.data)
PRESENT_STANDARD = form.in_class_percentage.data
ON_TIME_STANDARD = form.on_time_percentage.data
student_info = json.loads(return_student_info(StudentID).data)[0]
first_name = student_info["FirstName"]
last_name = student_info["LastName"]
df = attendance_benchmark.main(PRESENT_STANDARD, ON_TIME_STANDARD)
df = df[df["StudentID"] == StudentID]
student_pd_df_cols = [
"Term",
"Pd",
"excused",
"present",
"tardy",
"unexcused",
"total",
"%_present",
"%_on_time",
"meet_attd_standard",
]
student_pd_df = df[student_pd_df_cols]
student_pd_table = utils.return_df_as_table(student_pd_df)
# table_style = TableStyle([("ALIGN", (0, 0), (-1, -1), "RIGHT")])
# for (
# row,
# values,
# ) in enumerate(student_pd_df.values.tolist()):
# for column, value in enumerate(values):
# if value == False:
# table_style.add("TEXTCOLOR", (column, row), (column, row), colors.red)
# student_pd_table.setStyle(table_style)
student_eligibility_df_cols = ["Term", "overall_meet_attd_standard"]
student_eligibility_df = df[student_eligibility_df_cols]
student_eligibility_df = student_eligibility_df.drop_duplicates(subset=["Term"])
student_eligibility_df_table = utils.return_df_as_table(student_eligibility_df)
flowables = []
paragraph = Paragraph(
f"{first_name.title()} {last_name.title()} ({StudentID})",
styles["Heading1"],
)
flowables.append(paragraph)
paragraph = Paragraph(
f"Attendance Benchmark Data - Present {PRESENT_STANDARD}% & On Time {ON_TIME_STANDARD}%",
styles["Heading2"],
)
flowables.append(paragraph)
flowables.append(student_eligibility_df_table)
flowables.append(student_pd_table)
flowables.append(PageBreak())
attd_grid_df = attendance_benchmark.return_attd_grid(StudentID)
student_attd_grid_table = utils.return_df_as_table(attd_grid_df)
table_style = TableStyle([("ALIGN", (0, 0), (-1, -1), "RIGHT")])
student_attd_grid_table.setStyle(table_style)
flowables.append(student_attd_grid_table)
f = BytesIO()
my_doc = SimpleDocTemplate(
f,
pagesize=landscape(letter),
topMargin=0.50 * inch,
leftMargin=1 * inch,
rightMargin=1 * inch,
bottomMargin=0.5 * inch,
)
my_doc.build(flowables)
f.seek(0)
return f, f"{first_name.title()}_{last_name.title()}"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.