text
stringlengths
184
4.48M
#pragma once #include "action.h" #include "controls.h" #include "state.h" class Pick : public Action { State * state; public: Pick(State &state) { this->state = &state; } void call() { if(state->menuIndex == 0) { state->isOnMainMenu = false; } else if(state->menuIndex == 1) { state->quit = true; } } }; class ChangeSelectionUp : public Action { State * state; public: ChangeSelectionUp(State &state) { this->state = &state; } void call() { int index = state->menuIndex - 1; if(index >= 0 ) state->menuIndex = index; } }; class ChangeSelectionDown: public Action { State * state; public: ChangeSelectionDown(State &state) { this->state = &state; } void call() { int index = state->menuIndex + 1; if(index < 2) state->menuIndex = index; } }; class MenuControls : public Controls { public: Pick pick; ChangeSelectionUp up; ChangeSelectionDown down; MenuControls(State &state) : pick(state), up(state), down(state) { set(sf::Keyboard::Enter, pick); set(sf::Keyboard::Up, up); set(sf::Keyboard::Down, down); }; };
<div class="mod-list-market"> <div class="m-button"> <button nz-button nzType="primary" (click)="showAddModal()" *ngIf="authService.getPermissions().includes('market:create')"> <i nz-icon nzType="plus" nzTheme="outline"></i> <span>Add market</span> </button> </div> <nz-table #rowSelectionTable nzShowPagination nzShowSizeChanger [nzData]="listMarkets" [nzPageSize]="5" [nzPageSizeOptions]="[5,10]" > <thead> <tr> <th>Name</th> <th>Logo</th> <th>marketbranch</th> <th *ngIf="authService.getPermissions().includes('market:update') || authService.getPermissions().includes('market:delete')" >Aktion</th> </tr> </thead> <tbody *ngIf="!isLoading"> <tr *ngFor="let item of rowSelectionTable.data"> <td>{{ item.name }}</td> <td> <img nz-image width="70px" height="70px" nzSrc="{{publicUrl}}{{item.logo }}" alt="{{ item.name }}"/> </td> <td> <button class="m-button-action" nz-button nzType="primary" (click)="showMarketBranches(item.id)"> <i nz-icon nzType="eye" nzTheme="outline"></i> </button> </td> <td *ngIf="authService.getPermissions().includes('market:update') || authService.getPermissions().includes('market:delete')"> <button class="m-button-action" nz-button nzType="primary" (click)="showEditModal(item)" *ngIf="authService.getPermissions().includes('market:update')"> <i nz-icon nzType="edit" nzTheme="outline"></i> </button> <button class="m-button-action" nz-button nzType="primary" (click)="showDeleteConfirm(item.id)" *ngIf="authService.getPermissions().includes('market:delete')"> <i nz-icon nzType="delete" nzTheme="outline"></i> </button> <nz-modal [(nzVisible)]="item.editModalIsVisible" nzTitle="Modal edit market" (nzOnCancel)="handleCancelEditModal(item)" [nzFooter]="null" > <p *nzModalContent> <app-edit-market [marketObject]="item"></app-edit-market> </p> </nz-modal> </td> </tr> </tbody> <tbody *ngIf="isLoading"> <tr *ngFor="let item of [0, 1, 2, 3, 4]"> <td> <nz-skeleton [nzActive]="true" [nzParagraph]="false"></nz-skeleton> </td> <td> <nz-skeleton-element nzType="image" [nzActive]="true"></nz-skeleton-element> </td> <td> <nz-skeleton-element nzType="button" [nzActive]="true"></nz-skeleton-element> </td> </tr> </tbody> </nz-table> <nz-modal [(nzVisible)]="addModalIsVisible" nzTitle="Modal add market" (nzOnCancel)="handleCancelAddModal()" [nzFooter]="null" > <p *nzModalContent> <app-add-market></app-add-market> </p> </nz-modal> </div>
return { "hrsh7th/nvim-cmp", lazy = true, event = "InsertEnter", dependencies = { { "lukas-reineke/cmp-under-comparator" }, { "andersevenrud/cmp-tmux" }, { "f3fora/cmp-spell" }, { "kdheepak/cmp-latex-symbols" }, }, opts = function(_, opts) local icons = { kind = require("user.icons").get("kind"), type = require("user.icons").get("type"), cmp = require("user.icons").get("cmp"), } local compare = require("cmp.config.compare") compare.lsp_scores = function(entry1, entry2) local diff if entry1.completion_item.score and entry2.completion_item.score then diff = (entry2.completion_item.score * entry2.score) - (entry1.completion_item.score * entry1.score) else diff = entry2.score - entry1.score end return (diff < 0) end local comparators = { -- require("cmp_tabnine.compare"), compare.offset, -- Items closer to cursor will have lower priority compare.exact, -- compare.scopes, compare.lsp_scores, compare.sort_text, compare.score, compare.recently_used, -- compare.locality, -- Items closer to cursor will have higher priority, conflicts with `offset` require("cmp-under-comparator").under, compare.kind, compare.length, compare.order, } local myopts = { sorting = { priority_weight = 2, comparators = comparators, }, formatting = { fields = { "abbr", "kind", "menu" }, format = function(entry, vim_item) local lspkind_icons = vim.tbl_deep_extend("force", icons.kind, icons.type, icons.cmp) -- load lspkind icons vim_item.kind = string.format( " %s %s", lspkind_icons[vim_item.kind] or icons.cmp.undefined, vim_item.kind or "" ) vim_item.menu = setmetatable({ cmp_tabnine = "[TN]", copilot = "[CPLT]", buffer = "[BUF]", orgmode = "[ORG]", nvim_lsp = "[LSP]", nvim_lua = "[LUA]", path = "[PATH]", tmux = "[TMUX]", treesitter = "[TS]", latex_symbols = "[LTEX]", luasnip = "[SNIP]", spell = "[SPELL]", }, { __index = function() return "[BTN]" -- builtin/unknown source names end, })[entry.source.name] local label = vim_item.abbr local truncated_label = vim.fn.strcharpart(label, 0, 80) if truncated_label ~= label then vim_item.abbr = truncated_label .. "..." end return vim_item end, }, -- You should specify your *installed* sources. sources = { { name = "nvim_lsp", max_item_count = 350 }, { name = "nvim_lua" }, { name = "luasnip" }, { name = "path" }, { name = "treesitter" }, { name = "spell" }, { name = "tmux" }, { name = "orgmode" }, { name = "buffer" }, { name = "latex_symbols" }, }, experimental = { ghost_text = { hl_group = "Whitespace", }, }, } return require("astronvim.utils").extend_tbl(opts, myopts) end, }
import { InputAdornment, Box, Button, TextField } from "@mui/material"; import SearchIcon from "@mui/icons-material/Search"; import ReactPaginate from "react-paginate"; import SectionHeading from "../Components/SectionHeading/SectionHeading"; import cashierImg from "../../assets/Cashier.png"; import { CartsType, CategoriesType, Products } from "../../types/types"; import { useSelector } from "react-redux"; import CartCard from "./Components/CartCard/CartCard"; import { useState, ChangeEvent } from "react"; import CreateCartModal from "./Components/CreateCartModal/CreateCartModal"; import ProductCard from "./Components/ProductCard/ProductCard"; import AddToCartModal from "./Components/AddToCartModal/AddToCartModal"; import "./home.css"; import useFetchProducts from "../../hooks/useFetchProducts"; import useFetchCategories from "../../hooks/useFetchCategories"; import useFetchMeasures from "../../hooks/useFetchMeasures"; import useFetchCarts from "../../hooks/useFetchCarts"; import Loader from "../Components/Loader/Loader"; function Home() { useFetchCarts(); // fetch categories, products and measures if not fetched useFetchProducts(); useFetchCategories(); useFetchMeasures(); const carts: CartsType = useSelector((state: any) => state.carts.carts); const products: Products = useSelector( (state: any) => state.products.products ); const categories: CategoriesType = useSelector( (state: any) => state.categories.categories ); // state for create cart modal const [showCreateModal, setShowCreateModal] = useState(false); // filter products // for add to cart modal const [showAddToCartModal, setShowAddToCartModal] = useState(false); const [selectedProductId, setSelectedProductId] = useState(-1); // function to handle search and filter const [searchTerm, setSearchTerm] = useState(""); const [selectedCategoryId, setSelectedCategoryId] = useState("all"); const handleSearch = (e: ChangeEvent<HTMLInputElement>) => { setSearchTerm(e.target.value.trim().toLowerCase()); }; const handleSelect = (e: ChangeEvent<HTMLSelectElement>) => { setSelectedCategoryId(e.target.value); }; const filteredProducts = products?.filter((product) => { const productName = product.attributes.name.toLowerCase(); let categoryMatch: boolean; if ( selectedCategoryId === "all" || product.attributes.category.data?.id === +selectedCategoryId ) categoryMatch = true; else categoryMatch = false; const searchTermMatch = searchTerm === "" || productName.includes(searchTerm); return categoryMatch && searchTermMatch; }); // pagination const [pageNumber, setPageNumber] = useState(0); const productPerPage = 8; const visitedPage = pageNumber * productPerPage; const productsToShow = filteredProducts?.slice( visitedPage, visitedPage + productPerPage ); const pageCount = Math.ceil(filteredProducts?.length / productPerPage); const changePage = ({ selected }: any) => { setPageNumber(selected); }; // loading const isLoading: Boolean = useSelector( (state: any) => state.isLoading.isLoading ); const spinner = ( <div className="loading-container"> <Loader /> </div> ); if (isLoading) return spinner; return ( <> <section> <SectionHeading position="left" text="Cart Management" /> <Box display="flex" flexDirection="row" flexWrap="wrap" justifyContent="space-between" alignItems="flex-start" gap={2} > <Box flex={1} minWidth={300} margin="auto" p={2}> <article> <p> As a cashier, you have the ability to create and manage multiple carts, providing you with a flexible and efficient checkout process. Here are the key features and actions available to you: </p> <ul className="cart-ul"> <li> Create Carts: &nbsp; <span> Initiate new carts for different customers or transactions, each with a unique identifier. This allows you to handle multiple transactions simultaneously. </span> </li> <li> Edit Carts: &nbsp; <span> Modify the contents of each cart as needed. Add or remove products, adjust quantities, and update cart details to accurately reflect the customer's purchase. </span> </li> <li> Delete Carts: &nbsp; <span> Remove unnecessary or abandoned carts from the system to keep your workspace organized and focused on active transactions. </span> </li> </ul> <p> By leveraging these cart management capabilities, you can streamline your point-of-sale operations, provide personalized service to customers, and ensure smooth and accurate checkouts. </p> </article> <Button onClick={() => setShowCreateModal(true)} sx={{ my: 4, backgroundColor: "var(--yellow-color)", color: "#FFFFFF", fontWeight: "bold", transition: "0.3s", "&:hover": { opacity: 0.8, backgroundColor: "var(--yellow-color)", transform: "translateY(-2px)", }, }} variant="contained" > New Cart </Button> </Box> <Box flex={2} minWidth={300} maxWidth={400} p={2} margin="auto"> <img style={{ width: "100%" }} src={cashierImg} alt="cashier-img" /> </Box> </Box> {showCreateModal && <CreateCartModal setIsShow={setShowCreateModal} />} </section> <section> <SectionHeading position="center" text="Carts" /> <Box flex={1} minWidth={300} margin="auto" p={2} pb={4}></Box> <Box display="flex" flexDirection="row" flexWrap="wrap" justifyContent="space-between" alignItems="center" gap={2} > {!carts?.length ? ( <p> Oops! It seems that no categories have been added yet. Don't worry, you can easily add new categories to your system to organize your products more effectively. Just click the "Add Category" button to get started and enhance your inventory management. </p> ) : ( carts.map((cart) => <CartCard key={cart.id} cart={cart} />) )} </Box> </section> <section> <SectionHeading position="center" text="Our Products" /> <Box marginTop={6} marginBottom={6} display="flex" flexDirection="row" flexWrap="wrap" justifyContent="space-between" alignItems="flex-start" gap={2} > <Box flex={1} minWidth={300} margin="auto" p={2}> {/* search element */} <TextField variant="outlined" color="secondary" size="small" label="I'm Looking for..." type="search" fullWidth onChange={handleSearch} InputProps={{ startAdornment: ( <InputAdornment position="start"> <SearchIcon /> </InputAdornment> ), }} /> </Box> {/* categories for slice */} <Box flex={1} minWidth={300} margin="auto" p={2}> <select style={{ width: "100%", border: "1px solid #eee" }} onChange={handleSelect} > <option value="all">All Categories</option> {categories?.map((cat) => ( <option value={cat.id} key={cat.id}> {cat.attributes.name} </option> ))} </select> </Box> </Box> {/* products cards */} <div className="products-container"> {productsToShow?.map((product) => ( <ProductCard key={product.id} product={product} setShowAddToCartModal={setShowAddToCartModal} setSelectedProductId={setSelectedProductId} /> ))} </div> <div> <ReactPaginate pageCount={pageCount} onPageChange={changePage} previousLabel="Prev" nextLabel="Next" containerClassName="paginationBtns" activeClassName="active_pagination" /> </div> {showAddToCartModal && ( <AddToCartModal setIsShow={setShowAddToCartModal} selectedProductId={selectedProductId} /> )} </section> </> ); } export default Home;
// Copyright 2017 The Nomulus Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package google.registry.flows; import static com.google.appengine.api.users.UserServiceFactory.getUserService; import static google.registry.testing.DatastoreHelper.loadRegistrar; import static google.registry.testing.DatastoreHelper.persistResource; import com.google.appengine.api.users.User; import com.google.common.collect.ImmutableSet; import google.registry.model.registrar.RegistrarContact; import google.registry.testing.AppEngineRule; import google.registry.testing.UserInfo; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Test logging in with appengine user credentials, such as via the console. */ @RunWith(JUnit4.class) public class EppLoginUserTest extends EppTestCase { @Rule public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() .withUserService(UserInfo.create("person@example.com", "12345")) .build(); @Before public void initTest() throws Exception { User user = getUserService().getCurrentUser(); persistResource( new RegistrarContact.Builder() .setParent(loadRegistrar("NewRegistrar")) .setEmailAddress(user.getEmail()) .setGaeUserId(user.getUserId()) .setTypes(ImmutableSet.of(RegistrarContact.Type.ADMIN)) .build()); setTransportCredentials(GaeUserCredentials.forCurrentUser(getUserService())); } @Test public void testLoginLogout() throws Exception { assertCommandAndResponse("login_valid.xml", "login_response.xml"); assertCommandAndResponse("logout.xml", "logout_response.xml"); } @Test public void testNonAuthedLogin_fails() throws Exception { assertCommandAndResponse("login2_valid.xml", "login_response_unauthorized_role.xml"); } @Test public void testMultiLogin() throws Exception { assertCommandAndResponse("login_valid.xml", "login_response.xml"); assertCommandAndResponse("logout.xml", "logout_response.xml"); assertCommandAndResponse("login_valid.xml", "login_response.xml"); assertCommandAndResponse("logout.xml", "logout_response.xml"); assertCommandAndResponse("login2_valid.xml", "login_response_unauthorized_role.xml"); } @Test public void testLoginLogout_wrongPasswordStillWorks() throws Exception { // For user-based logins the password in the epp xml is ignored. assertCommandAndResponse("login_invalid_wrong_password.xml", "login_response.xml"); assertCommandAndResponse("logout.xml", "logout_response.xml"); } }
{ // Only Number만 가능 function checkNotNullBad(arg: number | null): number { if(arg == null){ throw new Error('not valid number!') } return arg; } // 타입 보장 X function checkNotNullAnyBad(arg: any | null): any { if(arg == null){ throw new Error('not valid number!') } return arg; } // 이럴 때, 제네릭을 사용하면 유용! function checkNotNull<GENERIC>(arg: GENERIC | null): GENERIC { if(arg == null){ throw new Error('not valid number!') } return arg; } // const result = checkNotNullBad(1234); // console.log(result); // checkNotNull(null); const number = checkNotNull(123); const boal: boolean = checkNotNull(true); } // ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ // ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ interface Either<L, R> { left: () => L; right: () => R; } class SimpleEither<L, R> implements Either<L, R> { constructor(private leftValue: L, private rightValue: R) {} left(): L { return this.leftValue; } right(): R { return this.rightValue; } } const either: Either<number, number>= new SimpleEither(4, 5); either.left(); either.right(); // ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ // ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ interface Employee { pay(): void; } class FullTimeEmployee implements Employee { pay() { console.log(`full time!!`); } workFullTime() { } } class PartTimeEmployee implements Employee { pay() { console.log(`part time!!`); } workPartTime() { } } // 세부적인 타입을 인자로 받아서 정말 추상적인 타입으로 다시 리턴하는 함수는 별로... function payBad(employee: Employee): Employee { employee.pay(); return employee; } function pay<T extends Employee>(employee: T): T { employee.pay(); return employee; } const ellie = new FullTimeEmployee(); const bob = new PartTimeEmployee(); ellie.workFullTime(); bob.workPartTime(); const ellieAfterPay = pay(ellie); const bobAfterPay = pay(bob); const obj = { name: 'ellie', age: 20, }; const obj2 = { animal: '🦮' , }; console.log(getValue(obj, 'name')); console.log(getValue(obj, 'age')); console.log(getValue(obj2, 'animal')); function getValue<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }
// move_semantics5.rs // Make me compile only by reordering the lines in `main()`, but without // adding, changing or removing any of them. // Execute `rustlings hint move_semantics5` for hints :) fn main() { //Rajout des commentaires pour comprendre le cheminement. // L'opérateur * permet de pointer vers une valeur ou de la Deref let mut x = 100; // println!("x vaut : {}", x); let y = &mut x; // println!("y vaut : {}", y); *y += 100; // println!("y vaut : {}", y); let z = &mut x; // println!("z vaut : {}", z); *z += 1000; // println!("z vaut : {}", z); // println!(); // println!(); // println!("{}", x); assert_eq!(x, 1200); }
import { MessagesRepository } from '../../domain/MessagesRepository'; import Message from '../../domain/Message'; import { Client, LocalAuth } from 'whatsapp-web.js'; import qrcode from 'qrcode-terminal'; import { EventBus } from '../../../Shared/domain/EventBus'; import { WhatsappMessageReceivedDomainEvent } from '../../domain/WhatsappMessageReceivedDomainEvent'; import { WhatsappMessageRepositoryConfig } from './WhatsappMessageRepositoryConfig'; class WhatsappMessageRepository implements MessagesRepository { constructor( private eventBus: EventBus, private config: WhatsappMessageRepositoryConfig, ) {} async publishNewMessages(): Promise<Message[]> { return new Promise(() => { const client = new Client({ webVersionCache: { type: 'remote', remotePath: 'https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/2.2412.54.html', }, authStrategy: new LocalAuth({ dataPath: '/usr/src/app/data' }), puppeteer: { headless: true, executablePath: '/usr/bin/chromium', args: [ '--no-sandbox', '--headless', '--autoplay-policy=no-user-gesture-required', '--no-first-run', '--disable-gpu', '--use-fake-ui-for-media-stream', '--use-fake-device-for-media-stream', '--disable-sync', ], timeout: 100000, }, }); client.on('qr', (qr) => { // Generate and scan this code with your phone qrcode.generate(qr, { small: true }); }); client.on('ready', async () => { const chat = await client.getChatById(this.config.chatId); const messages = await chat.fetchMessages({ limit: 10 }); const newMessagesEvents = messages .filter((msg) => msg.type === 'chat') .map( (msg) => new WhatsappMessageReceivedDomainEvent({ jsonRawData: JSON.stringify(msg.rawData), messageId: msg.id.id, body: msg.body, }), ); this.eventBus.publish(newMessagesEvents); }); client.on('message', async (msg) => { if (msg.type !== 'chat' || msg.fromMe) return; if ((await msg.getChat()).id._serialized !== this.config.chatId) return; this.eventBus.publish([ new WhatsappMessageReceivedDomainEvent({ jsonRawData: JSON.stringify(msg.rawData), messageId: msg.id.id, body: msg.body, }), ]); }); client.initialize(); }); } } export default WhatsappMessageRepository;
package project.persistence.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import project.persistence.entities.Cabinet; import java.util.List; import java.util.Optional; /** * By extending the {@link JpaRepository} we have access to powerful methods. * For detailed information, see: * http://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html * http://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html * */ /** * The cabinet repository uses mostly Spring commands. * Used for connecting users to their medicines. */ @Repository public interface CabinetRepository extends JpaRepository<Cabinet, Long> { Cabinet save(Cabinet cabinet); Cabinet findByUsersId(Long id); void delete(Cabinet cabinet); List<Cabinet> findAll(); @Query(value = "select c from Cabinet c where c.usersId = ?1" ) List<Cabinet> getMedsByUser(Long userId); }
import pandas as pd from sklearn.preprocessing import LabelEncoder, StandardScaler from sklearn.metrics import accuracy_score from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.model_selection import train_test_split, GridSearchCV # Load the data file_path = 'results_2019-20_with_sentiment.json' # Adjust to your correct file path df = pd.read_json(file_path) # Preprocessing df['DateTime'] = pd.to_datetime(df['DateTime']) df['Month'] = df['DateTime'].dt.month df['DayOfWeek'] = df['DateTime'].dt.dayofweek df.fillna({'HomeTeamScoreVader': 0, 'AwayTeamScoreVader': 0}, inplace=True) def prepare_data(include_sentiment=False): features = [ 'HomeTeam', 'AwayTeam', 'Referee', 'HS', 'AS', 'HST', 'AST', 'HC', 'AC', 'HF', 'AF', 'HY', 'AY', 'HR', 'AR', 'Month', 'DayOfWeek' ] if include_sentiment: features.extend(['HomeTeamScoreVader', 'AwayTeamScoreVader']) X = df[features] for column in ['HomeTeam', 'AwayTeam', 'Referee']: le = LabelEncoder() X[column] = le.fit_transform(X[column]) y = df['FTR'] return X, y # Split and scale data def split_and_scale(X, y): X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) return X_train_scaled, X_test_scaled, y_train, y_test # Initialize and train models def train_models(X_train_scaled, y_train): models = { 'GaussianNB': GaussianNB(), 'KNN': KNeighborsClassifier(), 'SVM': SVC(), } param_grid = {'C': [0.001, 0.01, 0.1, 1, 10, 100], 'penalty': ['l1', 'l2']} lr = LogisticRegression(max_iter=1000, solver='liblinear') grid_search = GridSearchCV(lr, param_grid, cv=5, scoring='accuracy') grid_search.fit(X_train_scaled, y_train) models['LogisticRegression'] = grid_search.best_estimator_ for name, model in models.items(): model.fit(X_train_scaled, y_train) return models # Evaluate models def evaluate_models(models, X_test_scaled, y_test, team_mapping, X_test): game_details = [] for index, (scaled_features, actual) in enumerate(zip(X_test_scaled, y_test)): predictions = {f"{name}_Prediction": model.predict([scaled_features])[0] for name, model in models.items()} # Decode team names using the original (unscaled) test data home_team = team_mapping[X_test.iloc[index]['HomeTeam']] away_team = team_mapping[X_test.iloc[index]['AwayTeam']] game_info = { "Game": f"{home_team} vs {away_team}", "Actual": actual, **predictions } game_details.append(game_info) # Convert game details into a DataFrame for nicer display games_df = pd.DataFrame(game_details) print(games_df.to_string(index=False)) # Print the DataFrame without the index # Calculate and print accuracies accuracies = {} print("\nModel Accuracies:") for name in models.keys(): accuracies[name] = games_df.apply(lambda row: row['Actual'] == row[f'{name}_Prediction'], axis=1).mean() print(f"{name}: {accuracies[name]:.4f}") # Team mapping for decoding team names team_encoder = LabelEncoder().fit(df['HomeTeam']) team_mapping = {index: label for index, label in enumerate(team_encoder.classes_)} # Assuming the models are trained and the data is prepared # Experiment without VADER scores print("Experiment without VADER Scores") X, y = prepare_data(include_sentiment=False) X_train_scaled, X_test_scaled, y_train, y_test = split_and_scale(X, y) models = train_models(X_train_scaled, y_train) evaluate_models(models, X_test_scaled, y_test, team_mapping, X.iloc[y_test.index]) # Experiment with VADER scores print("\nExperiment with VADER Scores") X, y = prepare_data(include_sentiment=True) X_train_scaled, X_test_scaled, y_train, y_test = split_and_scale(X, y) models = train_models(X_train_scaled, y_train) evaluate_models(models, X_test_scaled, y_test, team_mapping, X.iloc[y_test.index])
//===- HWLegalizeModulesPass.cpp - Lower unsupported IR features away -----===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This pass lowers away features in the SV/Comb/HW dialects that are // unsupported by some tools (e.g. multidimensional arrays) as specified by // LoweringOptions. This pass is run relatively late in the pipeline in // preparation for emission. Any passes run after this (e.g. PrettifyVerilog) // must be aware they cannot introduce new invalid constructs. // //===----------------------------------------------------------------------===// #include "PassDetail.h" #include "circt/Dialect/HW/HWOps.h" #include "circt/Dialect/HW/HWTypes.h" #include "circt/Dialect/SV/SVPasses.h" #include "circt/Support/LoweringOptions.h" #include "mlir/IR/Builders.h" using namespace circt; //===----------------------------------------------------------------------===// // HWLegalizeModulesPass //===----------------------------------------------------------------------===// namespace { struct HWLegalizeModulesPass : public sv::HWLegalizeModulesBase<HWLegalizeModulesPass> { void runOnOperation() override; private: void processPostOrder(Block &block); bool tryLoweringPackedArrayOp(Operation &op); Value lowerLookupToCasez(Operation &op, Value input, Value index, mlir::Type elementType, SmallVector<Value> caseValues); bool processUsers(Operation &op, Value value, ArrayRef<Value> mapping); std::optional<std::pair<uint64_t, unsigned>> tryExtractIndexAndBitWidth(Value value); /// This is the current hw.module being processed. hw::HWModuleOp thisHWModule; bool anythingChanged; /// This tells us what language features we're allowed to use in generated /// Verilog. LoweringOptions options; /// This pass will be run on multiple hw.modules, this keeps track of the /// contents of LoweringOptions so we don't have to reparse the /// LoweringOptions for every hw.module. StringAttr lastParsedOptions; }; } // end anonymous namespace bool HWLegalizeModulesPass::tryLoweringPackedArrayOp(Operation &op) { return TypeSwitch<Operation *, bool>(&op) .Case<hw::AggregateConstantOp>([&](hw::AggregateConstantOp constOp) { // Replace individual element uses (if any) with input fields. SmallVector<Value> inputs; OpBuilder builder(constOp); for (auto field : llvm::reverse(constOp.getFields())) { if (auto intAttr = dyn_cast<IntegerAttr>(field)) inputs.push_back( builder.create<hw::ConstantOp>(constOp.getLoc(), intAttr)); else inputs.push_back(builder.create<hw::AggregateConstantOp>( constOp.getLoc(), constOp.getType(), field.cast<ArrayAttr>())); } if (!processUsers(op, constOp.getResult(), inputs)) return false; // Remove original op. return true; }) .Case<hw::ArrayConcatOp>([&](hw::ArrayConcatOp concatOp) { // Redirect individual element uses (if any) to the input arguments. SmallVector<std::pair<Value, uint64_t>> arrays; for (auto array : llvm::reverse(concatOp.getInputs())) { auto ty = hw::type_cast<hw::ArrayType>(array.getType()); arrays.emplace_back(array, ty.getNumElements()); } for (auto *user : llvm::make_early_inc_range(concatOp.getResult().getUsers())) { if (TypeSwitch<Operation *, bool>(user) .Case<hw::ArrayGetOp>([&](hw::ArrayGetOp getOp) { if (auto indexAndBitWidth = tryExtractIndexAndBitWidth(getOp.getIndex())) { auto [indexValue, bitWidth] = *indexAndBitWidth; // FIXME: More efficient search for (const auto &[array, size] : arrays) { if (indexValue >= size) { indexValue -= size; continue; } OpBuilder builder(getOp); getOp.getInputMutable().set(array); getOp.getIndexMutable().set( builder.createOrFold<hw::ConstantOp>( getOp.getLoc(), APInt(bitWidth, indexValue))); return true; } } return false; }) .Default([](auto op) { return false; })) continue; op.emitError("unsupported packed array expression"); signalPassFailure(); } // Remove the original op. return true; }) .Case<hw::ArrayCreateOp>([&](hw::ArrayCreateOp createOp) { // Replace individual element uses (if any) with input arguments. SmallVector<Value> inputs(llvm::reverse(createOp.getInputs())); if (!processUsers(op, createOp.getResult(), inputs)) return false; // Remove original op. return true; }) .Case<hw::ArrayGetOp>([&](hw::ArrayGetOp getOp) { // Skip index ops with constant index. auto index = getOp.getIndex(); if (auto *definingOp = index.getDefiningOp()) if (isa<hw::ConstantOp>(definingOp)) return false; // Generate case value element lookups. auto ty = hw::type_cast<hw::ArrayType>(getOp.getInput().getType()); OpBuilder builder(getOp); SmallVector<Value> caseValues; for (size_t i = 0, e = ty.getNumElements(); i < e; i++) { auto loc = op.getLoc(); auto index = builder.createOrFold<hw::ConstantOp>( loc, APInt(llvm::Log2_64_Ceil(e), i)); auto element = builder.create<hw::ArrayGetOp>(loc, getOp.getInput(), index); caseValues.push_back(element); } // Transform array index op into casez statement. auto theWire = lowerLookupToCasez(op, getOp.getInput(), index, ty.getElementType(), caseValues); // Emit the read from the wire, replace uses and clean up. builder.setInsertionPoint(getOp); auto readWire = builder.create<sv::ReadInOutOp>(getOp.getLoc(), theWire); getOp.getResult().replaceAllUsesWith(readWire); return true; }) .Case<sv::ArrayIndexInOutOp>([&](sv::ArrayIndexInOutOp indexOp) { // Skip index ops with constant index. auto index = indexOp.getIndex(); if (auto *definingOp = index.getDefiningOp()) if (isa<hw::ConstantOp>(definingOp)) return false; // Skip index ops with unpacked arrays. auto inout = indexOp.getInput().getType(); if (hw::type_isa<hw::UnpackedArrayType>(inout.getElementType())) return false; // Generate case value element lookups. auto ty = hw::type_cast<hw::ArrayType>(inout.getElementType()); OpBuilder builder(&op); SmallVector<Value> caseValues; for (size_t i = 0, e = ty.getNumElements(); i < e; i++) { auto loc = op.getLoc(); auto index = builder.createOrFold<hw::ConstantOp>( loc, APInt(llvm::Log2_64_Ceil(e), i)); auto element = builder.create<sv::ArrayIndexInOutOp>( loc, indexOp.getInput(), index); auto readElement = builder.create<sv::ReadInOutOp>(loc, element); caseValues.push_back(readElement); } // Transform array index op into casez statement. auto theWire = lowerLookupToCasez(op, indexOp.getInput(), index, ty.getElementType(), caseValues); // Replace uses and clean up. indexOp.getResult().replaceAllUsesWith(theWire); return true; }) .Case<sv::PAssignOp>([&](sv::PAssignOp assignOp) { // Transform array assignment into individual assignments for each array // element. auto inout = assignOp.getDest().getType(); auto ty = hw::type_dyn_cast<hw::ArrayType>(inout.getElementType()); if (!ty) return false; OpBuilder builder(assignOp); for (size_t i = 0, e = ty.getNumElements(); i < e; i++) { auto loc = op.getLoc(); auto index = builder.createOrFold<hw::ConstantOp>( loc, APInt(llvm::Log2_64_Ceil(e), i)); auto dstElement = builder.create<sv::ArrayIndexInOutOp>( loc, assignOp.getDest(), index); auto srcElement = builder.create<hw::ArrayGetOp>(loc, assignOp.getSrc(), index); builder.create<sv::PAssignOp>(loc, dstElement, srcElement); } // Remove original assignment. return true; }) .Case<sv::RegOp>([&](sv::RegOp regOp) { // Transform array reg into individual regs for each array element. auto ty = hw::type_dyn_cast<hw::ArrayType>(regOp.getElementType()); if (!ty) return false; OpBuilder builder(regOp); auto name = StringAttr::get(regOp.getContext(), "name"); SmallVector<Value> elements; for (size_t i = 0, e = ty.getNumElements(); i < e; i++) { auto loc = op.getLoc(); auto element = builder.create<sv::RegOp>(loc, ty.getElementType()); if (auto nameAttr = regOp->getAttrOfType<StringAttr>(name)) { element.setNameAttr( StringAttr::get(regOp.getContext(), nameAttr.getValue())); } elements.push_back(element); } // Fix users to refer to individual element regs. if (!processUsers(op, regOp.getResult(), elements)) return false; // Remove original reg. return true; }) .Default([&](auto op) { return false; }); } Value HWLegalizeModulesPass::lowerLookupToCasez(Operation &op, Value input, Value index, mlir::Type elementType, SmallVector<Value> caseValues) { // Create the wire for the result of the casez in the // hw.module. OpBuilder builder(&op); auto theWire = builder.create<sv::RegOp>(op.getLoc(), elementType, builder.getStringAttr("casez_tmp")); builder.setInsertionPoint(&op); auto loc = input.getDefiningOp()->getLoc(); // A casez is a procedural operation, so if we're in a // non-procedural region we need to inject an always_comb // block. if (!op.getParentOp()->hasTrait<sv::ProceduralRegion>()) { auto alwaysComb = builder.create<sv::AlwaysCombOp>(loc); builder.setInsertionPointToEnd(alwaysComb.getBodyBlock()); } // If we are missing elements in the array (it is non-power of // two), then add a default 'X' value. if (1ULL << index.getType().getIntOrFloatBitWidth() != caseValues.size()) { caseValues.push_back(builder.create<sv::ConstantXOp>( op.getLoc(), op.getResult(0).getType())); } APInt caseValue(index.getType().getIntOrFloatBitWidth(), 0); auto *context = builder.getContext(); // Create the casez itself. builder.create<sv::CaseOp>( loc, CaseStmtType::CaseZStmt, index, caseValues.size(), [&](size_t caseIdx) -> std::unique_ptr<sv::CasePattern> { // Use a default pattern for the last value, even if we // are complete. This avoids tools thinking they need to // insert a latch due to potentially incomplete case // coverage. bool isDefault = caseIdx == caseValues.size() - 1; Value theValue = caseValues[caseIdx]; std::unique_ptr<sv::CasePattern> thePattern; if (isDefault) thePattern = std::make_unique<sv::CaseDefaultPattern>(context); else thePattern = std::make_unique<sv::CaseBitPattern>(caseValue, context); ++caseValue; builder.create<sv::BPAssignOp>(loc, theWire, theValue); return thePattern; }); return theWire; } bool HWLegalizeModulesPass::processUsers(Operation &op, Value value, ArrayRef<Value> mapping) { for (auto *user : llvm::make_early_inc_range(value.getUsers())) { if (TypeSwitch<Operation *, bool>(user) .Case<hw::ArrayGetOp>([&](hw::ArrayGetOp getOp) { if (auto indexAndBitWidth = tryExtractIndexAndBitWidth(getOp.getIndex())) { getOp.replaceAllUsesWith(mapping[indexAndBitWidth->first]); return true; } return false; }) .Case<sv::ArrayIndexInOutOp>([&](sv::ArrayIndexInOutOp indexOp) { if (auto indexAndBitWidth = tryExtractIndexAndBitWidth(indexOp.getIndex())) { indexOp.replaceAllUsesWith(mapping[indexAndBitWidth->first]); return true; } return false; }) .Default([](auto op) { return false; })) { user->erase(); continue; } user->emitError("unsupported packed array expression"); signalPassFailure(); return false; } return true; } std::optional<std::pair<uint64_t, unsigned>> HWLegalizeModulesPass::tryExtractIndexAndBitWidth(Value value) { if (auto constantOp = dyn_cast<hw::ConstantOp>(value.getDefiningOp())) { auto index = constantOp.getValue(); return std::make_optional( std::make_pair(index.getZExtValue(), index.getBitWidth())); } return std::nullopt; } void HWLegalizeModulesPass::processPostOrder(Block &body) { if (body.empty()) return; // Walk the block bottom-up, processing the region tree inside out. Block::iterator it = std::prev(body.end()); while (it != body.end()) { auto &op = *it; // Advance the iterator, using the end iterator as a sentinel that we're at // the top of the block. if (it == body.begin()) it = body.end(); else --it; if (op.getNumRegions()) { for (auto &region : op.getRegions()) for (auto &regionBlock : region.getBlocks()) processPostOrder(regionBlock); } if (options.disallowPackedArrays) { // Try supported packed array op lowering. if (tryLoweringPackedArrayOp(op)) { it = --Block::iterator(op); op.erase(); anythingChanged = true; continue; } // Otherwise, if the IR produces a packed array and we aren't allowing // multi-dimensional arrays, reject the IR as invalid. for (auto value : op.getResults()) { if (value.getType().isa<hw::ArrayType>()) { op.emitError("unsupported packed array expression"); signalPassFailure(); } } } } } void HWLegalizeModulesPass::runOnOperation() { thisHWModule = getOperation(); // Parse the lowering options if necessary. auto optionsAttr = LoweringOptions::getAttributeFrom( cast<ModuleOp>(thisHWModule->getParentOp())); if (optionsAttr != lastParsedOptions) { if (optionsAttr) options = LoweringOptions(optionsAttr.getValue(), [&](Twine error) { thisHWModule.emitError(error); }); else options = LoweringOptions(); lastParsedOptions = optionsAttr; } // Keeps track if anything changed during this pass, used to determine if // the analyses were preserved. anythingChanged = false; // Walk the operations in post-order, transforming any that are interesting. processPostOrder(*thisHWModule.getBodyBlock()); // If we did not change anything in the IR mark all analysis as preserved. if (!anythingChanged) markAllAnalysesPreserved(); } std::unique_ptr<Pass> circt::sv::createHWLegalizeModulesPass() { return std::make_unique<HWLegalizeModulesPass>(); }
// Import the employee service const employeeService = require("../services/employee.service"); // Create the add employee controller async function createEmployee(req, res, next) { // Check if employee email already exists in the database const employeeExists = await employeeService.checkIfEmployeeExists( req.body.employee_email ); // If employee exists, send a response to the client if (employeeExists) { res.status(400).json({ error: "This email address is already associated with another employee!", }); } else { try { // Validate request body const errors = validateCreateEmployee(req.body); if (errors) { return res.status(400).json({ errors }); } const employeeData = req.body; // Create the employee const employee = await employeeService.createEmployee(employeeData); if (!employee) { console.log(employee); res.status(400).json({ error: "Failed to add the employee!", }); } else { res.status(200).json({ status: "true", }); } } catch (error) { console.log(err); res.status(400).json({ error: "Something went wrong!", }); } } } // Create the getAllEmployees controller async function getAllEmployees(req, res, next) { // Call the getAllEmployees method from the employee service const employees = await employeeService.getAllEmployees(); // console.log(employees); if (!employees) { res.status(400).json({ error: "Failed to get all employees!", }); } else { res.status(200).json({ status: "success", data: employees, }); } } // Create the getSingleEmployee controller async function getSingleEmployee(req, res, next) { const employeeId = req.params.id; // Call the getSingleEmployee method from the employee service const employee = await employeeService.getSingleEmployee(employeeId); // console.log(employees); if (!employee) { res.status(400).json({ error: "Failed to get single employee!", }); } else { res.status(200).json( employee, ); } } // Create the updateEmployee controller const updateEmployee = async (req, res) => { try { const EmployeeId = req.params.id; const updatedEmployee = await employeeService.updateEmployee( EmployeeId, req.body ); if (!updatedEmployee) { return res.status(404).json({ error: "Employee not exist", }); } res.status(200).json({ status: "true", Employee: updatedEmployee, }); } catch (error) { console.error(error); res.status(500).json({ error: "Internal Server Error", }); } }; // Employee validation function for createEmployee const validateCreateEmployee = (employeeData) => { const errors = []; // Add your validation logic here if ( !employeeData.employee_email || !isValidEmail(employeeData.employee_email) ) { errors.push({ param: "employee_email", msg: "Invalid email address" }); } // Add more validation checks as needed return errors.length > 0 ? errors : null; }; // Employee validation function for email format const isValidEmail = (email) => { // Implement your email validation logic // For simplicity, a basic check is shown here return /\S+@\S+\.\S+/.test(email); }; // Export the createEmployee controller module.exports = { createEmployee, getAllEmployees, getSingleEmployee, updateEmployee, };
/* SINTESIS FM: Historia: La síntesis FM fue desarrollada e introducida por John Chowning en los años 60 y 70 en el Instituto de Investigación de Música Computacional de la Universidad de Stanford. Posteriormente, esta técnica fue popularizada por Yamaha con su icónico sintetizador DX7 en 1983. Desde entonces, la síntesis FM ha sido un pilar en la música electrónica y el diseño de sonido. Concepto Básico: La síntesis FM implica la modulación de la frecuencia de una onda (llamada portadora) por otra onda (llamada moduladora). El resultado es una generación compleja de armónicos que puede dar lugar a timbres muy variados y ricos. Parámetros Clave: Portadora (Carrier): La onda principal cuya frecuencia se modula. Moduladora (Modulator): La onda que modula la frecuencia de la portadora. Índice de Modulación: Determina la cantidad de modulación. Un índice más alto resulta en timbres más complejos. */ /* Indice Modulación: es simplemente una medida de cuánta modulación de frecuencia se está aplicando. Específicamente, se refiere a la cantidad en la que la frecuencia de la onda portadora está siendo modulada por la onda moduladora. Formula: Frecuencia Modulada = FreP + (indiceM * amplitud de la moduladora) Impacto del índice de modulación: Bajo:Con valores bajos de IM, la modulación es sutil. Esto resulta en cambios leves en el timbre del sonido. En general, el sonido resultante será más simple y tendrá menos armónicos. la modulación se suaviza, y el sonido resultante tiende a ser más suave y menos armónico. Es útil para sonidos más limpios y tonales. Altos: Con valores altos de IM, la modulación es intensa. Esto puede introducir una gran cantidad de armónicos adicionales, lo que hace que el sonido sea más rico y complejo. Los sonidos pueden variar desde metálicos hasta atonales, dependiendo de otros parámetros. el sonido se vuelve más rico en armónicos y adquiere un carácter más metálico o agresivo. En síntesis FM, esto es útil para crear sonidos como campanas, bajos metálicos, y efectos de sonido atonales. */ //EJEMPLOS: ( SynthDef(\fmBass, { arg freq=100, amp=0.5, modIndex=5, modFreqRatio=0.5, freqModulator=200; var carrier, modulator, result; modulator = SinOsc.ar(freqModulator * modFreqRatio) * modIndex; carrier = SinOsc.ar(freq + modulator); result = carrier * amp; Out.ar(0, result); }).add; ) x = Synth(\fmBass, [\freq, rrand(100, 800), \amp, 0.2, \modIndex, 10, \modFreqRatio, 0.2, \freqModulator, rrand(100, 900)]); //CAMPANA FM ( SynthDef(\fmBell, { arg freq=660, amp=0.5, modIndex=7, modFreqRatio=2; var carrier, modulator, result, env; env = EnvGen.kr(Env.perc(0.01, 1), doneAction:2); modulator = SinOsc.ar(freq * modFreqRatio) * modIndex; carrier = SinOsc.ar(freq + modulator); result = carrier * amp * env; Out.ar(0, result); }).add; ) x = Synth(\fmBell, [\freq, 700, \amp, 0.2, \modIndex, 2, \modFreqRatio, 2]) //PAD FM RADIO ( SynthDef(\fmPad, { arg freq=440, amp=0.5, modIndex=3, freqMod=200; var carrier, modulator, result, env; env = EnvGen.kr(Env.adsr(2, 1, 0.5, 2), doneAction:2); modulator = SinOsc.ar(freqMod) * modIndex; carrier = SinOsc.ar(freq + modulator); result = carrier * amp * env; Out.ar(0, result!2); }).add; ) x = Synth(\fmPad, [\freq, 200, \amp, 0.2, \modIndex, 0.2, \freqMod, 700]) //El modFreqRatio solamente es NECESARIO cuando no tenemos una frecuencia especifica para ambos, y lo traza en razón (porque sino serían lo mismo)
import React, {useContext, forwardRef} from 'react'; import {makeStyles, Theme, createStyles} from '@material-ui/core/styles'; import {useFormik} from 'formik'; import * as yup from 'yup'; import Button from '@material-ui/core/Button'; import IconButton from '@material-ui/core/IconButton'; import TextField from '@material-ui/core/TextField'; import PropTypes from 'prop-types'; import DialogContent from '@material-ui/core/DialogContent'; import DialogTitle from '@material-ui/core/DialogTitle'; import {Container} from '@material-ui/core'; import CancelIcon from '@material-ui/icons/Cancel'; import clsx from 'clsx'; import {RestContext} from '../../context/RestContext'; import UploadImage from '../common/UploadImage'; import { addMinutes, dateRoundedToQuarterHour, formatDateForPicker, } from '@webrtc/backend/dist/shared/util/timeHelpers'; import {FILE_SIZE, SUPPORTED_FORMATS} from '../../util/constants'; import {AppStateContext} from '../../context/AppStateContext'; import {FormProps} from '../../util/types'; const validationSchema = yup.object({ title: yup .string() .min(4, 'Title should be at least 4 characters') .defined('Title is required'), description: yup .string() .min(4, 'Description should be at least 4 characters') .defined('Description is required'), start: yup .date() .min(new Date(), 'Start time cannot be in past') .defined('Start date is required'), end: yup .date() .min(yup.ref('start'), 'End time cannot be before start time' ) .defined('End date is required'), iconImage: yup .mixed() .test('fileSize', 'File size is too large', (value) => !value || (value && value.size <= FILE_SIZE), ) .test('fileType', 'Unsupported File Format', (value) => !value || SUPPORTED_FORMATS.includes(value.type), ), }); const useStyles = makeStyles((theme: Theme) => createStyles({ paper: { backgroundColor: theme.palette.background.paper, borderRadius: theme.shape.borderRadius, boxShadow: theme.shadows[5], padding: theme.spacing(2, 4, 3), minWidth: 800, display: 'flex', flexDirection: 'column', [theme.breakpoints.down('sm')]: { minWidth: 0, padding: theme.spacing(2, 0, 1), }, }, titleItem: { [theme.breakpoints.down('sm')]: { alignSelf: 'center', }, }, formContainer: { flexDirection: 'column', alignItems: 'center', flexWrap: 'nowrap', alignContent: 'center', width: '100%', }, formItem: { margin: theme.spacing(1, 0, 3), flexShrink: 1, flexWrap: 'nowrap', width: '70%', [theme.breakpoints.down('sm')]: { width: '100%', alignContent: 'center', justifyContent: 'center', padding: theme.spacing(1, 0, 1), margin: theme.spacing(1, 0, 2), }, }, nameItem: { margin: theme.spacing(1, 1, 1), flexShrink: 1, width: '100%', [theme.breakpoints.down('sm')]: { padding: theme.spacing(1, 0, 1), }, }, dateField: { margin: theme.spacing(1, 2, 1), minWidth: 220, width: '100%', [theme.breakpoints.down('sm')]: { padding: theme.spacing(1, 0, 1), margin: theme.spacing(1, 0, 2), }, }, startDate: { [theme.breakpoints.down('sm')]: { order: 2, }, }, endDate: { [theme.breakpoints.down('sm')]: { order: 3, }, }, dateContainer: { display: 'flex', flexDirection: 'row', flexWrap: 'nowrap', justifyContent: 'space-around', alignItems: 'center', alignContent: 'space-between', [theme.breakpoints.down('sm')]: { flexDirection: 'column', padding: 0, flexWrap: 'nowrap', width: '100%', justifyContent: 'center', alignContent: 'center', alignItems: 'center', }, }, helperText: { position: 'absolute', bottom: -20, [theme.breakpoints.down('sm')]: { bottom: -12, }, }, upload: { boxShadow: theme.shadows[1], backgroundColor: theme.palette.secondary.light, }, closeButton: { position: 'absolute', top: '3%', left: '5%', fontSize: 40, [theme.breakpoints.up('md')]: { display: 'none', }, }, }), ); /** * A forward reference exotic component that renders new meeting form. * The component is intended to be rendered inside of a Modal. * A ref is forwarded through the component from it's props to a * div element wrapping DialogTitle and DialogContent. The forward ref allows * the form to be rendered in a Modal component transparently without * breaking any of the functionality of the Modal or introducing * accessibility issues. * @param {React.Dispatch<React.SetStateAction<boolean>>} setOpen A function * that sets the state of a boolean variable representing whether the * modal should open. * @type {React.ForwardRefExoticComponent<React.PropsWithoutRef<FormProps> * & React.RefAttributes<HTMLDivElement>>} */ const NewMeetingForm = forwardRef<HTMLDivElement, FormProps>(({ setOpen, }, ref) => { const {createMeeting} = useContext(RestContext); const {sm} = useContext(AppStateContext); const classes = useStyles(); const handleClose = () => { setOpen(false); }; const defaultStartTime = formatDateForPicker(dateRoundedToQuarterHour); const defaultEndTime = formatDateForPicker( addMinutes(dateRoundedToQuarterHour, 30), ); const formik = useFormik({ initialValues: { title: '', description: '', start: defaultStartTime, end: defaultEndTime, iconImage: '', }, validationSchema: validationSchema, onSubmit: (values, {setSubmitting}) => { const {start, end, ...otherValues} = values; const newMeeting = { start: new Date(start), end: new Date(end), ...otherValues, }; setTimeout(async () => { if (!createMeeting) return; createMeeting(newMeeting).then( (result) => { if (result) handleClose(); setSubmitting(false); }); }, 500); }, }); return ( <div className={classes.paper} ref={ref}> <DialogTitle className={classes.titleItem} id="new-meeting-form-title" > New Meeting </DialogTitle> <DialogContent > <Container className={classes.formContainer}> <IconButton size={'medium'} className={classes.closeButton} color="secondary" aria-label="cancel" onClick={handleClose} > <CancelIcon fontSize={'inherit'}/> </IconButton> <form onSubmit={formik.handleSubmit}> <Container className={classes.dateContainer}> <TextField className={clsx(classes.startDate, classes.dateField)} fullWidth={sm?? false} id="start" label="Starts" type="datetime-local" variant="outlined" InputLabelProps={{ shrink: true, }} value={formik.values.start} onBlur={formik.handleBlur} onChange={formik.handleChange('start')} error={ formik.touched.start && Boolean(formik.errors.start) } helperText={formik.touched.start && formik.errors.start} FormHelperTextProps={{className: classes.helperText}} /> <TextField className={clsx(classes.endDate, classes.dateField)} fullWidth={sm?? false} id="end" label="Ends" type="datetime-local" variant="outlined" InputLabelProps={{ shrink: true, }} value={formik.values.end} onBlur={formik.handleBlur} onChange={formik.handleChange('end')} error={ formik.touched.end && Boolean(formik.errors.end) } helperText={formik.touched.end && formik.errors.end} /> <UploadImage formik={formik} buttonProps={{ variant: sm? 'contained': 'text', className: classes.upload, }} /> </Container> <TextField fullWidth className={classes.formItem} autoComplete='off' variant="outlined" id="title" name="title" label="Title" value={formik.values.title} onBlur={formik.handleBlur} onChange={formik.handleChange} error={formik.touched.title && Boolean(formik.errors.title)} helperText={formik.touched.title && formik.errors.title} FormHelperTextProps={{className: classes.helperText}} /> <TextField fullWidth multiline maxRows={4} className={classes.formItem} autoComplete='off' variant="outlined" id="description" name="description" label="Description" value={formik.values.description} onBlur={formik.handleBlur} onChange={formik.handleChange} error={ formik.touched.description && Boolean(formik.errors.description) } helperText={ formik.touched.description && formik.errors.description } FormHelperTextProps={{className: classes.helperText}} /> <Button className={classes.formItem} color="primary" variant="contained" fullWidth type="submit" > Submit </Button> </form> </Container> </DialogContent> </div> ); }); NewMeetingForm.propTypes = { setOpen: PropTypes.func.isRequired, }; NewMeetingForm.displayName = 'New Meeting Form'; export default NewMeetingForm;
// Capturo el div contenedor y traigo las notas del localStorage const contenedor = document.querySelector('.contenedor'); const notes = JSON.parse(localStorage.getItem('notes')) // Si existen las notas, creo el html para agregarlas con el formato correspondiente if (notes) { for (let i = 0; i < notes.length; i++) { const element = notes[i]; if (element.length >= 1) { contenedor.innerHTML += ` <div class='notes'> <div class="tools"> <button class="edit"><i class="fas fa-edit"></i></button> <button class="delete"><i class="far fa-trash-alt"></i></button> </div> <div class="divMain"> <span class="spanMain">${element}</span> </div> <textarea class='hidden'>${element}</textarea> </div> ` }} // Ejecuto la funcion una vez para que cargue los botones de las notas nuevas // Puedo ejecutar la funcion antes de declararla gracias al hoisting de js capturarEventos(); } // Creo la funcion donde capturo todos los elementos de cada post-it // y creo el for each de cada array de elementos que capture, para // agregarle funcionalidad a los botones function capturarEventos() { const editBtn = document.querySelectorAll('.edit'); const deleteBtn = document.querySelectorAll('.delete'); const textArea = document.querySelectorAll('textarea'); const spanMain = document.querySelectorAll('.spanMain'); editBtn.forEach((btn, i) => { btn.addEventListener('click', () => { // Aca toggleo las clases hidden, para que se deje de ver el textArea y se vea el span de la nota spanMain[i].classList.toggle('hidden'); textArea[i].classList.toggle('hidden'); // Aca guardo el valor del textArea en el span de la nota spanMain[i].innerText = textArea[i].value; updateLs() }); }); deleteBtn.forEach((btn, i) => { btn.addEventListener('click', () => { if (spanMain[i].innerText.length === 0 && textArea[i].value.length === 0) { const notes = document.querySelectorAll('.notes'); contenedor.removeChild(notes[i]); } if (spanMain[i].innerText.length >= 1 || textArea[i].value.length >= 1) { spanMain[i].innerText = ''; textArea[i].value = ''; } updateLs() }) }); } // Obtengo el boton de agregar nota y contenedor para los div de las notas, // agrego el div html de las notas, ademas ejecuto la funcion capturarEventos() de nuevo // para poder asignarle a los botones del nuevo div funcionalidad tmb const addNoteBtn = document.querySelector('.addNoteBtn'); addNoteBtn.addEventListener('click', () => { contenedor.innerHTML += ` <div class='notes'> <div class="tools"> <button class="edit"><i class="fas fa-edit"></i></button> <button class="delete"><i class="far fa-trash-alt"></i></button> </div> <span class="spanMain hidden"></span> <textarea></textarea> </div> ` capturarEventos(); }); function updateLs() { const spanMain = document.querySelectorAll('.spanMain'); const notesArray = []; spanMain.forEach(note => { notesArray.push(note.innerText) }) localStorage.setItem('notes', JSON.stringify(notesArray)); }
<template> <div class="navbar"> <hamburger :is-active="sidebar.opened" class="hamburger-container" @toggleClick="toggleSideBar" /> <breadcrumb class="breadcrumb-container" /> <div class="right-menu"> <el-dropdown class="avatar-container" trigger="click"> <div class="avatar-wrapper"> <img :src="avatar + '?imageView2/1/w/80/h/80'" class="user-avatar"> <i class="el-icon-caret-bottom" /> </div> <el-dropdown-menu slot="dropdown" class="user-dropdown"> <router-link to="/"> <el-dropdown-item> Home </el-dropdown-item> </router-link> <el-dropdown-item> 谷歌身份验证 <el-switch v-model="auth" active-color="#13ce66" inactive-color="#ff4949" active-value="1" inactive-value="0" @change="getGoogelCode" /> </el-dropdown-item> <el-dropdown-item class="user-dropdown" @click.native="()=> modifyVisible = true"> 修改密码 </el-dropdown-item> <!-- <a target="_blank" href="https://github.com/PanJiaChen/vue-admin-template/"> <el-dropdown-item>Github</el-dropdown-item> </a> <a target="_blank" href="https://panjiachen.github.io/vue-element-admin-site/#/"> <el-dropdown-item>Docs</el-dropdown-item> </a> --> <el-dropdown-item divided @click.native="logout"> <span style="display: block">退出</span> </el-dropdown-item> </el-dropdown-menu> </el-dropdown> </div> <!-- 谷歌验证器 --> <el-dialog title="谷歌验证器" :visible.sync="dialogVisible" width="40%"> <p>1.秘钥绑定</p> <div style="padding: 30px; background-color: #f2f2f2"> <p>账号:{{ account }}</p> <p>秘钥:{{ serect }}</p> </div> <div> <p>2.扫码绑定(使用Geogle身份验证器 APP 扫码)</p> </div> <div id="qrcode" /> <p style="text-align: center"> 请使用“Google 身份验证器APP” 绑定,各大软件商店均可下载该APP,支持安卓、IOS系统。 </p> <p style="text-align: center; color: #f56c6c"> 开启服务后,请立即使用“Google 身份验证器APP” 绑定,以免出现无法登录的情况。 </p> </el-dialog> <ModifyPassword :visible.sync="modifyVisible" /> </div> </template> <script> import { mapGetters } from 'vuex' import Breadcrumb from '@/components/Breadcrumb' import Hamburger from '@/components/Hamburger' import { createGoogleAuth } from '@/api/business' import QRCode from 'qrcodejs2' import store from '@/store' import ModifyPassword from '@/components/ModifyPassword' export default { components: { Breadcrumb, Hamburger, ModifyPassword }, data() { return { auth: '0', dialogVisible: false, account: '', serect: '', modifyVisible: false } }, computed: { ...mapGetters(['sidebar', 'avatar']) }, created() { this.auth = `${store.getters.status}` }, methods: { toggleSideBar() { this.$store.dispatch('app/toggleSideBar') }, async logout() { await this.$store.dispatch('user/logout') this.$router.push(`/login?redirect=${this.$route.fullPath}`) }, // 获取谷歌验证码 getGoogelCode() { createGoogleAuth({ status: this.auth }) .then((res) => { if (this.auth == 0) { this.$message.success('操作成功') } else { this.dialogVisible = true this.account = res.name this.serect = res.code this.$nextTick(() => { const qrcode = new QRCode('qrcode', { width: 200, height: 200, text: res.qr // 二维码地址 }) }) } }) .catch((err) => { console.log(err) }) } } } </script> <style lang="scss" scoped> .navbar { height: 50px; overflow: hidden; position: relative; background: #fff; box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08); .hamburger-container { line-height: 46px; height: 100%; float: left; cursor: pointer; transition: background 0.3s; -webkit-tap-highlight-color: transparent; &:hover { background: rgba(0, 0, 0, 0.025); } } .breadcrumb-container { float: left; } .right-menu { float: right; height: 100%; line-height: 50px; &:focus { outline: none; } .right-menu-item { display: inline-block; padding: 0 8px; height: 100%; font-size: 18px; color: #5a5e66; vertical-align: text-bottom; &.hover-effect { cursor: pointer; transition: background 0.3s; &:hover { background: rgba(0, 0, 0, 0.025); } } } .avatar-container { margin-right: 30px; .avatar-wrapper { margin-top: 5px; position: relative; .user-avatar { cursor: pointer; width: 40px; height: 40px; border-radius: 10px; } .el-icon-caret-bottom { cursor: pointer; position: absolute; right: -20px; top: 25px; font-size: 12px; } } } } } #qrcode { display: flex; align-items: center; justify-content: center; } </style>
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { PlagaEnfermedadService } from 'src/app/services/plaga-enfermedad.service'; @Component({ selector: 'app-plaga-enfermedad', templateUrl: './plaga-enfermedad.component.html', styleUrls: ['./plaga-enfermedad.component.css'] }) export class PlagaEnfermedadComponent implements OnInit { crearPlagaEnfermedad: FormGroup; submitted = false; plagasEnfermedades: any [] = []; idEliminar: String = ""; constructor(private fb: FormBuilder, private plagaEnfermedadService: PlagaEnfermedadService) { this.crearPlagaEnfermedad = this.fb.group({ nombre: ['', [Validators.required, Validators.maxLength(10)]], nombreCientifico: ['', Validators.required], }) } ngOnInit(): void { this.readPlagasEnfermedades(); } agregarPlagaEnfermedad(){ // validacion de los campos llenados this.submitted = true; if(this.crearPlagaEnfermedad.invalid){ return; } const plagaEnfermedad: any= { nombre: this.crearPlagaEnfermedad.value.nombre, nombreCientifico: this.crearPlagaEnfermedad.value.nombreCientifico, // fecha del sistema // fechaCreacion: new Date(), // fechaActualizacion : new Date() } this.plagaEnfermedadService.create(plagaEnfermedad) .subscribe( response => { console.log(response); this.submitted = true; location.reload(); }, error => { console.log(error); }); } readPlagasEnfermedades(): void { this.plagaEnfermedadService.readAll() .subscribe(data => { this.plagasEnfermedades = data; }, error => { console.log(error); }); } get nombre() { return this.crearPlagaEnfermedad.get('nombre'); } get nombreCientifico() { return this.crearPlagaEnfermedad.get('nombreCientifico'); } getIdEliminar(id: String){ this.idEliminar = id; } eliminarPlagaEnfermedad(){ this.plagaEnfermedadService.delete(this.idEliminar) .subscribe(data => { console.log(data); location.reload(); }, error => { console.log(error); }); } }
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.android_webview.test; import android.graphics.Bitmap; import android.graphics.Picture; import android.net.http.SslError; import android.webkit.ConsoleMessage; import android.webkit.ValueCallback; import org.chromium.android_webview.AwContentsClient.AwWebResourceRequest; import org.chromium.android_webview.AwWebResourceResponse; import org.chromium.base.ThreadUtils; import org.chromium.content.browser.test.util.CallbackHelper; import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnEvaluateJavaScriptResultHelper; import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnPageCommitVisibleHelper; import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnPageFinishedHelper; import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnPageStartedHelper; import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnReceivedErrorHelper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * AwContentsClient subclass used for testing. */ public class TestAwContentsClient extends NullContentsClient { private boolean mAllowSslError; private final OnPageStartedHelper mOnPageStartedHelper; private final OnPageFinishedHelper mOnPageFinishedHelper; private final OnPageCommitVisibleHelper mOnPageCommitVisibleHelper; private final OnReceivedErrorHelper mOnReceivedErrorHelper; private final OnReceivedError2Helper mOnReceivedError2Helper; private final OnReceivedHttpErrorHelper mOnReceivedHttpErrorHelper; private final CallbackHelper mOnReceivedSslErrorHelper; private final OnDownloadStartHelper mOnDownloadStartHelper; private final OnReceivedLoginRequestHelper mOnReceivedLoginRequestHelper; private final OnEvaluateJavaScriptResultHelper mOnEvaluateJavaScriptResultHelper; private final AddMessageToConsoleHelper mAddMessageToConsoleHelper; private final OnScaleChangedHelper mOnScaleChangedHelper; private final OnReceivedTitleHelper mOnReceivedTitleHelper; private final PictureListenerHelper mPictureListenerHelper; private final ShouldOverrideUrlLoadingHelper mShouldOverrideUrlLoadingHelper; private final DoUpdateVisitedHistoryHelper mDoUpdateVisitedHistoryHelper; private final OnCreateWindowHelper mOnCreateWindowHelper; private final FaviconHelper mFaviconHelper; private final TouchIconHelper mTouchIconHelper; public TestAwContentsClient() { super(ThreadUtils.getUiThreadLooper()); mOnPageStartedHelper = new OnPageStartedHelper(); mOnPageFinishedHelper = new OnPageFinishedHelper(); mOnPageCommitVisibleHelper = new OnPageCommitVisibleHelper(); mOnReceivedErrorHelper = new OnReceivedErrorHelper(); mOnReceivedError2Helper = new OnReceivedError2Helper(); mOnReceivedHttpErrorHelper = new OnReceivedHttpErrorHelper(); mOnReceivedSslErrorHelper = new CallbackHelper(); mOnDownloadStartHelper = new OnDownloadStartHelper(); mOnReceivedLoginRequestHelper = new OnReceivedLoginRequestHelper(); mOnEvaluateJavaScriptResultHelper = new OnEvaluateJavaScriptResultHelper(); mAddMessageToConsoleHelper = new AddMessageToConsoleHelper(); mOnScaleChangedHelper = new OnScaleChangedHelper(); mOnReceivedTitleHelper = new OnReceivedTitleHelper(); mPictureListenerHelper = new PictureListenerHelper(); mShouldOverrideUrlLoadingHelper = new ShouldOverrideUrlLoadingHelper(); mDoUpdateVisitedHistoryHelper = new DoUpdateVisitedHistoryHelper(); mOnCreateWindowHelper = new OnCreateWindowHelper(); mFaviconHelper = new FaviconHelper(); mTouchIconHelper = new TouchIconHelper(); mAllowSslError = true; } public OnPageStartedHelper getOnPageStartedHelper() { return mOnPageStartedHelper; } public OnPageCommitVisibleHelper getOnPageCommitVisibleHelper() { return mOnPageCommitVisibleHelper; } public OnPageFinishedHelper getOnPageFinishedHelper() { return mOnPageFinishedHelper; } public OnReceivedErrorHelper getOnReceivedErrorHelper() { return mOnReceivedErrorHelper; } public OnReceivedError2Helper getOnReceivedError2Helper() { return mOnReceivedError2Helper; } public OnReceivedHttpErrorHelper getOnReceivedHttpErrorHelper() { return mOnReceivedHttpErrorHelper; } public CallbackHelper getOnReceivedSslErrorHelper() { return mOnReceivedSslErrorHelper; } public OnDownloadStartHelper getOnDownloadStartHelper() { return mOnDownloadStartHelper; } public OnReceivedLoginRequestHelper getOnReceivedLoginRequestHelper() { return mOnReceivedLoginRequestHelper; } public OnEvaluateJavaScriptResultHelper getOnEvaluateJavaScriptResultHelper() { return mOnEvaluateJavaScriptResultHelper; } public ShouldOverrideUrlLoadingHelper getShouldOverrideUrlLoadingHelper() { return mShouldOverrideUrlLoadingHelper; } public AddMessageToConsoleHelper getAddMessageToConsoleHelper() { return mAddMessageToConsoleHelper; } public DoUpdateVisitedHistoryHelper getDoUpdateVisitedHistoryHelper() { return mDoUpdateVisitedHistoryHelper; } public OnCreateWindowHelper getOnCreateWindowHelper() { return mOnCreateWindowHelper; } public FaviconHelper getFaviconHelper() { return mFaviconHelper; } public TouchIconHelper getTouchIconHelper() { return mTouchIconHelper; } /** * Callback helper for onScaleChangedScaled. */ public static class OnScaleChangedHelper extends CallbackHelper { private float mPreviousScale; private float mCurrentScale; public void notifyCalled(float oldScale, float newScale) { mPreviousScale = oldScale; mCurrentScale = newScale; super.notifyCalled(); } public float getOldScale() { return mPreviousScale; } public float getNewScale() { return mCurrentScale; } public float getLastScaleRatio() { assert getCallCount() > 0; return mCurrentScale / mPreviousScale; } } public OnScaleChangedHelper getOnScaleChangedHelper() { return mOnScaleChangedHelper; } public PictureListenerHelper getPictureListenerHelper() { return mPictureListenerHelper; } /** * Callback helper for onReceivedTitle. */ public static class OnReceivedTitleHelper extends CallbackHelper { private String mTitle; public void notifyCalled(String title) { mTitle = title; super.notifyCalled(); } public String getTitle() { return mTitle; } } public OnReceivedTitleHelper getOnReceivedTitleHelper() { return mOnReceivedTitleHelper; } @Override public void onReceivedTitle(String title) { mOnReceivedTitleHelper.notifyCalled(title); } public String getUpdatedTitle() { return mOnReceivedTitleHelper.getTitle(); } @Override public void onPageStarted(String url) { mOnPageStartedHelper.notifyCalled(url); } @Override public void onPageCommitVisible(String url) { mOnPageCommitVisibleHelper.notifyCalled(url); } @Override public void onPageFinished(String url) { mOnPageFinishedHelper.notifyCalled(url); } @Override public void onReceivedError(int errorCode, String description, String failingUrl) { mOnReceivedErrorHelper.notifyCalled(errorCode, description, failingUrl); } @Override public void onReceivedError2(AwWebResourceRequest request, AwWebResourceError error) { mOnReceivedError2Helper.notifyCalled(request, error); } @Override public void onReceivedSslError(ValueCallback<Boolean> callback, SslError error) { callback.onReceiveValue(mAllowSslError); mOnReceivedSslErrorHelper.notifyCalled(); } public void setAllowSslError(boolean allow) { mAllowSslError = allow; } /** * CallbackHelper for OnDownloadStart. */ public static class OnDownloadStartHelper extends CallbackHelper { private String mUrl; private String mUserAgent; private String mContentDisposition; private String mMimeType; long mContentLength; public String getUrl() { assert getCallCount() > 0; return mUrl; } public String getUserAgent() { assert getCallCount() > 0; return mUserAgent; } public String getContentDisposition() { assert getCallCount() > 0; return mContentDisposition; } public String getMimeType() { assert getCallCount() > 0; return mMimeType; } public long getContentLength() { assert getCallCount() > 0; return mContentLength; } public void notifyCalled(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) { mUrl = url; mUserAgent = userAgent; mContentDisposition = contentDisposition; mMimeType = mimeType; mContentLength = contentLength; notifyCalled(); } } @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) { getOnDownloadStartHelper().notifyCalled(url, userAgent, contentDisposition, mimeType, contentLength); } /** * Callback helper for onCreateWindow. */ public static class OnCreateWindowHelper extends CallbackHelper { private boolean mIsDialog; private boolean mIsUserGesture; private boolean mReturnValue; public boolean getIsDialog() { assert getCallCount() > 0; return mIsDialog; } public boolean getUserAgent() { assert getCallCount() > 0; return mIsUserGesture; } public void setReturnValue(boolean returnValue) { mReturnValue = returnValue; } public boolean notifyCalled(boolean isDialog, boolean isUserGesture) { mIsDialog = isDialog; mIsUserGesture = isUserGesture; boolean returnValue = mReturnValue; notifyCalled(); return returnValue; } } @Override public boolean onCreateWindow(boolean isDialog, boolean isUserGesture) { return mOnCreateWindowHelper.notifyCalled(isDialog, isUserGesture); } /** * CallbackHelper for OnReceivedLoginRequest. */ public static class OnReceivedLoginRequestHelper extends CallbackHelper { private String mRealm; private String mAccount; private String mArgs; public String getRealm() { assert getCallCount() > 0; return mRealm; } public String getAccount() { assert getCallCount() > 0; return mAccount; } public String getArgs() { assert getCallCount() > 0; return mArgs; } public void notifyCalled(String realm, String account, String args) { mRealm = realm; mAccount = account; mArgs = args; notifyCalled(); } } @Override public void onReceivedLoginRequest(String realm, String account, String args) { getOnReceivedLoginRequestHelper().notifyCalled(realm, account, args); } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { mAddMessageToConsoleHelper.notifyCalled(consoleMessage); return false; } /** * Callback helper for AddMessageToConsole. */ public static class AddMessageToConsoleHelper extends CallbackHelper { private List<ConsoleMessage> mMessages = new ArrayList<ConsoleMessage>(); public void clearMessages() { mMessages.clear(); } public List<ConsoleMessage> getMessages() { return mMessages; } public int getLevel() { assert getCallCount() > 0; return getLastMessage().messageLevel().ordinal(); } public String getMessage() { assert getCallCount() > 0; return getLastMessage().message(); } public int getLineNumber() { assert getCallCount() > 0; return getLastMessage().lineNumber(); } public String getSourceId() { assert getCallCount() > 0; return getLastMessage().sourceId(); } private ConsoleMessage getLastMessage() { return mMessages.get(mMessages.size() - 1); } void notifyCalled(ConsoleMessage message) { mMessages.add(message); notifyCalled(); } } @Override public void onScaleChangedScaled(float oldScale, float newScale) { mOnScaleChangedHelper.notifyCalled(oldScale, newScale); } /** * Callback helper for PictureListener. */ public static class PictureListenerHelper extends CallbackHelper { // Generally null, depending on |invalidationOnly| in enableOnNewPicture() private Picture mPicture; public Picture getPicture() { assert getCallCount() > 0; return mPicture; } void notifyCalled(Picture picture) { mPicture = picture; notifyCalled(); } } @Override public void onNewPicture(Picture picture) { mPictureListenerHelper.notifyCalled(picture); } /** * Callback helper for ShouldOverrideUrlLoading. */ public static class ShouldOverrideUrlLoadingHelper extends CallbackHelper { private String mShouldOverrideUrlLoadingUrl; private boolean mShouldOverrideUrlLoadingReturnValue = false; private boolean mIsRedirect; private boolean mHasUserGesture; private boolean mIsMainFrame; void setShouldOverrideUrlLoadingUrl(String url) { mShouldOverrideUrlLoadingUrl = url; } void setShouldOverrideUrlLoadingReturnValue(boolean value) { mShouldOverrideUrlLoadingReturnValue = value; } public String getShouldOverrideUrlLoadingUrl() { assert getCallCount() > 0; return mShouldOverrideUrlLoadingUrl; } public boolean getShouldOverrideUrlLoadingReturnValue() { return mShouldOverrideUrlLoadingReturnValue; } public boolean isRedirect() { return mIsRedirect; } public boolean hasUserGesture() { return mHasUserGesture; } public boolean isMainFrame() { return mIsMainFrame; } public void notifyCalled( String url, boolean isRedirect, boolean hasUserGesture, boolean isMainFrame) { mShouldOverrideUrlLoadingUrl = url; mIsRedirect = isRedirect; mHasUserGesture = hasUserGesture; mIsMainFrame = isMainFrame; notifyCalled(); } } @Override public boolean shouldOverrideUrlLoading(AwWebResourceRequest request) { super.shouldOverrideUrlLoading(request); boolean returnValue = mShouldOverrideUrlLoadingHelper.getShouldOverrideUrlLoadingReturnValue(); mShouldOverrideUrlLoadingHelper.notifyCalled( request.url, request.isRedirect, request.hasUserGesture, request.isMainFrame); return returnValue; } /** * Callback helper for doUpdateVisitedHistory. */ public static class DoUpdateVisitedHistoryHelper extends CallbackHelper { String mUrl; boolean mIsReload; public String getUrl() { assert getCallCount() > 0; return mUrl; } public boolean getIsReload() { assert getCallCount() > 0; return mIsReload; } public void notifyCalled(String url, boolean isReload) { mUrl = url; mIsReload = isReload; notifyCalled(); } } @Override public void doUpdateVisitedHistory(String url, boolean isReload) { getDoUpdateVisitedHistoryHelper().notifyCalled(url, isReload); } /** * CallbackHelper for OnReceivedError2. */ public static class OnReceivedError2Helper extends CallbackHelper { private AwWebResourceRequest mRequest; private AwWebResourceError mError; public void notifyCalled(AwWebResourceRequest request, AwWebResourceError error) { mRequest = request; mError = error; notifyCalled(); } public AwWebResourceRequest getRequest() { assert getCallCount() > 0; return mRequest; } public AwWebResourceError getError() { assert getCallCount() > 0; return mError; } } /** * CallbackHelper for OnReceivedHttpError. */ public static class OnReceivedHttpErrorHelper extends CallbackHelper { private AwWebResourceRequest mRequest; private AwWebResourceResponse mResponse; public void notifyCalled(AwWebResourceRequest request, AwWebResourceResponse response) { mRequest = request; mResponse = response; notifyCalled(); } public AwWebResourceRequest getRequest() { assert getCallCount() > 0; return mRequest; } public AwWebResourceResponse getResponse() { assert getCallCount() > 0; return mResponse; } } @Override public void onReceivedHttpError(AwWebResourceRequest request, AwWebResourceResponse response) { super.onReceivedHttpError(request, response); mOnReceivedHttpErrorHelper.notifyCalled(request, response); } /** * CallbackHelper for onReceivedIcon. */ public static class FaviconHelper extends CallbackHelper { private Bitmap mIcon; public void notifyFavicon(Bitmap icon) { mIcon = icon; super.notifyCalled(); } public Bitmap getIcon() { assert getCallCount() > 0; return mIcon; } } @Override public void onReceivedIcon(Bitmap bitmap) { // We don't inform the API client about the URL of the icon. mFaviconHelper.notifyFavicon(bitmap); } /** * CallbackHelper for onReceivedTouchIconUrl. */ public static class TouchIconHelper extends CallbackHelper { private HashMap<String, Boolean> mTouchIcons = new HashMap<String, Boolean>(); public void notifyTouchIcon(String url, boolean precomposed) { mTouchIcons.put(url, precomposed); super.notifyCalled(); } public int getTouchIconsCount() { assert getCallCount() > 0; return mTouchIcons.size(); } public boolean hasTouchIcon(String url) { return mTouchIcons.get(url); } } @Override public void onReceivedTouchIconUrl(String url, boolean precomposed) { mTouchIconHelper.notifyTouchIcon(url, precomposed); } }
from dash import html, callback, Output, Input, dcc, register_page import pandas as pd import pathlib import os import plotly.express as px import plotly.graph_objs as go # Registering page register_page(__name__, path='/') # Incorporating data data_dir = pathlib.Path("data") data = {} dropdown_options = [] for file_name in os.listdir(data_dir): crypto_name = file_name.split("-")[0] dropdown_options.append( {"label": crypto_name, "value": crypto_name} ) data[crypto_name] = pd.read_csv(os.path.join(data_dir, file_name)) column_options = [] for column in data["BTC"].columns[1:]: column_options.append(column) # App layout layout = html.Div([ html.H3("[Time Series] Crypto Currency"), html.Div([ "Choose Crypto(s):", dcc.Dropdown(options=dropdown_options, value=["BTC"], multi=True, id="crypto-dropdown") ]), html.Div([ "Choose column:", dcc.Checklist(options=column_options, value=["adjclose"], id="column-checklist") ]), dcc.Graph(figure=px.line(data["BTC"], x="timestamp", y="adjclose"), id="crypto-graph") ]) # Controls and callbacks @callback( Output("crypto-graph", "figure"), Input("crypto-dropdown", "value"), Input("column-checklist", "value") ) def update_graph(crypto_chosen, columns_chosen): fig = px.line() for crypto in crypto_chosen: for column in columns_chosen: fig.add_trace(go.Scatter( x=data[crypto]["timestamp"], y=data[crypto][column], name=f'{crypto} - {column}' )) return fig
; Name: Vansh Nagpal ; Email: vnagp002@ucr.edu ; ; Lab: lab 5, ex 3 ; Lab section: 022 ; TA: Karan Bhogal, Cody Kurpanek ; .orig x3000 ; Initialize the stack. Don't worry about what that means for now. ld r6, top_stack_addr ; DO NOT MODIFY, AND DON'T USE R6, OTHER THAN FOR BACKUP/RESTORE lea r1, array ld r4, sub_get_string_3200 jsrr r4 ld r4, sub_is_palindrome_3400 jsrr r4 print lea r0, output_str puts do_while_print ldr r0, r1, #0 out add r1, r1, #1 add r5, r5, #-1 brp do_while_print end_do_while_print add r3, r4, #0 add r3, r3, #-1 brn not_palindrome_print is_palindrome_print lea r0, output_str_is_p puts br end_print not_palindrome_print lea r0, output_str_is_not_p puts end_print ; your code goes here halt ; your local data goes here top_stack_addr .fill xFE00 ; DO NOT MODIFY THIS LINE OF CODE array .blkw #100 sub_get_string_3200 .fill x3200 sub_is_palindrome_3400 .fill x3400 output_str .stringz "The string " output_str_is_p .stringz " IS a palindrome\n" output_str_is_not_p .stringz " IS NOT a palindrome\n" .end ; your subroutines go below here ;------------------------------------------------------------------------ ; Subroutine: SUB_GET_STRING_3200 ; Parameter (R1): The starting address of the character array ; Postcondition: The subroutine has prompted the user to input a string, ; terminated by the [ENTER] key (the "sentinel"), and has stored ; the received characters in an array of characters starting at (R1). ; the array is NULL-terminated; the sentinel character is NOT stored. ; Return Value (R5): The number of non-sentinel chars read from the user. ; R1 contains the starting address of the array unchanged. ;------------------------------------------------------------------------- .orig x3200 ; backs up registers add r6, r6, #-1 str r1, r6, #0 add r6, r6, #-1 str r7, r6, #0 ld r3, neg_sent and r5, r5, #0 do_while_input getc out str r0, r1, #0 check_sentinel ldr r2, r1, #0 add r2, r2, r3 brz end_do_while_input add r5, r5, #1 add r1, r1, #1 brnp do_while_input end_do_while_input ; converts newline character to null and r0, r0, #0 str r0, r1, #0 and r2, r2, #0 and r3, r3, #0 ; restores registers ldr r7, r6, #0 add r6, r6, #1 ldr r1, r6, #0 add r6, r6, #1 ret neg_sent .fill #-10 .end ;------------------------------------------------------------------------- ; Subroutine: SUB_IS_PALINDROME_3400 ; Parameter (R1): The starting address of a null-terminated string ; Parameter (R5): The number of characters in the array. ; Postcondition: The subroutine has determined whether the string at (R1) ; is a palindrome or not, and returned a flag to that effect. ; Return Value: R4 {1 if the string is a palindrome, 0 otherwise} ;------------------------------------------------------------------------- .orig x3400 ; backs up registers add r6, r6, #-1 str r7, r6, #0 add r6, r6, #-1 str r1, r6, #0 add r6, r6, #-1 str r5, r6, #0 ld r4, sub_to_upper_3600 jsrr r4 add r2, r1, r5 add r2, r2, #-1 ; r1 has first memory adr ; r2 has last memory adr ; r3 has first char ; r4 has last char do_while_compare add r4, r2, #0 ; r4 <- r2 not r4, r4 add r4, r4, #1 ; 2s complement of r4 add r4, r1, r4 ; r4 <- r1 - r4 brz is_a_palindrome ; if 0 middle reached, jump to palindrome condition ; if middle not reached, continue comparing ldr r3, r1, #0 ; r3 <- r1 ldr r4, r2, #0 ; r4 <- r2 not r4, r4 add r4, r4, #1 add r4, r3, r4 ; r4 <- r3 - r4 brnp not_a_palindrome ; if not 0, characters dont match, jump to not palindrome condition add r1, r1, #1 ; increment r1 to next char mem adr add r2, r2, #-1 ; decrement r2 to previous char mem adr br do_while_compare is_a_palindrome ; r4 = 1 if palindrome add r4, r4, #1 br end_do_while_compare not_a_palindrome ; r4 = 0 if not palindrome and r4, r4, #0 end_do_while_compare ; restores registers ; ldr r3, r6, #0 ; add r6, r6, #1 ldr r5, r6, #0 add r6, r6, #1 ldr r1, r6, #0 add r6, r6, #1 ldr r7, r6, #0 add r6, r6, #1 ret sub_to_upper_3600 .fill x3600 .end ;------------------------------------------------------------------------- ; Subroutine: SUB_TO_UPPER_3600 ; Parameter (R1): Starting address of a null-terminated string ; Postcondition: The subroutine has converted the string to upper-case ; in-place i.e. the upper-case string has replaced the original string ; No return value, no output, but R1 still contains the array address, unchanged ;------------------------------------------------------------------------- .orig x3600 ; backs up registers add r6, r6, #-1 str r7, r6, #0 add r6, r6, #-1 str r1, r6, #0 add r6, r6, #-1 str r5, r6, #0 ld r2, lower_to_upper_mask ; load mask xDF = 1101 1111 do_while_convert_case ldr r0, r1, #0 add r0, r0, #0 brz end_do_while_convert_case ; once null is reached, terminate and r0, r0, r2 ; and with the bit mask str r0, r1, #0 add r1, r1, #1 br do_while_convert_case end_do_while_convert_case ; restores registers ldr r5, r6, #0 add r6, r6, #1 ldr r1, r6, #0 add r6, r6, #1 ldr r7, r6, #0 add r6, r6, #1 ret lower_to_upper_mask .fill xDF .end
import abc from abc import ABC import numpy as np import scipy import torch from torch import nn from data_utils.data_corruption.corruption_type import CorruptionType from data_utils.data_corruption.covariates_dimension_reducer import WeightedZReducer from data_utils.data_corruption.data_corruption_masker import DataCorruptionIndicatorFactory, DataCorruptionMasker from data_utils.data_type import DataType from data_utils.datasets.synthetic_dataset_generator import SyntheticDataGenerator from utils import set_seeds, get_seed class CausalInferenceCorruptionMasker(DataCorruptionMasker): def __init__(self, propensity_score_function): super().__init__() self.propensity_score_function = propensity_score_function def get_corruption_probabilities(self, unscaled_x: torch.Tensor, unscaled_z: torch.Tensor): return 1-self.propensity_score_function(unscaled_x, unscaled_z) class CausalInferenceDataGenerator(SyntheticDataGenerator): """ 1: Was initially defined in: Estimation and inference of heterogeneous treatment effects using random forests. 2: A variant of the example in https://arxiv.org/pdf/2006.06138.pdf (Conformal Inference # of Counterfactuals and Individual Treatment Effects) """ def __init__(self, x_dim: int, rho: float = 0.9): super().__init__() self.x_dim = x_dim self.rho = rho def generate_data(self, data_size: int, device='cpu', seed=0): curr_seed = get_seed() set_seeds(seed) x = torch.randn(data_size, self.x_dim + 1) fac = torch.randn(data_size) x = x * np.sqrt(1 - self.rho) + fac[:, None] * np.sqrt(self.rho) x = torch.Tensor(scipy.stats.norm.cdf(x.numpy())) z = x[:, -1] x = x[:, :-1] y = self.get_y_given_x_z(x, z, seed=seed) data_masker = CausalInferenceCorruptionMasker(self.compute_propensity_score) deleted = data_masker.get_corruption_mask(x, z) set_seeds(curr_seed) x, y, z, deleted = x.to(device), y.to(device), z.to(device), deleted.to(device) assert x.shape[1] == self.x_dim return x, y, z, data_masker, deleted def compute_propensity_score(self, x, z): device = z.device return torch.Tensor(1 + scipy.stats.beta(2, 4).cdf(z.detach().cpu().numpy())).to(device).squeeze() / 4 def generate_with_repeats(self, generator, *inputs, repeats: int = None, seed=0): curr_seed = get_seed() if repeats is None: repeats = 1 squeeze = True else: squeeze = False repeated_inputs = [] device = inputs[0].device for input in inputs: repeated_inputs += [input.unsqueeze(0).repeat(repeats, 1, 1).flatten(0, 1).cpu()] unflatten = nn.Unflatten(0, (repeats, inputs[0].shape[0])) set_seeds(seed) result = generator(*repeated_inputs, seed=seed) set_seeds(curr_seed) result = unflatten(result).to(device) if squeeze: result = result.squeeze(0) return result def generate_z_given_x(self, x: torch.Tensor, repeats: int = None, seed=0) -> torch.Tensor: raise NotImplementedError() def get_y_given_x_z(self, x: torch.Tensor, z: torch.Tensor, repeats: int = None, seed=0) -> torch.Tensor: return self.generate_with_repeats(self.get_y_given_x_z_core, x, z, repeats=repeats, seed=seed) def get_y_given_x_z_core(self, x: torch.Tensor, z: torch.Tensor, **kwargs): std = -torch.log(x[:, 1] + 1e-9) q = torch.quantile(z, q=0.2) std = std * 500 * (z < q).squeeze().float() + std * (z >= q).squeeze().float() tau = 2 / (1 + torch.exp(-12 * (x[:, 1] - 0.5))) * 2 / (1 + torch.exp(-12 * (x[:, 2] - 0.5))) y = tau + std * torch.randn(x.shape[0]) return y def get_y_given_x(self, x: torch.Tensor, repeats: int = None, seed=0): return self.generate_with_repeats(self.get_y_given_x_core, x, repeats=repeats, seed=seed) def get_y_given_x_core(self, x: torch.Tensor, **kwargs): raise NotImplementedError() """ deleted.float().mean().item() import matplotlib.pyplot as plt plt.scatter(reduced_z.squeeze().cpu(), y.squeeze().cpu()) plt.xlabel("z") plt.ylabel("y") plt.show() y[deleted].var() y[~deleted].var() plt.scatter(z[:, 0].squeeze().cpu(), y.squeeze().cpu()) plt.xlabel("z0") plt.ylabel("y") plt.show() """
package config import ( "context" "github.com/getCompassUtils/go_base_frame/api/system/log" "go_company_cache/api/includes/type/db/company_data" ) // GetList получаем информацию о нескольких записях конфига из кэша func (store *Storage) GetList(ctx context.Context, companyDataConn *company_data.DbConn, keyList []string) ([]*company_data.KeyRow, []string) { var keyListStruct []*company_data.KeyRow // делим записи конфига на тех которых надо получить из базы и получили из кэша needFetchKeyList, keyListStruct := store.splitKeyList(keyList) subChannelList := store.doSubKeyListOnChanList(ctx, needFetchKeyList, companyDataConn) notFoundKeyList := make([]string, 0) for k, v := range subChannelList { err := waitUntilKeyAddedToCache(v, k) if err != nil { notFoundKeyList = append(notFoundKeyList, k) continue } keyInfo, isExist := store.mainStorage.getKeyItemFromCache(k) if !isExist { log.Errorf("Не получили ключ %d из кэша после ожидания канала", k) notFoundKeyList = append(notFoundKeyList, k) continue } keyListStruct = append(keyListStruct, keyInfo.keyRow) } return keyListStruct, notFoundKeyList } // GetOne получаем информацию об одном значении конфига из кеша func (store *Storage) GetOne(ctx context.Context, companyDataConn *company_data.DbConn, key string) (*company_data.KeyRow, bool) { // пытаемся получить запись из кэша keyItem, exist := store.mainStorage.getKeyItemFromCache(key) // если нашли запись в кэше, просто отдаем if exist { return keyItem.keyRow, exist } // подписываем значение конфига на канал и ждем, пока получим его с базы subChannel := store.doSubKeyOnChan(ctx, key, companyDataConn) _ = waitUntilKeyAddedToCache(subChannel, key) keyItem, exist = store.mainStorage.getKeyItemFromCache(key) if !exist { log.Errorf("Не получили значение конфига %s из кэша после ожидания канала", key) return nil, false } return keyItem.keyRow, exist } // Делим записи конфига на тех которых надо получить из базы и получили из кэша func (store *Storage) splitKeyList(keyList []string) ([]string, []*company_data.KeyRow) { needFetchKeyList := make([]string, 0) var keyListStruct []*company_data.KeyRow for _, key := range keyList { keyItem, exist := store.mainStorage.getKeyItemFromCache(key) if !exist { needFetchKeyList = append(needFetchKeyList, key) continue } keyListStruct = append(keyListStruct, keyItem.keyRow) } return needFetchKeyList, keyListStruct } // DeleteKeyFromCache удаляем из кэша по key func (store *Storage) DeleteKeyFromCache(key string) { store.mainStorage.deleteFromStore(key) } // ClearCache очистить кэш конфига func (store *Storage) ClearCache() { store.mainStorage.clear() }
import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: 'input[max-length],textarea[max-length]', host: { '(input)': '$event', }, }) export class MaxLengthDirective { lastValue: string; @Input('max-length') maxLenght: number = null; constructor(public ref: ElementRef) {} @HostListener('input', ['$event']) onInput($event: InputEvent) { const target = $event.target as HTMLInputElement; const { value, type } = target; if (!this.maxLenght) { return; } if (!value) { return; } if (type == 'text') { this.validateString($event, value); return; } if (type == 'number') { this.validateNumbers(target, value, $event); return; } } validateString($event: InputEvent, value: string) { if (value.length > this.maxLenght) { ($event.target as HTMLInputElement).value = value.slice( 0, this.maxLenght ); } } validateNumbers(target: HTMLInputElement, value: string, $event: InputEvent) { ($event.target as HTMLInputElement).setAttribute( 'max', `${this.maxLenght}` ); const intPart = `${value}`.split('.')[0]; if (!intPart.length) { return; } if (intPart.length > this.maxLenght) { const _intPart = intPart.slice(0, this.maxLenght); const val: string = `${Number(_intPart)}${value.slice(intPart.length)}`; ($event.target as HTMLInputElement).value = val; } if (value.length > 1 && value.startsWith('0') && !value.includes('.')) { ($event.target as HTMLInputElement).value = value.slice(1); } } }
package com.yh.devicehelper.activities.main_activity.recycles_views import android.graphics.Rect import android.view.DragEvent import android.view.View import android.view.View.OnDragListener import android.widget.Toast import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.yh.devicehelper.R import com.yh.devicehelper.activities.main_activity.recycles_views.apps.AppsRecyclerViewAdapter import com.yh.devicehelper.activities.main_activity.recycles_views.autostart_apps.AutostartAppsRecyclerViewAdapter import com.yh.devicehelper.databinding.ActivityMainBinding import com.yh.devicehelper.utlis.app_info.AppInfo import com.yh.devicehelper.utlis.apps_storage.AppsStorage import kotlin.math.abs class RecyclersViewsManager(private val binding: ActivityMainBinding) { private val MIN_Y_FOR_SCROLL_COEFICIENT = 0.1 private val SCROLL_COEFICIENT = 0.03 private val minYScroll = MIN_Y_FOR_SCROLL_COEFICIENT * binding.root.context.resources.displayMetrics.heightPixels // 100 для 1280x720 ; 165 для 2000x1200 private val scroll = (SCROLL_COEFICIENT * binding.root.context.resources.displayMetrics.heightPixels).toInt() // 250 для 1280x720 ; 415 для 2000x1200 private lateinit var appsAdapter: AppsRecyclerViewAdapter private lateinit var autostartAppsAdapter: AutostartAppsRecyclerViewAdapter private var fromRecyclerView: RecyclerView? = null private var fromPosition = -1 private val appsOnDragListener = OnDragListener { v, event -> when (event.action) { DragEvent.ACTION_DRAG_STARTED -> { val draggableView = event.localState as View if (draggableView.parent == binding.appsRV) { fromPosition = binding.appsRV.getChildAdapterPosition(draggableView) fromRecyclerView = binding.appsRV } true } DragEvent.ACTION_DRAG_ENTERED -> { v.invalidate() true } DragEvent.ACTION_DRAG_EXITED -> { v.invalidate() true } DragEvent.ACTION_DRAG_LOCATION -> { val rvLocation = Rect() binding.appsRV.getLocalVisibleRect(rvLocation) if (event.y < minYScroll) { startScroll(-scroll) } else if (abs(event.y - rvLocation.bottom) < minYScroll) { startScroll(scroll) } else { stopScroll() } true } DragEvent.ACTION_DROP -> { stopScroll() val targetView = binding.appsRV.findChildViewUnder(event.x, event.y) if (fromRecyclerView == binding.appsRV) { if (targetView != null) { val targetViewPosition = binding.appsRV.getChildAdapterPosition(targetView) AppsStorage.moveApp(fromPosition, targetViewPosition) } else { AppsStorage.moveApp(fromPosition, binding.appsRV.adapter!!.itemCount - 1) } } else if (fromRecyclerView == binding.autostartAppsRV) { if (targetView != null) { val targetViewPosition = binding.appsRV.getChildAdapterPosition(targetView) val app = AppsStorage.autostartAppsInfos[fromPosition] AppsStorage.addApp(app, targetViewPosition) AppsStorage.removeAutostartApp(app.packageName) } else { val app = AppsStorage.autostartAppsInfos[fromPosition] AppsStorage.addApp(app) AppsStorage.removeAutostartApp(app.packageName) } } true } else -> { true } } } private val autostartAppsOnDragListener = OnDragListener { v, event -> when (event.action) { DragEvent.ACTION_DRAG_STARTED -> { val draggableView = event.localState as View if (draggableView.parent == binding.autostartAppsRV) { fromPosition = binding.autostartAppsRV.getChildAdapterPosition(draggableView) fromRecyclerView = binding.autostartAppsRV } true } DragEvent.ACTION_DRAG_ENTERED -> { v.invalidate() true } DragEvent.ACTION_DRAG_EXITED -> { v.invalidate() true } DragEvent.ACTION_DROP -> { val targetView = binding.autostartAppsRV.findChildViewUnder(event.x, event.y) if (fromRecyclerView == binding.autostartAppsRV) { if (targetView != null && AppsStorage.autostartAppsInfos.size == 2) { val targetViewPosition = binding.appsRV.getChildAdapterPosition(targetView) AppsStorage.moveAutostartApp(fromPosition, targetViewPosition) } } else if (fromRecyclerView == binding.appsRV) { if (AppsStorage.autostartAppsInfos.size < 2) { var flag = true if (targetView != null) { val index = binding.autostartAppsRV.getChildAdapterPosition(targetView) val item = autostartAppsAdapter.dataSet[index] if (item != null) { val targetViewPosition = binding.autostartAppsRV.getChildAdapterPosition(targetView) val app = AppsStorage.appsInfos[fromPosition] AppsStorage.addAutostartApp(app, targetViewPosition) flag = false } } if (flag) { val app = AppsStorage.appsInfos[fromPosition] AppsStorage.addAutostartApp(app) } } else { Toast.makeText(binding.root.context, binding.root.context.getString(R.string.max_autostart_apps), Toast.LENGTH_LONG).show() } } true } else -> { true } } } private val rootOnDragListener = OnDragListener { view, dragEvent -> when(dragEvent.action) { DragEvent.ACTION_DROP -> { stopScroll() true } else -> { true } } } private var state = false private fun startScroll(scroll: Int) { if (!state) { state = true val handler = android.os.Handler() Thread { while (state) { handler.post { binding.appsRV.smoothScrollBy(0, scroll, null, 10) } Thread.sleep(10) } }.start() } } private fun stopScroll() { state = false } init { binding.appsRV.layoutManager = GridLayoutManager(binding.root.context, 4) appsAdapter = AppsRecyclerViewAdapter(AppsStorage.appsInfos) binding.appsRV.adapter = appsAdapter binding.appsRV.setOnDragListener(appsOnDragListener) binding.autostartAppsRV.layoutManager = GridLayoutManager(binding.root.context, 1) val autostartAppsDataSet = ArrayList<AppInfo?>() autostartAppsDataSet.addAll(AppsStorage.autostartAppsInfos) autostartAppsAdapter = AutostartAppsRecyclerViewAdapter(autostartAppsDataSet) binding.autostartAppsRV.adapter = autostartAppsAdapter binding.autostartAppsRV.setOnDragListener(autostartAppsOnDragListener) binding.root.setOnDragListener(rootOnDragListener) } }
import java.util.Random; class lab9{ // Student: Oscar Ricaud, Professor: Julio Urenda, TA: Saif // Lab9 Info: // In the main method of lab9.java it creates the values for n // for example it does a for loop of, 100,200,300,400 // While it does this it calls 2 methods the, HeapSortMagic // and the BinarySearchTreeMagic // Both of these methods take in the same value which is n. (100,200,300,400) // public static void main(String[] args) { // FIX TIMER long startTimer = System.nanoTime(); int computeTime= 0; int [] values = new int[4]; for(int i = 0 ; i < 4; i ++){ computeTime = 100 + computeTime; values[i] = computeTime; int timeValue = values[i]; System.out.println("timeValue: " + timeValue); for(int j = 0; j < timeValue; j++){ BinarySearchTreeMagic(timeValue); HeapSortMagic(timeValue); } long endTimer = System.nanoTime(); // FIX ME // System.out.println("TotalTime: " + (endTimer-startTimer)); } } private static void HeapSortMagic(int timeValue) { long startTime = System.currentTimeMillis(); Random rand = new Random(); int [] array = new int [timeValue]; System.out.println("******************************"); System.out.println("Size of array. " + array.length); System.out.println("******************************"); for(int i = 0; i < array.length; i ++){ array[i] = rand.nextInt(timeValue) + 0; // System.out.println("array[i]" + array[i]); HeapSort.sort(array); } System.out.println("Sorted using HeapSortMagic: " ); System.out.println(""); // Sorts this for (int j = 0; j< timeValue; j++){ System.out.print(array[j]+" "); System.out.print(""); // FIX TIMER //long endTime = System.currentTimeMillis(); //long total = endTime - startTime; //System.out.println("total time:" + (total)); } } private static void BinarySearchTreeMagic(int timeValue) { long startTime = System.currentTimeMillis(); BinarySearchTree bst = new BinarySearchTree( ); Random rand = new Random(); int [] array = new int [timeValue]; System.out.println("Size of array. " + array.length); for(int i = 0; i < array.length; i ++){ array[i] = rand.nextInt(timeValue) + 0; bst.insert(array[i]); } // System.out.println(Arrays.toString(array)); System.out.println(""); System.out.println("Sorted using the magic Binary Search Tree: "); System.out.println(""); bst.inorderTraversal( ); long endTime = System.currentTimeMillis(); long total = endTime - startTime; System.out.println("Total time:" + total); } }
/***************************************************************************** * * This file is part of NCrystal (see https://mctools.github.io/ncrystal/) * * Copyright 2015-2022 NCrystal developers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * Component: NCrystal_sample * * %I * Written by: NCrystal developers * Version: 1.0.0 * Origin: NCrystal Developers (European Spallation Source ERIC and DTU Nutech) * * McStas sample component for the NCrystal library for thermal neutron transport * (<a href="https://github.com/mctools/ncrystal">www</a>). * * %D * McStas sample component for the NCrystal scattering library. * Find more information at <a href="https://github.com/mctools/ncrystal/wiki">the NCrystal wiki</a>. * In particular, browse the available datafiles at <a href="https://github.com/mctools/ncrystal/wiki/Data-library">Data-library</a> * and read about the format of the configuration string expected in * the "cfg" parameter at <a href="https://github.com/mctools/ncrystal/wiki/Using-NCrystal">Using-NCrystal</a>. * * <p/>NCrystal is available under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0 license</a>. * Depending on the configuration choices, optional NCrystal * modules under different licenses might be enabled, * see <a href="https://github.com/mctools/ncrystal/blob/master/NOTICE">here</a> for more details. * * Note also that for more complicated geometries, it might be desirable to use * NCrystal via the McStas Union components instead. * * <p/>This NCrystal_sample component used to be shipped with NCrystal itself, * but starting with McStas 3.2 it is shipped along with McStas itself * (accordingly the components version number is reset to 1.0.0 to avoid * confusion). As engine it will use whichever NCrystal installation is * available and associated with the "ncrystal-config" command. * * %P * Input parameters: * cfg: [str] NCrystal material configuration string (details <a href="https://github.com/mctools/ncrystal/wiki/Using-NCrystal">on this page</a>). * absorptionmode: [0|1|2] 0 : disable absorption. 1 : enable absorption via intensity reduction. 2 : enable absorption by terminating the tracking. * multscat: [0|1] 0 : disable multiple scattering. 1 : enable multiple scattering * xwidth: [m] x-dimension (width) of sample, if box shape is desired * yheight: [m] y-dimension (height) of sample, if box or cylinder shape is desired * zdepth: [m] z-dimension (depth) of sample, if box shape is desired * radius: [m] radius of sample, if sphere or cylinder shape is desired * * %L * The NCrystal wiki at <a href="https://github.com/mctools/ncrystal/wiki">https://github.com/mctools/ncrystal/wiki</a>. * * %E *******************************************************************************/ DEFINE COMPONENT NCrystal_sample SETTING PARAMETERS (string cfg="void", absorptionmode=1, multscat=1, xwidth=0, yheight=0, zdepth=0, radius=0 ) OUTPUT PARAMETERS (params, geoparams)/*not really intended for output, but here for multi-instance support*/ DEPENDENCY "-Wl,-rpath,CMD(ncrystal-config --show libdir) -LCMD(ncrystal-config --show libdir) -lNCrystal -ICMD(ncrystal-config --show includedir)" NOACC /* Notice: you must remove this line if using the legacy McStas 2.x branch. */ SHARE %{ /* common includes, defines, functions, etc. shared by all instances of this component */ #ifndef WIN32 #include "NCrystal/ncrystal.h" #else #include "NCrystal\\ncrystal.h" #endif #include "stdio.h" #include "stdlib.h" #ifndef NCMCERR2 /* consistent/convenient error reporting */ # define NCMCERR2(compname,msg) do { fprintf(stderr, "\nNCrystal: %s: ERROR: %s\n\n", compname, msg); exit(1); } while (0) #endif static int ncsample_reported_version = 0; //Keep all instance-specific parameters on a few structs: typedef struct { double density_factor; double inv_density_factor; ncrystal_scatter_t scat; ncrystal_process_t proc_scat, proc_abs; int proc_scat_isoriented; int absmode; } ncrystalsample_t; typedef enum {NC_BOX, NC_SPHERE, NC_CYLINDER} ncrystal_shapetype; typedef struct { ncrystal_shapetype shape; double dx, dy, dz, rradius;//naming rradius instead of radius to avoid mcstas macro issues (due to clash with component parameter name). } ncrystalsamplegeom_t; /* Factor out geometry related code in the following functions (+MCDISPLAY section below): */ void ncrystalsample_initgeom(ncrystalsamplegeom_t* geom, const char * name_comp, double xxwidth, double yyheight, double zzdepth, double rradius) { int isbox = ( xxwidth>0 && yyheight>0 && zzdepth>0 ); int iscyl = ( yyheight>0 && rradius>0 ); int issphere = ( !iscyl && rradius>0 ); int nshapes = (isbox?1:0)+(iscyl?1:0)+(issphere?1:0); if (nshapes==0) NCMCERR2(name_comp,"must specify more parameters to define shape"); if ( nshapes > 1 || ( iscyl && ( xxwidth>0 || zzdepth>0 ) ) || ( issphere && ( xxwidth>0 || yyheight > 0 || zzdepth>0 ) ) ) NCMCERR2(name_comp,"conflicting shape parameters specified (pick either parameters for box, cylinder or sphere, not more than one)"); if (isbox) { geom->shape = NC_BOX; geom->dx = xxwidth; geom->dy = yyheight; geom->dz = zzdepth; geom->rradius = 0.0; } else if (iscyl) { geom->shape = NC_CYLINDER; geom->dx = 0.0; geom->dy = yyheight; geom->dz = 0.0; geom->rradius = rradius; } else { if (!issphere) NCMCERR2(name_comp,"logic error in shape selection"); geom->shape = NC_SPHERE; geom->dx = 0.0; geom->dy = 0.0; geom->dz = 0.0; geom->rradius = rradius; } } int ncrystalsample_surfintersect(ncrystalsamplegeom_t* geom, double *t0, double *t1, double x, double y, double z, double vx, double vy, double vz) { switch (geom->shape) { case NC_CYLINDER: return cylinder_intersect(t0,t1,x,y,z,vx,vy,vz,geom->rradius, geom->dy); case NC_BOX: return box_intersect(t0, t1, x, y, z, vx, vy, vz,geom->dx, geom->dy, geom->dz); case NC_SPHERE: return sphere_intersect(t0,t1,x,y,z,vx,vy,vz,geom->rradius); }; } #ifndef NCMCERR /* more convenient form (only works in TRACE section, not in SHARE functions) */ # define NCMCERR(msg) NCMCERR2(NAME_CURRENT_COMP,msg) #endif %} DECLARE %{ ncrystalsample_t params; ncrystalsamplegeom_t geoparams; double ncrystal_convfact_vsq2ekin; double ncrystal_convfact_ekin2vsq; %} INITIALIZE %{ //Print NCrystal version + sanity check setup. if ( NCRYSTAL_VERSION != ncrystal_version() ) { NCMCERR("Inconsistency detected between included ncrystal.h and linked NCrystal library!"); } if (ncsample_reported_version != ncrystal_version()) { if (ncsample_reported_version) { NCMCERR("Inconsistent NCrystal library versions detected - this should normally not be possible!"); } ncsample_reported_version = ncrystal_version(); printf( "NCrystal: McStas sample component(s) are using version %s of the NCrystal library.\n",ncrystal_version_str()); } //The following conversion factors might look slightly odd. They reflect the //fact that the various conversion factors used in McStas and NCrystal are not //completely consistent among each other (TODO: Follow up on this with McStas //developers!). Also McStas's V2K*K2V is not exactly 1. All in all, this can //give issues when a McStas user is trying to set up a narrow beam very //precisely in an instrument file, attempting to carefully hit a certain //narrow Bragg reflection in this NCrystal component. We can not completely //work around all issues here, but for now, we assume that the user is //carefully setting up things by specifying the wavelength to some source //component. That wavelength is then converted to the McStas state pars //(vx,vy,vz) via K2V. We thus here first use 1/K2V (and *not* V2K) to convert //back to a wavelength, and then we use NCrystal's conversion constants to //convert the resulting wavelength to kinetic energy needed for NCrystal's //interfaces. // 0.0253302959105844428609698658024319097260896937 is 1/(4*pi^2) ncrystal_convfact_vsq2ekin = ncrystal_wl2ekin(1.0) * 0.0253302959105844428609698658024319097260896937 / ( K2V*K2V ); ncrystal_convfact_ekin2vsq = 1.0 / ncrystal_convfact_vsq2ekin; //for our sanity, zero-initialise all instance-specific data: memset(&params,0,sizeof(params)); memset(&params,0,sizeof(geoparams)); ncrystalsample_initgeom(&geoparams, NAME_CURRENT_COMP, xwidth, yheight, zdepth, radius); if (!(absorptionmode==0||absorptionmode==1||absorptionmode==2)) NCMCERR("Invalid value of absorptionmode"); params.absmode = absorptionmode; #ifndef rand01 /* Tell NCrystal to use the rand01 function provided by McStas: */ ncrystal_setrandgen(rand01); #else /* rand01 is actually a macro not an actual C-function (most likely defined as */ /* _rand01(_particle->randstate) for OPENACC purposes), which we can not */ /* register with NCrystal. As a workaround we tell NCrystal to use its own RNG */ /* algorithm, with merely the seed provided by McStas: */ ncrystal_setbuiltinrandgen_withseed( mcseed ); #endif /* access material info to get number density (natoms/volume): */ ncrystal_info_t info = ncrystal_create_info(cfg); double numberdensity = ncrystal_info_getnumberdensity(info); ncrystal_unref(&info); //numberdensity is the atomic number density in units of Aa^-3=1e30m^3, and //given that we have cross-sections in barn (1e-28m^2) and want to generate //distances in meters with -log(R)/(numberdensity*xsect), we get the unit //conversion factor of 0.01: params.density_factor = - 0.01 / numberdensity; params.inv_density_factor = -100.0 * numberdensity; //Setup scattering: params.scat = ncrystal_create_scatter(cfg); params.proc_scat = ncrystal_cast_scat2proc(params.scat); params.proc_scat_isoriented = ! ncrystal_isnonoriented(params.proc_scat);; //Setup absorption: if (params.absmode) { params.proc_abs = ncrystal_cast_abs2proc(ncrystal_create_absorption(cfg)); if (!ncrystal_isnonoriented(params.proc_abs)) NCMCERR("Encountered oriented NCAbsorption process which is not currently supported by this component."); } %} TRACE %{ /* Handle arbitrary incoming neutron with state vector (x,y,z,vx,vy,vz,t,sx,sy,sz,p) */ do { /* neutron is outside our surface at this point. First check if it intersects it... */ double t0,t1; if (!ncrystalsample_surfintersect(&geoparams,&t0,&t1,x,y,z,vx,vy,vz)) break;//no intersections with our sample geometry, so nothing more to do. /* Propagate the neutron to our surface (t0<=0 means we started inside!) */ if (t0>0) PROP_DT(t0); /* let the neutron fly in a straight line for t0 */ double dir[3], dirout[3]; double v2 = vx*vx+vy*vy+vz*vz; double absv = sqrt(v2); double inv_absv = 1.0/absv; dir[0] = vx*inv_absv; dir[1] = vy*inv_absv; dir[2] = vz*inv_absv; double ekin = ncrystal_convfact_vsq2ekin * v2; double xsect_scat = 0.0; double xsect_abs = 0.0; ncrystal_crosssection(params.proc_scat,ekin,(const double(*)[3])&dir,&xsect_scat); if (params.absmode) ncrystal_crosssection_nonoriented(params.proc_abs, ekin,&xsect_abs); while(1) { /* Make the calculations and pick the final state before exiting the sample */ double xsect_step = xsect_scat; if (params.absmode==2) xsect_step += xsect_abs; double distance = xsect_step ? log( rand01() ) * params.density_factor / xsect_step : DBL_MAX; /* in m */ double timestep = distance * inv_absv; /* Test when the neutron would reach the outer surface in absence of interactions: */ if (!ncrystalsample_surfintersect(&geoparams,&t0,&t1,x,y,z,vx,vy,vz)) NCMCERR("Can not propagate to surface from inside volume!"); if(timestep>t1) { /* neutron reaches surface, move forward to surface and apply intensity reduction if absmode=1 */ if (params.absmode==1) p *= exp( absv * t1 * xsect_abs * params.inv_density_factor ); PROP_DT(t1); break;//end stepping inside volume } /*move neutron forward*/ PROP_DT(timestep); /* perform reaction */ if (params.absmode==2 && xsect_abs > rand01()*xsect_step ) { /* reaction was full-blooded absorption */ ABSORB;/* kill track (uses goto to jump out of current loop context)*/ } else if (params.absmode==1) { /* reaction was scatter and we model absorption by intensity-reduction */ p *= exp( distance * xsect_abs * params.inv_density_factor ); } else { /* reaction was scatter and we do not perform any intensity-reduction */ } /* scattering */ double ekin_final; ncrystal_samplescatter( params.scat, ekin, (const double(*)[3])&dir, &ekin_final, &dirout ); double delta_ekin = ekin_final - ekin; if (delta_ekin) { ekin = ekin_final; if (ekin<=0) { //not expected to happen much, but an interaction could in principle bring the neutron to rest. ABSORB; } v2 = ncrystal_convfact_ekin2vsq * ekin; absv = sqrt(v2); inv_absv = 1.0/absv; } vx=dirout[0]*absv; vy=dirout[1]*absv; vz=dirout[2]*absv; dir[0]=dirout[0]; dir[1]=dirout[1]; dir[2]=dirout[2]; SCATTER;/* update mcstas scatter counter and potentially enable trajectory visualisation */ if (multscat) { //Must update x-sects if energy changed or processes are oriented: if (delta_ekin&&params.absmode) ncrystal_crosssection_nonoriented(params.proc_abs, ekin,&xsect_abs); if (delta_ekin||params.proc_scat_isoriented) ncrystal_crosssection(params.proc_scat,ekin,(const double(*)[3])&dir,&xsect_scat); } else { //Multiple scattering disabled, so we just need to propagate the neutron //out of the sample and (if absmode==1) apply one more intensity //reduction factor. We handle this by putting cross-sections to 0 here, //which will result in an infinife step length of the next step. xsect_scat = 0.0; if (params.absmode!=1) xsect_abs = 0.0; } }/*exited at a surface*/ /* Exited the surface. We let the while condition below always be false for * * now, since we only support convex bodies, so there is no need to check if * * we might be able to enter our shape again: */ } while (0); %} FINALLY %{ ncrystal_unref(&params.scat); ncrystal_invalidate(&params.proc_scat);//a cast of params.scat, so just invalidate handle don't unref if (params.absmode) ncrystal_unref(&params.proc_abs); %} MCDISPLAY %{ //NB: Future McStas (2.5?) is slated to introduce mcdis_cylinder and //mcdis_sphere functions, which we at that point should likely use. switch (geoparams.shape) { case NC_CYLINDER: mcdis_circle("xz", 0, geoparams.dy/2.0, 0, geoparams.rradius); mcdis_circle("xz", 0, -geoparams.dy/2.0, 0, geoparams.rradius); mcdis_line(-geoparams.rradius, -geoparams.dy/2.0, 0, -geoparams.rradius, +geoparams.dy/2.0, 0); mcdis_line(+geoparams.rradius, -geoparams.dy/2.0, 0, +geoparams.rradius, +geoparams.dy/2.0, 0); mcdis_line(0, -geoparams.dy/2.0, -geoparams.rradius, 0, +geoparams.dy/2.0, -geoparams.rradius); mcdis_line(0, -geoparams.dy/2.0, +geoparams.rradius, 0, +geoparams.dy/2.0, +geoparams.rradius); break; case NC_BOX: mcdis_box(0., 0., 0., geoparams.dx, geoparams.dy, geoparams.dz); break; case NC_SPHERE: mcdis_circle("xy", 0., 0., 0., geoparams.rradius); mcdis_circle("xz", 0., 0., 0., geoparams.rradius); mcdis_circle("yz", 0., 0., 0., geoparams.rradius); break; }; %} END
package com.ixigo.sdk.payment.gpay import android.app.Activity import com.google.android.apps.nbu.paisa.inapp.client.api.PaymentsClient import com.google.android.apps.nbu.paisa.inapp.client.api.Wallet import com.ixigo.sdk.payment.data.GpayPaymentInput import org.json.JSONArray import org.json.JSONException import org.json.JSONObject object GpayUtils { /** * Create a Google Pay API base request object with properties used in all requests. * * @return Google Pay API base request object. * @throws JSONException */ private val baseRequest = JSONObject().apply { put("apiVersion", 2) put("apiVersionMinor", 0) } private fun getPaymentMethod(): JSONArray { val type = JSONObject().apply { put("type", "UPI") } return JSONArray().put(type) } /** * An object describing accepted forms of payment by your app, used to determine a viewer's * readiness to pay. * @return API version and payment methods supported by the app. */ fun isReadyToPayRequest(): String? { return try { baseRequest.apply { put("allowedPaymentMethods", getPaymentMethod()) }.toString() } catch (e: JSONException) { null } } /** * Creates an instance of [PaymentsClient] for use in an [Activity] using the environment and * theme set in [Constants]. */ fun createPaymentsClient(): PaymentsClient { return Wallet.getPaymentsClient() } /** * Provide Google Pay API with a payment amount, currency, and amount status. * * @return information about the requested payment. * @throws JSONException * @see [TransactionInfo] */ @Throws(JSONException::class) private fun getTransactionInfo(input: GpayPaymentInput): JSONObject { return JSONObject().apply { put("totalPrice", input.amount) put("totalPriceStatus", "FINAL") put("currencyCode", "INR") put("transactionNote", input.transactionNote) } } /** * An object describing information requested in a Google Pay payment sheet * @return Payment data expected by your app. * @see [PaymentDataRequest] */ fun getPaymentDataRequest(input: GpayPaymentInput): String { return baseRequest .apply { put("allowedPaymentMethods", JSONArray().put(getAllowedPaymentMethods(input))) put("transactionInfo", getTransactionInfo(input)) } .toString() } private fun getAllowedPaymentMethods(input: GpayPaymentInput): JSONObject { return JSONObject().apply { put("type", "UPI") put("parameters", getParameters(input)) put("tokenizationSpecification", JSONObject().apply { put("type", "DIRECT") }) } } private fun getParameters(input: GpayPaymentInput): JSONObject { return JSONObject().apply { put("payeeVpa", input.payeeVpa) put("payeeName", input.payeeName) put("referenceUrl", input.referenceUrl) put("mcc", input.mcc) put("transactionReferenceId", input.transactionReferenceId) // paymentTransactionId put("transactionId", input.transactionId) // paymentId (used by gpay) } } }
import React, { ChangeEvent, FC, InputHTMLAttributes, memo, useEffect, useRef } from 'react'; import { classNames } from '@/shared/lib/classNames/classNames'; import style from './Input.module.scss'; type InputExtends = Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'value' | 'readOnly'>; type InputTheme = 'default' | 'clear'; interface InputProps extends InputExtends { className?: string; theme?: InputTheme; value?: string | number; onChange?: (value: string) => void; readonly?: boolean; type?: string; autofocus?: boolean; } export const Input: FC<InputProps> = memo( ({ className, theme = 'default', value, onChange, type = 'text', autofocus, readonly, ...otherProps }: InputProps) => { const ref = useRef<HTMLInputElement>(null); const changeInput = (e: ChangeEvent<HTMLInputElement>) => { onChange?.(e.target.value); }; useEffect(() => { if (autofocus) { ref.current?.focus(); } }, [autofocus]); return ( <input ref={ref} value={value} onChange={changeInput} className={classNames(style.Input, { [style.readonly]: readonly }, [className, style[theme]])} type={type} readOnly={readonly} // eslint-disable-next-line {...otherProps} /> ); }, );
Play Codenames with Glove This repository implements a simple single-player version of the codenames game by Vlaada Chvátil. You can play as the agent or the spymaster, and the Glove word vectors will take the role of your partner, as you try to find the 8 marked words in as few rounds as possible. ``` $ git clone git@github.com:thomasahle/codenames.git ... $ sh get_glove.sh ... $ python3 codenames.py ...Loading vectors ...Loading words ...Making word to index dict ...Loading codenames Ready! Will you be agent or spymaster?: agent buck bat pumpkin charge iron well boot chick superhero glove stream germany sock dragon scientist duck bugle school ham mammoth bridge fair triangle capital horn Thinking.................... Clue: "golden 6" (certainty 7.78, remaining words 8) Your guess: bridge Correct! ``` How it works The bot decides what words go well together, by comparing their vectors in the GloVe trained on Wikipedia text. This means that words that often occour in the same articles and sentences are judged to be similar. In the example about, golden is of course similar to bridge by association with the Golden Gate Bridge. Other words that were found to be similar were 'dragon', 'triangle', 'duck', 'iron' and 'horn'. However, in Codenames the task is not merely to find words that describe other words well. You also need to make sure that 'bad words' are as different as possible from your clue. To achieve this, the bot tries to find a word that maximizes the similarity gap between the marked words and the bad words. If you want the bot to be more aggressive in its clues (choosing larger groups), try changing the `agg = .5` value near the top of `codenames.py` to a larger value, such as `.8` or `1.5`.
// // ContentView.swift // D35_Multiplication_Table // // Created by MacBook on 26.7.2023. // import SwiftUI struct NextQuestionButton: View { let nextQuestion: () -> Void let questionsAsked: Int let amountOfQuestions: Int let questionAnswered: Bool var buttonText: String { if questionsAsked + 1 == amountOfQuestions { return "Finish" } else { return "Next" } } var body: some View { Button() { nextQuestion() } label: { Text(buttonText) .font(.custom("chalkboardse", size: 20)) .frame(width: 55) .padding(.vertical, 30) .padding(.horizontal, 60) .background(Color(red: 1, green: 0.91, blue: 0.72)) .clipShape(RoundedRectangle(cornerRadius: 30)) .foregroundColor(.black) .shadow(color: Color(red: 0.37, green: 0.37, blue: 0.37), radius: 2, y: 15) } .opacity(questionAnswered ? 1 : 0) .animation(.easeInOut, value: questionAnswered) } } struct TotalScore: View { var score: Int var body: some View { Text("Total score: \(score)") .font( .custom("Fuzzy Bubbles", size: 20) ) .foregroundColor(.white) } } struct StartScreenWhichTableText: View { var body: some View { Text("Which table do you want to practice?") .font( .custom("chalkboardse", size: 14) .bold() ) .padding(.top, 28) .padding(.bottom, 9) } } struct StartScreenMainLogo: View { var body: some View { Text("Mathy Friends") .font( .custom("Fuzzy Bubbles", size: 40) ) .foregroundColor(.white) .shadow(radius: 5) } } struct StartScreenAmountOfQuestionsText: View { var body: some View { Text("Select amount of questions") .font( .custom("chalkboardse", size: 14) .bold() ) .padding(.top, 14) .padding(.bottom, 9) } } struct StartButton: View { var startGame: () -> Void var body: some View { Button() { startGame() } label: { Text("Start") .font( .custom("chalkboardse", size: 28) .bold() ) .padding(.horizontal, 60) .padding(.vertical, 20) } .background(Color(red: 0.61, green: 0.37, blue: 1)) .foregroundColor(.white) .clipShape(RoundedRectangle(cornerRadius: 30)) .shadow(radius: 10) } } struct StartScreenTablePickerStyle: ViewModifier { func body(content: Content) -> some View { content .padding(.top, 9) .padding(.bottom, 14) .padding(.horizontal, 30) .cornerRadius(20) .background(Color(red: 0.61, green: 0.37, blue: 1)) .clipShape(RoundedRectangle(cornerRadius: 15)) .accentColor(.white) .shadow(radius: 2) } } struct StartScreenInfoBoxStyle: ViewModifier { func body(content: Content) -> some View { content .background(.regularMaterial) .frame(maxWidth:.infinity) .clipShape(RoundedRectangle(cornerRadius: 40)) .padding(23) .shadow(radius: 2) } } struct AnswerButtonStyle: ViewModifier { let questionAnswered: Bool let number: Int let tappedButton: Int func body(content: Content) -> some View { content .disabled(questionAnswered) .padding(.horizontal, 15) .padding(.vertical, 15) .shadow(color: Color(red: 0.37, green: 0.37, blue: 0.37), radius: 2, y: number == tappedButton ? 0 : 15) .offset(y: number == tappedButton ? 0 : -20) .animation(.default, value: tappedButton) } } struct AnswerButtonTextStyle: ViewModifier { let questionAnswered: Bool let number: Int let correctAnswerIndex: Int func body(content: Content) -> some View { content .font(.custom("chalkboardse", size: 31)) .frame(width: 55) .padding(.vertical, 47) .padding(.horizontal, 47) .background(!questionAnswered ? Color.defaultButtonColor : (number == correctAnswerIndex ? Color.correctButtonColor : Color.wrongButtonColor)) .clipShape(Circle()) .foregroundColor(.black) } } struct GenerateAnswerButtons: View { let correctAnswerIndex: Int let tappedButton: Int let questionAnswered: Bool let answerChosen: (Int) -> Void let buttonAnswers: [Int] var body: some View { ForEach(0..<2) { row in HStack{ ForEach(0..<2) { column in Button { answerChosen(row*2+column) } label: { Text("\(buttonAnswers[row*2+column])") .answerButtonTextStyled(questionAnswered: questionAnswered, number: row*2+column, correctAnswerIndex: correctAnswerIndex ) } .answerButtonStyled(questionAnswered: questionAnswered, number: row*2+column, tappedButton: tappedButton) } } } } } extension View { func startScreenQuestionBoxStyled() -> some View { modifier(StartScreenInfoBoxStyle()) } func startScreenTablePickerStyled() -> some View { modifier(StartScreenTablePickerStyle()) } func answerButtonStyled(questionAnswered: Bool, number: Int, tappedButton: Int) -> some View { modifier(AnswerButtonStyle(questionAnswered: questionAnswered, number: number, tappedButton: tappedButton)) } func answerButtonTextStyled(questionAnswered: Bool, number: Int, correctAnswerIndex: Int) -> some View { modifier(AnswerButtonTextStyle(questionAnswered: questionAnswered, number: number, correctAnswerIndex: correctAnswerIndex)) } } extension Color { static let defaultButtonColor = Color("defaultButton") static let wrongButtonColor = Color("wrongButton") static let correctButtonColor = Color("correctButton") static let purpleBackground = Color("kidPurple") } struct ContentView: View { @State private var gameStarted = false @State private var questionAnswered = false @State private var questionsAmountChosen: Int = 5 @State private var multiplicationTable: Int = 2 @State private var score = 0 @State private var alertShowing = false @State private var correctAnswerIndex = -1 @State private var tappedButton = -1 @State private var questionsAsked = 0 private var amountOfQuestions = [5, 10, 15] @State private var buttonAnswers = [Int]() func restartGame() { gameStarted = false questionAnswered = false score = 0 correctAnswerIndex = -1 tappedButton = -1 questionsAsked = 0 } func buttonAnswersGenerator() -> [Int] { var fakeAnswer: Int = 0 var buttonAnswers = [Int]() for _ in 0...2 { repeat { fakeAnswer = Int.random(in: (answers[questionsAsked] - 10)..<(answers[questionsAsked] + 10)) if fakeAnswer < 0 { fakeAnswer *= -1 } } while (fakeAnswer == answers[questionsAsked] || buttonAnswers.contains(fakeAnswer)) buttonAnswers.append(fakeAnswer) } correctAnswerIndex = Int.random(in: 0...3) buttonAnswers.insert(answers[questionsAsked], at: correctAnswerIndex) return buttonAnswers } @State private var questions = [Int]() @State private var answers = [Int]() func startGame() { gameStarted = true questions.removeAll() answers.removeAll() for i in 0..<questionsAmountChosen { if questionsAmountChosen == 5 { var answer: Int repeat { answer = Int.random(in: 2...9) } while (questions.contains(answer)) questions.append(answer) } else { questions.append(Int.random(in: 2...9)) } answers.append(questions[i] * multiplicationTable) } buttonAnswers = buttonAnswersGenerator() } func answerChosen(numberOfButton: Int) { tappedButton = numberOfButton if numberOfButton == correctAnswerIndex { score += 1 } questionAnswered = true } func nextQuestion() { if questionsAsked + 1 != questionsAmountChosen { questionsAsked += 1 buttonAnswers = buttonAnswersGenerator() } else { alertShowing = true } questionAnswered = false tappedButton = -1 } var body: some View { NavigationView { ZStack(alignment: .bottom) { Color.purpleBackground.ignoresSafeArea() Image("MathyFriendsBackground") .renderingMode(.original) .resizable() .edgesIgnoringSafeArea(.all) if !gameStarted { VStack(spacing: 60) { Spacer() StartScreenMainLogo() VStack() { StartScreenWhichTableText() Picker("Table of...", selection: $multiplicationTable) { ForEach(2..<10, id: \.self) { table in Text("\(table)") } } .startScreenTablePickerStyled() Divider() .padding(.vertical, 14) .padding(.horizontal, 24) StartScreenAmountOfQuestionsText() Picker("Select", selection: $questionsAmountChosen) { ForEach(amountOfQuestions, id: \.self) { amount in Text("\(amount)") } } .pickerStyle(.segmented) .padding(.top, 9) .padding(.bottom, 28) .padding(.horizontal, 24) } .startScreenQuestionBoxStyled() StartButton(startGame: startGame) Spacer() Spacer() } } else { VStack { TotalScore(score: score) Spacer() Text("\(multiplicationTable) × \(questions[questionsAsked]) = ...") .font( .custom("Fuzzy Bubbles", size: 40) ) .foregroundColor(.white) .shadow(color: .black, radius: 20) Spacer() VStack{ GenerateAnswerButtons(correctAnswerIndex: correctAnswerIndex, tappedButton: tappedButton, questionAnswered: questionAnswered, answerChosen: answerChosen, buttonAnswers: buttonAnswers) } NextQuestionButton(nextQuestion: nextQuestion, questionsAsked: questionsAsked, amountOfQuestions: questionsAmountChosen, questionAnswered: questionAnswered) Spacer() } } } } .alert(isPresented: $alertShowing) { Alert( title: Text("Good job!"), message: Text("You've answered \(questionsAsked + 1) questions and you score is \(score)"), dismissButton: .default(Text("Restart")) { restartGame() } ) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
class WineListsController < ApplicationController # GET /wine_lists # GET /wine_lists.json def index @wine_lists = WineList.all respond_to do |format| format.html # index.html.erb format.json { render json: @wine_lists } end end # GET /wine_lists/1 # GET /wine_lists/1.json def show @wine_list = WineList.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @wine_list } end end # GET /wine_lists/new # GET /wine_lists/new.json def new @wine_list = WineList.new respond_to do |format| format.html # new.html.erb format.json { render json: @wine_list } end end # GET /wine_lists/1/edit def edit @wine_list = WineList.find(params[:id]) end # POST /wine_lists # POST /wine_lists.json def create @wine_list = WineList.new(params[:wine_list]) respond_to do |format| if @wine_list.save format.html { redirect_to @wine_list, notice: 'Wine list was successfully created.' } format.json { render json: @wine_list, status: :created, location: @wine_list } else format.html { render action: "new" } format.json { render json: @wine_list.errors, status: :unprocessable_entity } end end end # PUT /wine_lists/1 # PUT /wine_lists/1.json def update @wine_list = WineList.find(params[:id]) respond_to do |format| if @wine_list.update_attributes(params[:wine_list]) format.html { redirect_to @wine_list, notice: 'Wine list was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @wine_list.errors, status: :unprocessable_entity } end end end # DELETE /wine_lists/1 # DELETE /wine_lists/1.json def destroy @wine_list = WineList.find(params[:id]) @wine_list.destroy respond_to do |format| format.html { redirect_to wine_lists_url } format.json { head :no_content } end end end
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { static class Point{ int r; int c; public Point(int r, int c){ this.r = r; this.c = c; } } private static int moveRow[] = {1,-1,0,0}; private static int moveCol[] = {0,0,1,-1}; static boolean[][] visited; static int[][] map; static ArrayList<Integer> answers; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); visited = new boolean[n][n]; map = new int[n][n]; answers = new ArrayList<>(); Queue<Point> hasHome = new LinkedList<>(); for(int i=0; i<n; i++){ st = new StringTokenizer(br.readLine()); String str = st.nextToken(); for(int j=0; j<n; j++){ map[i][j] = Integer.parseInt(str.substring(j, j+1)); if(map[i][j]==1) hasHome.add(new Point(i,j)); } } while(!hasHome.isEmpty()){ Point start = hasHome.poll(); if(visited[start.r][start.c]) continue; int count = BFS(start); answers.add(count); } Collections.sort(answers); System.out.println(answers.size()); for(int a : answers) System.out.println(a); } private static int BFS(Point p){ Queue<Point> homeQueue = new LinkedList<>(); int count = 0; homeQueue.add(p); visited[p.r][p.c] = true; while(!homeQueue.isEmpty()){ Point preHome = homeQueue.poll(); count++; for(int i=0; i<4; i++){ int nextRow = preHome.r + moveRow[i]; int nextCol = preHome.c + moveCol[i]; if(nextRow >= 0 && nextCol >= 0 && nextRow < map.length && nextCol < map.length){ if(map[nextRow][nextCol] == 1 && !visited[nextRow][nextCol]){ homeQueue.add(new Point(nextRow, nextCol)); visited[nextRow][nextCol] = true; } } } // // 위쪽 집 검사 // if(preHome.r > 0){ // if(map[preHome.r-1][preHome.c]==1 && !visited[preHome.r-1][preHome.c]){ // homeQueue.add(new Point(preHome.r-1, preHome.c)); // visited[preHome.r-1][preHome.c] = true; // } // } // // // 아래쪽 집 검사 // if(preHome.r < map.length-1){ // if(map[preHome.r+1][preHome.c]==1 && !visited[preHome.r+1][preHome.c]){ // homeQueue.add(new Point(preHome.r+1, preHome.c)); // visited[preHome.r+1][preHome.c] = true; // } // } // // // 왼쪽 집 검사 // if(preHome.c > 0){ // if(map[preHome.r][preHome.c-1]==1 && !visited[preHome.r][preHome.c-1]){ // homeQueue.add(new Point(preHome.r, preHome.c-1)); // visited[preHome.r][preHome.c-1] = true; // } // } // // // 오른쪽 집 검사 // if(preHome.c < map.length-1){ // if(map[preHome.r][preHome.c+1]==1 && !visited[preHome.r][preHome.c+1]){ // homeQueue.add(new Point(preHome.r, preHome.c+1)); // visited[preHome.r][preHome.c+1] = true; // } // } } return count; } }
import * as React from 'react'; import { Autocomplete, AutocompleteInputChangeReason, TextField, } from '@mui/material'; import { SyntheticEvent } from 'react'; import { Controller } from 'react-hook-form'; import { VariableSizeList, ListChildComponentProps } from 'react-window'; function renderRow(props: ListChildComponentProps) { const { data, index, style } = props; const dataSet = data[index]; const inlineStyle = { ...style, }; return <li style={inlineStyle}>{dataSet}</li>; } const OuterElementContext = React.createContext({}); // eslint-disable-next-line react/display-name const OuterElementType = React.forwardRef<HTMLDivElement>((props, ref) => { const outerProps = React.useContext(OuterElementContext); return <div ref={ref} {...props} {...outerProps} />; }); // Adapter for react-window const ListboxComponent = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLElement> >(function ListboxComponent(props, ref) { const { children, ...other } = props; const itemData: React.ReactChild[] = []; (children as React.ReactChild[]).forEach( (item: React.ReactChild & { children?: React.ReactChild[] }) => { itemData.push(item); } ); const itemCount = itemData.length; const itemSize = 60; const getChildSize = () => { return itemSize; }; const getHeight = () => { return 8 * itemSize; }; return ( <div ref={ref}> <OuterElementContext.Provider value={other}> <VariableSizeList itemData={itemData} height={getHeight()} width="100%" outerElementType={OuterElementType} innerElementType="div" itemSize={() => getChildSize()} overscanCount={20} itemCount={itemCount} > {renderRow} </VariableSizeList> </OuterElementContext.Provider> </div> ); }); export interface IAutocompleteTextfieldProps { name: string; label?: string; placeholder?: string; multiple?: boolean; freeSolo?: boolean; disabled?: boolean; control: any; //eslint-disable-line @typescript-eslint/no-explicit-any options: any[]; //eslint-disable-line @typescript-eslint/no-explicit-any startAdornment?: React.ReactElement; disableCloseOnSelect?: boolean; // eslint-disable-next-line @typescript-eslint/no-explicit-any ListboxComponent?: (props: any, ref: any) => any; isOptionEqualToValue: (option: any, value: any) => boolean; //eslint-disable-line @typescript-eslint/no-explicit-any renderOption?: (props: any, option: any) => React.ReactNode; //eslint-disable-line @typescript-eslint/no-explicit-any getOptionLabel?: (option: any) => string; //eslint-disable-line @typescript-eslint/no-explicit-any onInputChange?: ( event: SyntheticEvent<Element, Event>, value: string, reason: AutocompleteInputChangeReason ) => void; } export function AutocompleteTextfield({ name, label, placeholder, multiple, disabled = false, control, options, startAdornment, freeSolo, disableCloseOnSelect, isOptionEqualToValue, renderOption, getOptionLabel, onInputChange, }: IAutocompleteTextfieldProps) { return ( <Controller name={name} control={control} render={({ field: { onChange, value }, fieldState: { error } }) => ( <Autocomplete multiple={multiple} disabled={disabled} freeSolo={freeSolo} autoSelect={freeSolo} // if freeSolo, autoSelect should also be true id={`${name}-autocomplete`} options={options} ListboxComponent={ListboxComponent} value={value} getOptionLabel={getOptionLabel} isOptionEqualToValue={isOptionEqualToValue} renderOption={renderOption} ChipProps={{ sx: { backgroundColor: 'white', padding: '1rem 0.5rem', fontWeight: 500, fontSize: '0.8125rem', lineHeight: '1rem', borderRadius: '3.75rem', }, }} filterOptions={(x) => x} disableCloseOnSelect={disableCloseOnSelect} onChange={(e, data) => { onChange(data); }} onInputChange={onInputChange} renderInput={(params) => ( <TextField {...params} label={label} disabled={disabled} placeholder={placeholder} error={error ? true : false} InputProps={{ ...params.InputProps, startAdornment: ( <> {/* if autocomplete chips exist, hide custom startAdornment */} {!params.InputProps.startAdornment && startAdornment} {params.InputProps.startAdornment} </> ), }} helperText={error ? error?.message : ''} /> )} /> )} /> ); }
// Copyright 2024 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill/core/browser/test_payments_data_manager.h" #include "base/uuid.h" #include "components/autofill/core/browser/personal_data_manager.h" namespace autofill { TestPaymentsDataManager::TestPaymentsDataManager(const std::string& app_locale, PersonalDataManager* pdm) : PaymentsDataManager(/*profile_database=*/nullptr, /*account_database=*/nullptr, /*image_fetcher=*/nullptr, /*shared_storage_handler=*/nullptr, /*pref_service=*/nullptr, app_locale, pdm) {} TestPaymentsDataManager::~TestPaymentsDataManager() = default; void TestPaymentsDataManager::LoadCreditCards() { // Overridden to avoid a trip to the database. pending_creditcards_query_ = 125; pending_server_creditcards_query_ = 126; { std::vector<std::unique_ptr<CreditCard>> credit_cards; local_credit_cards_.swap(credit_cards); std::unique_ptr<WDTypedResult> result = std::make_unique<WDResult<std::vector<std::unique_ptr<CreditCard>>>>( AUTOFILL_CREDITCARDS_RESULT, std::move(credit_cards)); OnWebDataServiceRequestDone(pending_creditcards_query_, std::move(result)); } { std::vector<std::unique_ptr<CreditCard>> credit_cards; server_credit_cards_.swap(credit_cards); std::unique_ptr<WDTypedResult> result = std::make_unique<WDResult<std::vector<std::unique_ptr<CreditCard>>>>( AUTOFILL_CREDITCARDS_RESULT, std::move(credit_cards)); OnWebDataServiceRequestDone(pending_server_creditcards_query_, std::move(result)); } } void TestPaymentsDataManager::LoadCreditCardCloudTokenData() { pending_server_creditcard_cloud_token_data_query_ = 127; { std::vector<std::unique_ptr<CreditCardCloudTokenData>> cloud_token_data; server_credit_card_cloud_token_data_.swap(cloud_token_data); std::unique_ptr<WDTypedResult> result = std::make_unique< WDResult<std::vector<std::unique_ptr<CreditCardCloudTokenData>>>>( AUTOFILL_CLOUDTOKEN_RESULT, std::move(cloud_token_data)); OnWebDataServiceRequestDone( pending_server_creditcard_cloud_token_data_query_, std::move(result)); } } void TestPaymentsDataManager::LoadIbans() { pending_local_ibans_query_ = 128; pending_server_ibans_query_ = 129; { std::vector<std::unique_ptr<Iban>> ibans; local_ibans_.swap(ibans); std::unique_ptr<WDTypedResult> result = std::make_unique<WDResult<std::vector<std::unique_ptr<Iban>>>>( AUTOFILL_IBANS_RESULT, std::move(ibans)); OnWebDataServiceRequestDone(pending_local_ibans_query_, std::move(result)); } { std::vector<std::unique_ptr<Iban>> server_ibans; server_ibans_.swap(server_ibans); std::unique_ptr<WDTypedResult> result = std::make_unique<WDResult<std::vector<std::unique_ptr<Iban>>>>( AUTOFILL_IBANS_RESULT, std::move(server_ibans)); OnWebDataServiceRequestDone(pending_server_ibans_query_, std::move(result)); } } bool TestPaymentsDataManager::RemoveByGUID(const std::string& guid) { if (CreditCard* credit_card = GetCreditCardByGUID(guid)) { local_credit_cards_.erase(base::ranges::find( local_credit_cards_, credit_card, &std::unique_ptr<CreditCard>::get)); pdm_->NotifyPersonalDataObserver(); return true; } else if (const Iban* iban = GetIbanByGUID(guid)) { local_ibans_.erase( base::ranges::find(local_ibans_, iban, &std::unique_ptr<Iban>::get)); pdm_->NotifyPersonalDataObserver(); return true; } return false; } void TestPaymentsDataManager::RecordUseOfCard(const CreditCard* card) { CreditCard* credit_card = GetCreditCardByGUID(card->guid()); if (credit_card) { credit_card->RecordAndLogUse(); } } void TestPaymentsDataManager::RecordUseOfIban(Iban& iban) { std::unique_ptr<Iban> updated_iban = std::make_unique<Iban>(iban); std::vector<std::unique_ptr<Iban>>& container = iban.record_type() == Iban::kLocalIban ? local_ibans_ : server_ibans_; auto it = base::ranges::find(container, iban.record_type() == Iban::kLocalIban ? GetIbanByGUID(iban.guid()) : GetIbanByInstrumentId(iban.instrument_id()), &std::unique_ptr<Iban>::get); if (it != container.end()) { it->get()->RecordAndLogUse(); } } void TestPaymentsDataManager::AddCreditCard(const CreditCard& credit_card) { std::unique_ptr<CreditCard> local_credit_card = std::make_unique<CreditCard>(credit_card); local_credit_cards_.push_back(std::move(local_credit_card)); pdm_->NotifyPersonalDataObserver(); } std::string TestPaymentsDataManager::AddAsLocalIban(Iban iban) { CHECK_EQ(iban.record_type(), Iban::kUnknown); iban.set_record_type(Iban::kLocalIban); iban.set_identifier( Iban::Guid(base::Uuid::GenerateRandomV4().AsLowercaseString())); std::unique_ptr<Iban> local_iban = std::make_unique<Iban>(iban); local_ibans_.push_back(std::move(local_iban)); pdm_->NotifyPersonalDataObserver(); return iban.guid(); } std::string TestPaymentsDataManager::UpdateIban(const Iban& iban) { const Iban* old_iban = GetIbanByGUID(iban.guid()); CHECK(old_iban); local_ibans_.push_back(std::make_unique<Iban>(iban)); RemoveByGUID(iban.guid()); return iban.guid(); } void TestPaymentsDataManager::DeleteLocalCreditCards( const std::vector<CreditCard>& cards) { for (const auto& card : cards) { // Removed the cards silently and trigger a single notification to match the // behavior of PersonalDataManager. RemoveCardWithoutNotification(card); } pdm_->NotifyPersonalDataObserver(); } void TestPaymentsDataManager::UpdateCreditCard(const CreditCard& credit_card) { if (GetCreditCardByGUID(credit_card.guid())) { // AddCreditCard will trigger a notification to observers. We remove the old // card without notification so that exactly one notification is sent, which // matches the behavior of the PersonalDataManager. RemoveCardWithoutNotification(credit_card); AddCreditCard(credit_card); } } void TestPaymentsDataManager::AddServerCvc(int64_t instrument_id, const std::u16string& cvc) { auto card_iterator = std::find_if(server_credit_cards_.begin(), server_credit_cards_.end(), [instrument_id](auto& card) { return card->instrument_id() == instrument_id; }); if (card_iterator != server_credit_cards_.end()) { card_iterator->get()->set_cvc(cvc); } } void TestPaymentsDataManager::ClearServerCvcs() { for (CreditCard* card : GetServerCreditCards()) { if (!card->cvc().empty()) { card->clear_cvc(); } } } void TestPaymentsDataManager::ClearLocalCvcs() { for (CreditCard* card : GetLocalCreditCards()) { if (!card->cvc().empty()) { card->clear_cvc(); } } } bool TestPaymentsDataManager::IsAutofillPaymentMethodsEnabled() const { // Return the value of autofill_payment_methods_enabled_ if it has been set, // otherwise fall back to the normal behavior of checking the pref_service. if (autofill_payment_methods_enabled_.has_value()) { return autofill_payment_methods_enabled_.value(); } return PaymentsDataManager::IsAutofillPaymentMethodsEnabled(); } void TestPaymentsDataManager::ClearCreditCards() { local_credit_cards_.clear(); server_credit_cards_.clear(); } void TestPaymentsDataManager::ClearCreditCardOfferData() { autofill_offer_data_.clear(); } void TestPaymentsDataManager::RemoveCardWithoutNotification( const CreditCard& card) { if (CreditCard* existing_credit_card = GetCreditCardByGUID(card.guid())) { local_credit_cards_.erase( base::ranges::find(local_credit_cards_, existing_credit_card, &std::unique_ptr<CreditCard>::get)); } } } // namespace autofill
// Copyright © 2022 Polar. All rights reserved. import XCTest @testable import iOSCommunications final class PpiDataTest: XCTestCase { func testProcessPpiRawDataType0() throws { // Arrange // HEX: 03 00 94 35 77 00 00 00 00 00 // index data: // 0 type 03 (PPI) // 1..9 timestamp 00 00 00 00 00 00 00 00 // 10 frame type 00 (raw, type 0) let ppiDataFrameHeader = Data([ 0x01, 0x00, 0x94, 0x35, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, ]) let previousTimeStamp:UInt64 = 100 // HEX: 80 80 80 80 80 FF 00 01 00 01 00 00 // index type data: // 0 HR 0x80 (128) let heartRate = 128 // 1..2 PP 0x80 0x80 (32896) let intervalInMs:UInt16 = 32896 // 3..4 PP Error Estimate 0x80 0x80 (32896) let errorEstimate:UInt16 = 32896 // 5 PP flags 0xFF let blockerBit:Int = 0x01 let skinContactStatus:Int = 0x01 let skinContactSupported:Int = 0x01 // 6 HR 0x00 (0) let heartRate2 = 0 // 7..8 PP 0x01 0x00 (1) let intervalInMs2:UInt16 = 1 // 9..10 PP Error Estimate 0x01 0x00 (1) let errorEstimate2:UInt16 = 1 // 11 PP flags 0x00 let blockerBit2:Int = 0x00 let skinContactStatus2:Int = 0x00 let skinContactSupported2:Int = 0x00 let ppiDataFrameContent = Data([ 0x80, 0x80, 0x80, 0x80, 0x80, 0xFF, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00 ]) //let timeStamp: Long = Long.MAX_VALUE let dataFrame = try PmdDataFrame( data: ppiDataFrameHeader + ppiDataFrameContent, { _ in previousTimeStamp } , { _ in 1.0 }, { _ in 0 }) // Act let ppiData = try PpiData.parseDataFromDataFrame(frame: dataFrame) // Assert XCTAssertEqual(heartRate, ppiData.samples[0].hr) XCTAssertEqual(intervalInMs, ppiData.samples[0].ppInMs) XCTAssertEqual(errorEstimate, ppiData.samples[0].ppErrorEstimate) XCTAssertEqual(blockerBit, ppiData.samples[0].blockerBit) XCTAssertEqual(skinContactStatus, ppiData.samples[0].skinContactStatus) XCTAssertEqual(skinContactSupported, ppiData.samples[0].skinContactSupported) XCTAssertEqual(heartRate2, ppiData.samples[1].hr) XCTAssertEqual(intervalInMs2, ppiData.samples[1].ppInMs) XCTAssertEqual(errorEstimate2, ppiData.samples[1].ppErrorEstimate) XCTAssertEqual(blockerBit2, ppiData.samples[1].blockerBit) XCTAssertEqual(skinContactStatus2, ppiData.samples[1].skinContactStatus) XCTAssertEqual(skinContactSupported2, ppiData.samples[1].skinContactSupported) XCTAssertEqual(2, ppiData.samples.count) } }
import TodoItem from "./TodoItem"; import { Todo } from "./types"; interface TodoListProps { todos: Todo[] | undefined; // Ensure todos can be undefined onEditTodo: (id: number, updatedTitle: string) => void; onDeleteTodo: (id: number) => void; } const TodoList: React.FC<TodoListProps> = ({ todos, onEditTodo, onDeleteTodo, }) => { if (!todos || todos.length === 0) { // Handle the case where todos is undefined or empty return ( <div className="mt-4"> <p className="text-gray-600">No todos to display.</p> </div> ); } return ( <div className="mt-4"> {todos.map((todo) => ( <TodoItem key={todo.id} todo={todo} onEditTodo={onEditTodo} onDeleteTodo={onDeleteTodo} /> ))} </div> ); }; export default TodoList;
import type { Credential, CredentialData } from '../../../slices/types' import { motion } from 'framer-motion' import { startCase } from 'lodash' import React from 'react' import { fadeX } from '../../../FramerAnimations' import { StateIndicator } from '../../../components/StateIndicator' import { useCredentials } from '../../../slices/credentials/credentialsSelectors' import { prependApiUrl } from '../../../utils/Url' export interface Props { credentials: Credential[] } export const StarterCredentials: React.FC<Props> = ({ credentials }) => { const { issuedCredentials } = useCredentials() const issuedCredentialsStartCase = issuedCredentials.map((name) => startCase(name)) return ( <motion.div variants={fadeX} animate="show" exit="exit" className="flex flex-col bg-bcgov-white dark:bg-bcgov-black m-4 px-4 py-2 w-auto md:w-96 h-auto rounded-lg shadow" > <div className="flex-1-1 title mb-2"> <h1 className="font-semibold dark:text-white">Starter credentials</h1> <hr className="text-bcgov-lightgrey" /> </div> {credentials.map((item) => { const completed = issuedCredentials.includes(item.name) || issuedCredentialsStartCase.includes(item.name) return ( <div key={item.name} className="flex-1 flex flex-row items-center justify-between my-2"> <div className="bg-bcgov-lightgrey rounded-lg p-2 w-12"> <img className="h-8 m-auto" src={prependApiUrl(item.icon)} alt="icon" /> </div> <div className="flex-1 px-4 justify-self-start dark:text-white text-sm sm:text-base"> <p>{startCase(item.name)}</p> </div> <StateIndicator completed={completed} /> </div> ) })} </motion.div> ) }
using Database.Constants; using Database.Entities; using Database.Enums; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using System.Globalization; namespace Database; /// <summary> /// Контекст базы данных. /// </summary> public sealed class Context : IdentityDbContext<IdentityUser> { /// <summary> /// Создаёт экземпляр класса. /// </summary> /// <param name="options">Настройки для создания <see cref="Context"/>.</param> public Context(DbContextOptions options) : base(options) { } /// <summary> /// Таблица с категориями. /// </summary> public DbSet<Category> Categories { get; set; } /// <summary> /// Таблица с языками для изучения. /// </summary> public DbSet<Language> Languages { get; set; } /// <summary> /// Таблица с голосами. /// </summary> public DbSet<Voice> Voices { get; set; } /// <summary> /// Таблица с фразами. /// </summary> public DbSet<Phrase> Phrases { get; set; } /// <summary> /// Таблица с переводами. /// </summary> public DbSet<Translation> Translations { get; set; } /// <summary> /// Таблица с аудиофайлами. /// </summary> public DbSet<Audio> Audios { get; set; } /// <summary> /// Таблица с настройками. /// </summary> public DbSet<Setting> Settings { get; set; } /// <summary> /// Таблица с флагами, которые пользователь может применить к переводу. /// </summary> public DbSet<UserTranslation> UserTranslations { get; set; } /// <summary> /// Заполняет таблицы стандартными значениями. /// </summary> /// <param name="builder"><see cref="ModelBuilder"/>.</param> protected override void OnModelCreating(ModelBuilder builder) { ArgumentNullException.ThrowIfNull(builder, nameof(builder)); base.OnModelCreating(builder); var russianLanguage = new Language() { Id = 1, Name = "Русский", Enabled = true }; var serbianLanguage = new Language() { Id = 2, Name = "Сербский", Enabled = true }; var category = new Category { Id = 1, Name = "Общие", Enabled = true }; var phrase = new Phrase { Id = 1, CategoryId = category.Id, Text = "Привет", Enabled = true }; var russianVoice = new Voice { Id = 1, LanguageId = russianLanguage.Id, Name = "Борислав", Gender = Gender.Male }; var serbianVoice = new Voice { Id = 2, LanguageId = serbianLanguage.Id, Name = "Nicholas", Gender = Gender.Male }; var russianTranslation = new Translation { Id = 1, PhraseId = phrase.Id, LanguageId = russianLanguage.Id, Text = "Привет" }; var serbianTranslation = new Translation { Id = 2, PhraseId = phrase.Id, LanguageId = serbianLanguage.Id, Text = "Здраво" }; var russianAudio = new Audio { Id = russianTranslation.Id, VoiceId = russianVoice.Id, }; var serbianAudio = new Audio { Id = serbianTranslation.Id, VoiceId = serbianVoice.Id, }; var setting = new Setting { Key = SettingKey.OriginalLanguageId, Value = russianLanguage.Id.ToString(CultureInfo.InvariantCulture) }; builder.Entity<Language>().HasData(russianLanguage, serbianLanguage); builder.Entity<Category>().HasData(category); builder.Entity<Phrase>().HasData(phrase); builder.Entity<Voice>().HasData(russianVoice, serbianVoice); builder.Entity<Translation>().HasData(russianTranslation, serbianTranslation); builder.Entity<Audio>().HasData(russianAudio, serbianAudio); builder.Entity<Setting>().HasData(setting); } }
import { Entity, Column, PrimaryGeneratedColumn, } from 'typeorm'; export type UserRoleType = "admin" | "user" @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column('varchar') name: string; @Column('varchar', { unique: true, }) email: string; @Column('varchar') password: string; @Column({ type: "enum", enum: ["admin", "user"], default: "user" }) role: UserRoleType @Column({ type: 'jsonb', default: [] }) has_access_of: {}; @Column({ type: 'timestamp', default: new Date().toISOString() }) created_at: string; @Column({ type: 'timestamp', default: new Date().toISOString() })updated_at: string; }
## 思考和练习 请思考下面的问题。 ### Attention 1. 你怎么理解Attention? 2. 乘性Attention和加性Attention有什么不同? 3. Self-Attention为什么采用 Dot-Product Attention? 4. Self-Attention中的Scaled因子有什么作用?必须是 `sqrt(d_k)` 吗? 5. Multi-Head Self-Attention,Multi越多越好吗,为什么? 6. Multi-Head Self-Attention,固定`hidden_dim`,你认为增加 `head_dim` (需要缩小 `num_heads`)和减少 `head_dim` 会对结果有什么影响? 7. 为什么我们一般需要对 Attention weights 应用Dropout?哪些地方一般需要Dropout?Dropout在推理时是怎么执行的?你怎么理解Dropout? 8. Self-Attention的qkv初始化时,bias怎么设置,为什么? 9. 你还知道哪些变种的Attention?它们针对Vanilla实现做了哪些优化和改进? 10. 你认为Attention的缺点和不足是什么? 11. 你怎么理解Deep Learning的Deep?现在代码里只有一个Attention,多叠加几个效果会好吗? 12. DeepLearning中Deep和Wide分别有什么作用,设计模型架构时应怎么考虑? ### LLM 1. 你怎么理解Tokenize?你知道几种Tokenize方式,它们有什么区别? 2. 你觉得一个理想的Tokenizer模型应该具备哪些特点? 3. Tokenizer中有一些特殊Token,比如开始和结束标记,你觉得它们的作用是什么?我们为什么不能通过模型自动学习到开始和结束标记? 4. 为什么LLM都是Decoder-Only的? 5. RMSNorm的作用是什么,和LayerNorm有什么不同?为什么不用LayerNorm? 6. LLM中的残差连接体现在哪里?为什么用残差连接? 7. PreNormalization和PostNormalization会对模型有什么影响?为什么现在LLM都用PreNormalization? 8. FFN为什么先扩大后缩小,它们的作用分别是什么? 9. 为什么LLM需要位置编码?你了解几种位置编码方案? 10. 为什么RoPE能从众多位置编码中脱颖而出?它主要做了哪些改进? 11. 如果让你设计一种位置编码方案,你会考虑哪些因素? 12. 请你将《LLM部分》中的一些设计(如RMSNorm)加入到《Self-Attention部分》的模型设计中,看看能否提升效果?
Container Class It is just a class that have access directly to the Application State (Redux). More Info REACT-REDUX React and Redux are not at all connected. They are a totally separed projects and to connect them we need to use a specific library named ReactRedux. So, you must to import a special component named 'connect' from react-redux. import { connect } from 'react-redux'; Then, you need to use this component into the container class. Here we won't export the class, instead of it we will create a function named 'mapStateToProps' that will receive the 'application state' as a parameter. Whatever is returned will show up as props inside of BookList. EVERY TIME the application state changes, this method is called! function mapStateToProps(state) { return { books = state.books; }; } Finally, remember that we are not using the 'export default' directly into our component (in this case the 'container class') anymore. However we yet must to export our component ('container class'), using the 'connect' component from 'react-redux'. Here we will also connect our container class with the function used to connect the application state to the class props (mapSteteToProps). This is the snippet of code that produces the 'container class'. export default connect(mapStateToProps)(BooksList); Involved files: /reducers/reducer_books.js It is our application state data. /reducers/index.js It is the file that combines the application state data to a state name. BooksReduce -> books /containers/books-list.js It is our container class component. /components/app.js Just render the books-list.js. ACTIONS VS ACTIONS-CREATORS An Action Creator is just a function that returns an Action. An Action is just an object that flows through all of different Reducers. Reducers can then use that Action to produce a different value for a particular piece of State. At this example, we will be creating an Action to select books from the BookList. Involved files: /actions/index.js Here we just export a function that receives a book as a parameter. ex.: export default function selectBook(book) { console.log('A book has been selected: ', book.tilte); } /containers/book-list.js Here we will bind the selectBook Action to be used on the book-list.js, add the bindActionCreators (redux) The bindActionCreators is a a function will be responsible to take the value from the Action selectBook and check all the reducers into the application looking for its own reducer. (???) ex.: import { selectBook } from '../actions/index'; import { bindActionCreators } from 'redux'; // Anything returned from this function will end up as props // on the BookList container function mapDispatchToProps(dispatch) { // Whenever selectBook is called, the result should be passed // to all of our reducers return bindActionCreators( { selectBook: selectBook }, dispatch ); } // Promote BookList from a Component to a Container - It needs to know // about this new dispatch method, selectBook. Make it available as a prop export default connect(mapStateToProps, mapDispatchToProps)(BooksList);
import React, { useState } from 'react'; import { useDispatch } from 'react-redux'; import { selectItem } from 'features/products/views/slice'; import { Box, Grid, IconButton, ListItem } from '@mui/material'; import GridItem from 'common/components/dataDisplay/GridItem'; import EditCategory from 'features/products/categories/components/EditCategory'; import { DeleteForever, Edit } from '@mui/icons-material'; function CategoryOverviewItem({ category, setTriggerDelete, selected }) { const dispatch = useDispatch(); const [editCategoryOpen, setEditCategoryOpen] = useState(false); function handleEditCategory(event) { setEditCategoryOpen(true); } function handleSelectCategory(event) { dispatch(selectItem(category.id)); } return ( <React.Fragment> <ListItem sx={{ px: 2, py: 1, bgcolor: (theme) => (selected ? theme.palette.primary.light + '33' : null) }} button={!selected} onClick={!selected ? handleSelectCategory : null} > <Grid container> <GridItem item xs={1}> {category.id} </GridItem> <GridItem item xs={2}> {category.name} </GridItem> <GridItem item xs={2}> {category.desc} </GridItem> <GridItem item xs={2}> {category.products.length} </GridItem> <GridItem item xs={2}> {new Date(category.created).toLocaleDateString('DE-de')} </GridItem> <Box sx={{ visibility: selected ? 'visible' : 'hidden' }} display="flex" flexGrow={1} justifyContent="flex-end" > <IconButton aria-label="edit" size="small" onClick={handleEditCategory}> <Edit fontSize="small" /> </IconButton> <IconButton aria-label="edit" size="small" onClick={() => setTriggerDelete(true)}> <DeleteForever fontSize="small" color="error" /> </IconButton> </Box> </Grid> </ListItem> <EditCategory open={editCategoryOpen} onClose={() => setEditCategoryOpen(false)} category={category} /> </React.Fragment> ); } export default React.memo(CategoryOverviewItem);
import { useLocalization } from '@fluent/react'; import { useState } from 'react'; import { SetPauseTrackingRequestT, RpcMessage, TrackingPauseStateResponseT, TrackingPauseStateRequestT, } from 'solarxr-protocol'; import { useWebsocketAPI } from '@/hooks/websocket-api'; import { BigButton } from './commons/BigButton'; import { PlayIcon } from './commons/icon/PlayIcon'; import { PauseIcon } from './commons/icon/PauseIcon'; export function TrackingPauseButton( props: React.HTMLAttributes<HTMLButtonElement> ) { const { l10n } = useLocalization(); const { useRPCPacket, sendRPCPacket } = useWebsocketAPI(); const [trackingPause, setTrackingPause] = useState(false); const toggleTracking = () => { const pause = new SetPauseTrackingRequestT(!trackingPause); sendRPCPacket(RpcMessage.SetPauseTrackingRequest, pause); }; useRPCPacket( RpcMessage.TrackingPauseStateResponse, (data: TrackingPauseStateResponseT) => { setTrackingPause(data.trackingPaused); } ); sendRPCPacket( RpcMessage.TrackingPauseStateRequest, new TrackingPauseStateRequestT() ); return ( <BigButton text={l10n.getString( trackingPause ? 'tracking-paused' : 'tracking-unpaused' )} icon={trackingPause ? <PlayIcon width={20} /> : <PauseIcon width={20} />} onClick={toggleTracking} className={props.className} ></BigButton> ); }
(in-package regression) (macrolet ((make-updater-step (name estimator updater) `(defun ,name (A Y X estimate err sigma rho) (declare ((simple-array single-float) Y A X estimate err)) (declare (single-float rho sigma)) (with-matrixes ,estimator :declarations nil :target estimate) (with-matrixes (- Y estimate) :declarations nil :target err) (with-matrixes (+ (* rho A) (* sigma ,updater)) :target A :declarations ((scalar rho sigma)))))) (make-updater-step linear-updater (* X A) (* (transpose X) err)) (make-updater-step logistic-updater (map sigma (* X A)) (* (transpose X) (map dsigma err estimate)))) (macrolet ((make-updater-step (name estimator updater) `(defun ,name (A Y X estimate err sigma rho) (declare ((simple-array single-float) Y A X estimate err)) (declare (single-float rho sigma)) (setq rho (- 1 rho)) (with-matrixes ,estimator :declarations nil :target estimate) (with-matrixes (- Y estimate) :declarations nil :target err) (with-matrixes (+ A (* sigma ,updater)) :target A :declarations ((scalar sigma))) (with-matrixes (map (lambda (a) (cond ((> a rho) (- a rho)) ((> (- rho) a) (+ rho a)) (t 0.0))) A) :target A :declarations ((scalar rho)))))) (make-updater-step linear-updater-l1reg (* X A) (* (transpose X) err)) (make-updater-step logistic-updater-l1reg (map sigma (* X A)) (* (transpose X) (map dsigma err estimate)))) (defun do-regression-fn (update-fn Y A X sigma rho count body-fn) "Update up to COUNT times matrix A, and execute BODY in each iteration. In each step, A is set to ρA+σU, where U is provided updater. Parameter ρ below 1s0 prevents overfitting, and σ determines the speed of the regression. They are relate The ESTIMATOR is a matrix expression passed to `with-matrixes' macro. The body is executed with these bindings: - ESTIMATE for estimated value, - ERR for difference between the ESTIMATE and Y - Iteration count I and can use (RETURN) to terminate the loop, or change the parameters. ESTIMATOR and ERR are calculated even when not needed. This may change in future. " (loop with err = (make-array (array-dimensions Y) :element-type 'single-float) and estimate = (make-array (array-dimensions Y) :element-type 'single-float) for i from 0 to count do (funcall update-fn A Y X estimate err sigma rho) (funcall body-fn i err))) (defun do-normalized-iteration (update-fn Y A X iteration-speed regularization-cost-per-item count out tracing) (let* ((samples (array-dimension X 0)) (parameters (array-dimension X 1)) (dependents (array-dimension A 1)) (sigma (/ iteration-speed samples dependents)) (rho (- 1s0 (/ (* regularization-cost-per-item iteration-speed) parameters dependents)))) (assert (>= 1.0 rho 0.0)) (assert (>= sigma 0.0)) (when out (format out "~&# Samples: ~d Parameters: ~d Dependends: ~d~%" samples parameters dependents) (format out "~&# rho: ~f sigma: ~s~%" rho sigma)) (do-regression-fn update-fn Y A X sigma rho count (lambda (i err) (when (and out (zerop (mod i tracing))) (let ((e (/ (trace-times-transposed err err) 2.0 samples dependents)) (a-err (/ (* regularization-cost-per-item (trace-times-transposed A A)) dependents parameters 2.0))) (format out "~a ~a ~a ~a~%" i e A-err (+ e A-err)))))))) (defun linear-regression-iterations (Y A X msigma alpha count out tracing) (declare ((simple-array single-float) Y A X)) (do-normalized-iteration #'linear-updater Y A X msigma alpha count out tracing)) (defun logistic-regression-iterations (Y A X msigma alpha count out tracing) (do-normalized-iteration #'logistic-updater Y A X msigma alpha count out tracing)) (defun get-coefficients (fn y raw-x &key (A (make-random-array (array-dimension raw-x 1) (array-dimension y 1) 1s-2)) (sigma (- (/ 1s0 (array-dimension y 0)))) (alpha 0s0) out (tracing 100) (count 1000)) "Get coefficients for linear regression from data. Assumes that first row of X is all ones. This corresponds to getting linear term, and it is also used for normalization purposes." (assert (dotimes (i (array-dimension raw-x 0) t) (unless (= 1.0 (aref raw-x i 0)) (return nil)))) (multiple-value-bind (x norm) (normalize raw-x) (do-normalized-iteration fn y A x sigma alpha count out tracing) (with-matrixes (* norm A) :optimize ((speed 1))))) (defun linear-get-coefficients (&rest args) (apply #'get-coefficients #'linear-updater args)) (defun logistic-get-coefficients (&rest args) (apply #'get-coefficients #'logistic-updater args)) (defun logistic-l1-get-coefficients (&rest args) (apply #'get-coefficients #'logistic-updater-l1reg args)) (defmacro with-test-case ((samples indeps deps) &body body) `(multiple-value-bind (X Y A) (test-case ,samples ,indeps ,deps) ,@body))
import { prisma } from '@/lib/prisma' import { checkRateLimit } from '@/lib/ratelimit' import { setToolsOccurrences, slugger } from '@/lib/slugger' import { toolsSchema } from '@/schema/tools.schema' import { authOptions } from '@/utils/authOptions' import { getServerSession } from 'next-auth' import { NextResponse } from 'next/server' export async function GET(request: Request) { try { const headers = await checkRateLimit(request.headers.get("x-forwarded-for") ?? "") if (headers) { return new NextResponse("You can only send a request once per hour.", { status: 429, headers }) } const session = await getServerSession(authOptions); if (!session?.user.id || !(['USER', 'SUPER_ADMIN'].includes(session?.user.role || ""))) { return new NextResponse(JSON.stringify({ error: 'user unauthorised' }), { status: 403 }) } const tool = await prisma.tools.findMany({ where: { userId: session?.user.id }, include: { tags: true, user: true } }) return NextResponse.json(tool) } catch (error) { return new NextResponse(JSON.stringify({ error }), { status: 500 }) } } export const POST = async (request: Request) => { try { const headers = await checkRateLimit(request.headers.get("x-forwarded-for") ?? "") if (headers) { return new NextResponse("You can only send a request once per hour.", { status: 429, headers }) } const session = await getServerSession(authOptions); if (!session?.user.id || !(['USER', 'SUPER_ADMIN'].includes(session?.user.role || ""))) { return new NextResponse(JSON.stringify({ error: 'user unauthorised' }), { status: 403 }) } const tool = await prisma.tools.findMany({ where: { userId: session?.user.id } }) const body: unknown = await request.json(); const result = toolsSchema.safeParse(body); if (!result.success) { let zodErrors = {}; result.error.issues.forEach((issue) => { zodErrors = { ...zodErrors, [issue.path[0]]: issue.message }; }); return new NextResponse(JSON.stringify({ error: zodErrors }), { status: 400 }) } const requestTool = result.data const name = requestTool.name const summary = requestTool.summary || '-' const description = requestTool.description const websiteURL = requestTool.websiteURL const pricing = requestTool.pricing const appStoreURL = requestTool.appStoreURL const playStoreURL = requestTool.playStoreURL const possibleUseCase = requestTool.possibleUseCase const imageURL = requestTool.imageURL const tags = requestTool.tags await setToolsOccurrences() const slug = slugger.slug(name) const insertedTool = await prisma.tools.create( { data: { name, slug, description, summary, websiteURL, appStoreURL, playStoreURL, featuredAt: new Date().toISOString(), pricing, userId: session.user.id, isToolPublished: false, tags: { connect: tags.map((tagId) => ({ tagId })) }, imageURL, possibleUseCase, } } ) const toolDetails = await prisma.tools.findUnique({ where: { toolId: insertedTool.toolId }, include: { tags: true, user: true } }) return new NextResponse(JSON.stringify(toolDetails), { status: 201 }) } catch (error) { console.log(error) return new NextResponse(JSON.stringify({ error }), { status: 500 }) } }
import React from "react"; import { Outlet } from "react-router-dom"; import Dashboard from "../dashboard/Dashboard"; import Header from "../header/Header"; import SideBar from "../Sidebar/SideBar"; import style from "./style.module.scss"; import { Navigate } from "react-router-dom"; import { useSelector } from "react-redux"; const Home = () => { const { user: currentUser } = useSelector((state) => state.auth); if (!currentUser) { return <Navigate to="/login" />; } return ( <div className={style.parent}> <SideBar /> <div className={style.hoc}> <Header /> <main className={style.content_box}> <Outlet /> </main> </div> </div> ); }; export default Home;
const fs = require('fs'); const uid = require('uid'); const readFile = require('node:fs/promises').readFile; const writeFile = require('node:fs/promises').writeFile; // reading from json file const readData = async (path) => { try { const data = await readFile(path, 'utf8'); // console.log(data); if (!data || data === undefined || data === null) { console.log('file is empty'); return []; } // console.log(JSON.parse(data), ' from file'); const result = JSON.parse(data); return result; } catch (e) { console.log(e); } }; // adding data to json file const addData = async (path, data) => { const newData = { id: uid.uid(8), name: data.name, age: data.age, }; // reading data from the file try { const initialContent = await readData(path); // console.log(initialContent, ' initial content'); initialContent.push(newData); const newContentData = JSON.stringify(initialContent); await writeFile(path, newContentData, 'utf-8'); const newStudent = readData(path).catch((e) => { throw new Error(e); }); return newStudent; } catch (e) { throw new Error(e); } }; // getting student by id const getById = async (path, id) => { try { const students = await readData(path); if (students.length < 1) { return null; } const studentData = students.find((student) => student.id === id); if (!studentData) { return null; } return studentData; } catch (e) { throw new Error(e); } }; // updating student info const updateStudentInfo = async (path, id, update) => { try { const students = await readData(path); if (students.length < 1) { return null; } const student = await getById(path, id); if (student === null) { return null; } const newInfo = { ...student, name: update.name, age: update.age }; console.log(newInfo, ' new info '); // updating the file const studentList = students.filter((student) => student.id !== id); studentList.push(newInfo); console.log(studentList, 'student list'); const newContentData = JSON.stringify(studentList); await writeFile(path, newContentData, 'utf-8'); const updatedStudent = await getById(path, id); if (updatedStudent === null) { return null; } return updatedStudent; } catch (e) { throw new Error(e); } }; // deleting a specific student info const deleteInfo = async (path, id) => { try { const student = await getById(path, id); if (student === null) { return null; } const students = await readData(path); if (students.length < 1) { return null; } const newStudentList = students.filter((student) => student.id !== id); const newContentData = JSON.stringify(newStudentList); await writeFile(path, newContentData, 'utf-8'); const newStudent = readData(path).catch((e) => { throw new Error(e); }); return newStudent; } catch (e) { throw new Error(e); } }; module.exports = { addData, readData, getById, updateStudentInfo, deleteInfo };
#pragma once #include "ECS/ECS.hpp" #include "Util/Profiler.hpp" #include "ECS/Component/RenderingComponent/AlphaTestComponent.hpp" #include "ECS/Component/RenderingComponent/PhongShaderComponent.hpp" #include "ECS/Component/RenderingComponent/MeshComponent.hpp" #include "ECS/Component/RenderingComponent/OpaqueComponent.hpp" #include "ECS/Component/CameraComponent/OrthoCameraComponent.hpp" #include "ECS/Component/CameraComponent/ShadowCameraComponent.hpp" #include "ECS/Component/SpatialComponent/SpatialComponent.hpp" #include "ECS/Component/RenderingComponent/MaterialComponent.hpp" #include "ECS/Component/CollisionComponent/CameraCulledComponent.hpp" #include "ECS/Component/CameraComponent/OrthoCameraComponent.hpp" #include "ECS/Component/LightComponent/MainLightComponent.hpp" #include "ECS/Component/LightComponent/LightComponent.hpp" #include "ECS/Component/LightComponent/DirectionalLightComponent.hpp" #include "ECS/Component/LightComponent/PointLightComponent.hpp" #include "Renderer/GLObjects/SourceShader.hpp" #include "Renderer/GLObjects/ResolvedShaderInstance.hpp" namespace neo { template<typename... CompTs> void drawPhong(const ECS& ecs, const ECS::Entity cameraEntity, const Texture* shadowMap = nullptr, const ShaderDefines& inDefines = {}) { TRACY_GPU(); SourceShader* shader = Library::createSourceShader("Phong Shader", SourceShader::ConstructionArgs{ { ShaderStage::VERTEX, "model.vert"}, { ShaderStage::FRAGMENT, "phong.frag" } } ); ShaderDefines passDefines(inDefines); bool containsAlphaTest = false; MakeDefine(ALPHA_TEST); if constexpr ((std::is_same_v<AlphaTestComponent, CompTs> || ...)) { containsAlphaTest = true; passDefines.set(ALPHA_TEST); // Transparency sorting..for later // glEnable(GL_BLEND); // ecs.sort<AlphaTestComponent>([&cameraSpatial, &ecs](ECS::Entity entityLeft, ECS::Entity entityRight) { // auto leftSpatial = ecs.cGetComponent<SpatialComponent>(entityLeft); // auto rightSpatial = ecs.cGetComponent<SpatialComponent>(entityRight); // if (leftSpatial && rightSpatial) { // return glm::distance(cameraSpatial->getPosition(), leftSpatial->getPosition()) < glm::distance(cameraSpatial->getPosition(), rightSpatial->getPosition()); // } // return false; // }); } const glm::mat4 P = ecs.cGetComponentAs<CameraComponent, PerspectiveCameraComponent>(cameraEntity)->getProj(); const auto& cameraSpatial = ecs.cGetComponent<SpatialComponent>(cameraEntity); auto&& [lightEntity, _lightLight, light, lightSpatial] = *ecs.getSingleView<MainLightComponent, LightComponent, SpatialComponent>(); glm::mat4 L; const auto shadowCamera = ecs.getSingleView<ShadowCameraComponent, OrthoCameraComponent, SpatialComponent>(); const bool shadowsEnabled = shadowMap && shadowCamera.has_value(); MakeDefine(ENABLE_SHADOWS); if (shadowsEnabled) { passDefines.set(ENABLE_SHADOWS); const auto& [_, __, shadowOrtho, shadowCameraSpatial] = *shadowCamera; static glm::mat4 biasMatrix( 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f); L = biasMatrix * shadowOrtho.getProj() * shadowCameraSpatial.getView(); } bool directionalLight = ecs.has<DirectionalLightComponent>(lightEntity); bool pointLight = ecs.has<PointLightComponent>(lightEntity); glm::vec3 attenuation(0.f); MakeDefine(DIRECTIONAL_LIGHT); MakeDefine(POINT_LIGHT); if (directionalLight) { passDefines.set(DIRECTIONAL_LIGHT); } else if (pointLight) { attenuation = ecs.cGetComponent<PointLightComponent>(lightEntity)->mAttenuation; passDefines.set(POINT_LIGHT); } else { NEO_FAIL("Phong light needs a directional or point light component"); } ShaderDefines drawDefines(passDefines); const auto& view = ecs.getView<const PhongShaderComponent, const MeshComponent, const MaterialComponent, const SpatialComponent, const CompTs...>(); for (auto entity : view) { // VFC if (auto* culled = ecs.cGetComponent<CameraCulledComponent>(entity)) { if (!culled->isInView(ecs, entity, cameraEntity)) { continue; } } if (containsAlphaTest) { NEO_ASSERT(!ecs.has<OpaqueComponent>(entity), "Entity has opaque and alpha test component?"); } drawDefines.reset(); const auto& material = view.get<const MaterialComponent>(entity); MakeDefine(ALBEDO_MAP); MakeDefine(NORMAL_MAP); if (material.mAlbedoMap) { drawDefines.set(ALBEDO_MAP); } if (material.mNormalMap) { drawDefines.set(NORMAL_MAP); } auto& resolvedShader = shader->getResolvedInstance(drawDefines); resolvedShader.bind(); resolvedShader.bindUniform("albedo", material.mAlbedoColor); if (material.mAlbedoMap) { resolvedShader.bindTexture("albedoMap", *material.mAlbedoMap); } if (material.mNormalMap) { resolvedShader.bindTexture("normalMap", *material.mNormalMap); } // UBO candidates { resolvedShader.bindUniform("P", P); resolvedShader.bindUniform("V", cameraSpatial->getView()); resolvedShader.bindUniform("camPos", cameraSpatial->getPosition()); resolvedShader.bindUniform("lightCol", light.mColor); if (directionalLight || shadowsEnabled) { resolvedShader.bindUniform("lightDir", -lightSpatial.getLookDir()); } if (pointLight) { resolvedShader.bindUniform("lightPos", lightSpatial.getPosition()); resolvedShader.bindUniform("lightAtt", attenuation); } if (shadowsEnabled) { resolvedShader.bindUniform("L", L); resolvedShader.bindTexture("shadowMap", *shadowMap); } } const auto& drawSpatial = view.get<const SpatialComponent>(entity); resolvedShader.bindUniform("M", drawSpatial.getModelMatrix()); resolvedShader.bindUniform("N", drawSpatial.getNormalMatrix()); view.get<const MeshComponent>(entity).mMesh->draw(); } if (containsAlphaTest) { // glDisable(GL_BLEND); } } }
/* ISC License Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <string.h> #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #include <math.h> #include "fswAlgorithms/attGuidance/celestialTwoBodyPoint/celestialTwoBodyPoint.h" #include "architecture/utilities/linearAlgebra.h" #include "architecture/utilities/rigidBodyKinematics.h" #include "architecture/utilities/macroDefinitions.h" /*! This method initializes the configData for the nominal delta-V maneuver guidance. It checks to ensure that the inputs are sane and then creates the output message @return void @param configData The configuration data associated with the celestial body guidance @param moduleID The ID associated with the configData */ void SelfInit_celestialTwoBodyPoint(celestialTwoBodyPointConfig *configData, int64_t moduleID) { AttRefMsg_C_init(&configData->attRefOutMsg); return; } void Reset_celestialTwoBodyPoint(celestialTwoBodyPointConfig *configData, uint64_t callTime, int64_t moduleID) { configData->secCelBodyIsLinked = EphemerisMsg_C_isLinked(&configData->secCelBodyInMsg); // check if required input messages have been included if (!NavTransMsg_C_isLinked(&configData->transNavInMsg)) { _bskLog(configData->bskLogger, BSK_ERROR, "Error: celestialTwoBodyPoint.transNavInMsg wasn't connected."); } if (!EphemerisMsg_C_isLinked(&configData->celBodyInMsg)) { _bskLog(configData->bskLogger, BSK_ERROR, "Error: celestialTwoBodyPoint.celBodyInMsg wasn't connected."); } return; } /*! This method takes the spacecraft and points a specified axis at a named celestial body specified in the configuration data. It generates the commanded attitude and assumes that the control errors are computed downstream. @return void @param configData The configuration data associated with the celestial body guidance @param callTime The clock time at which the function was called (nanoseconds) @param moduleID The ID associated with the configData */ void Update_celestialTwoBodyPoint(celestialTwoBodyPointConfig *configData, uint64_t callTime, int64_t moduleID) { /*! - Parse the input messages */ parseInputMessages(configData, moduleID); /*! - Compute the pointing requirements */ computeCelestialTwoBodyPoint(configData, callTime); /*! - Write the output message */ AttRefMsg_C_write(&configData->attRefOut, &configData->attRefOutMsg, moduleID, callTime); } /*! This method takes the navigation translational info as well as the spice data of the primary celestial body and, if applicable, the second one, and computes the relative state vectors necessary to create the restricted 2-body pointing reference frame. @return void @param configData The configuration data associated with the celestial body guidance @param moduleID The ID associated with the configData */ void parseInputMessages(celestialTwoBodyPointConfig *configData, int64_t moduleID) { NavTransMsgPayload navData; EphemerisMsgPayload primPlanet; EphemerisMsgPayload secPlanet; double R_P1B_N_hat[3]; /* Unit vector in the direction of r_P1 */ double R_P2B_N_hat[3]; /* Unit vector in the direction of r_P2 */ double platAngDiff; /* Angle between r_P1 and r_P2 */ double dotProduct; /* Temporary scalar variable */ // read input messages navData = NavTransMsg_C_read(&configData->transNavInMsg); primPlanet = EphemerisMsg_C_read(&configData->celBodyInMsg); v3Subtract(primPlanet.r_BdyZero_N, navData.r_BN_N, configData->R_P1B_N); v3Subtract(primPlanet.v_BdyZero_N, navData.v_BN_N, configData->v_P1B_N); v3SetZero(configData->a_P1B_N); /* accelerations of s/c relative to planets set to zero*/ v3SetZero(configData->a_P2B_N); if(configData->secCelBodyIsLinked) { secPlanet = EphemerisMsg_C_read(&configData->secCelBodyInMsg); /*! - Compute R_P2 and v_P2 */ v3Subtract(secPlanet.r_BdyZero_N, navData.r_BN_N, configData->R_P2B_N); v3Subtract(secPlanet.v_BdyZero_N, navData.v_BN_N, configData->v_P2B_N); v3Normalize(configData->R_P1B_N, R_P1B_N_hat); v3Normalize(configData->R_P2B_N, R_P2B_N_hat); dotProduct = v3Dot(R_P2B_N_hat, R_P1B_N_hat); platAngDiff = safeAcos(dotProduct); } /*! - Cross the P1 states to get R_P2, v_p2 and a_P2 */ if(!configData->secCelBodyIsLinked || fabs(platAngDiff) < configData->singularityThresh || fabs(platAngDiff) > M_PI - configData->singularityThresh) { v3Cross(configData->R_P1B_N, configData->v_P1B_N, configData->R_P2B_N); v3Cross(configData->R_P1B_N, configData->a_P1B_N, configData->v_P2B_N); v3Cross(configData->v_P1B_N, configData->a_P1B_N, configData->a_P2B_N); } } /*! This method takes the spacecraft and points a specified axis at a named celestial body specified in the configuration data. It generates the commanded attitude and assumes that the control errors are computed downstream. @return void @param configData The configuration data associated with the celestial body guidance @param callTime The clock time at which the function was called (nanoseconds) */ void computeCelestialTwoBodyPoint(celestialTwoBodyPointConfig *configData, uint64_t callTime) { double temp3[3]; /* Temporary vector */ double temp3_1[3]; /* Temporary vector 1 */ double temp3_2[3]; /* Temporary vector 2 */ double temp3_3[3]; /* Temporary vector 3 */ double temp33[3][3]; /* Temporary 3x3 matrix */ double temp33_1[3][3]; /* Temporary 3x3 matrix 1 */ double temp33_2[3][3]; /* Temporary 3x3 matrix 2 */ double R_N[3]; /* Normal vector of the plane defined by R_P1 and R_P2 */ double v_N[3]; /* First time-derivative of R_n */ double a_N[3]; /* Second time-derivative of R_n */ double dcm_RN[3][3]; /* DCM that maps from Reference frame to the inertial */ double r1_hat[3]; /* 1st row vector of RN */ double r2_hat[3]; /* 2nd row vector of RN */ double r3_hat[3]; /* 3rd row vector of RN */ double dr1_hat[3]; /* r1_hat first time-derivative */ double dr2_hat[3]; /* r2_hat first time-derivative */ double dr3_hat[3]; /* r3_hat first time-derivative */ double I_33[3][3]; /* Identity 3x3 matrix */ double C1[3][3]; /* DCM used in the computation of rates and acceleration */ double C3[3][3]; /* DCM used in the computation of rates and acceleration */ double omega_RN_R[3]; /* Angular rate of the reference frame wrt the inertial in ref R-frame components */ double domega_RN_R[3]; /* Angular acceleration of the reference frame wrt the inertial in ref R-frame components */ double ddr1_hat[3]; /* r1_hat second time-derivative */ double ddr2_hat[3]; /* r2_hat second time-derivative */ double ddr3_hat[3]; /* r3_hat second time-derivative */ configData->attRefOut = AttRefMsg_C_zeroMsgPayload(); /* - Initial computations: R_n, v_n, a_n */ v3Cross(configData->R_P1B_N, configData->R_P2B_N, R_N); v3Cross(configData->v_P1B_N, configData->R_P2B_N, temp3_1); v3Cross(configData->R_P1B_N, configData->v_P2B_N, temp3_2); v3Add(temp3_1, temp3_2, v_N); /*Eq 4 */ v3Cross(configData->a_P1B_N, configData->R_P2B_N, temp3_1); v3Cross(configData->R_P1B_N, configData->a_P2B_N, temp3_2); v3Add(temp3_1, temp3_2, temp3_3); v3Cross(configData->v_P1B_N, configData->v_P2B_N, temp3); v3Scale(2.0, temp3, temp3); v3Add(temp3, temp3_3, a_N); /*Eq 5*/ /* - Reference Frame computation */ v3Normalize(configData->R_P1B_N, r1_hat); /* Eq 9a*/ v3Normalize(R_N, r3_hat); /* Eq 9c */ v3Cross(r3_hat, r1_hat, r2_hat); /* Eq 9b */ v3Normalize(r2_hat, r2_hat); v3Copy(r1_hat, dcm_RN[0]); v3Copy(r2_hat, dcm_RN[1]); v3Copy(r3_hat, dcm_RN[2]); C2MRP(dcm_RN, configData->attRefOut.sigma_RN); /* - Reference base-vectors first time-derivative */ m33SetIdentity(I_33); v3OuterProduct(r1_hat, r1_hat, temp33); m33Subtract(I_33, temp33, C1); m33MultV3(C1, configData->v_P1B_N, temp3); v3Scale(1.0 / v3Norm(configData->R_P1B_N), temp3, dr1_hat); /* Eq 11a*/ v3OuterProduct(r3_hat, r3_hat, temp33); m33Subtract(I_33, temp33, C3); m33MultV3(C3, v_N, temp3); v3Scale(1.0 / v3Norm(R_N), temp3, dr3_hat); /* Eq 11b*/ v3Cross(dr3_hat, r1_hat, temp3_1); v3Cross(r3_hat, dr1_hat, temp3_2); v3Add(temp3_1, temp3_2, dr2_hat); /* Eq 11c*/ /* - Angular velocity computation */ omega_RN_R[0] = v3Dot(r3_hat, dr2_hat); omega_RN_R[1]= v3Dot(r1_hat, dr3_hat); omega_RN_R[2] = v3Dot(r2_hat, dr1_hat); m33tMultV3(dcm_RN, omega_RN_R, configData->attRefOut.omega_RN_N); /* - Reference base-vectors second time-derivative */ m33MultV3(C1, configData->a_P1B_N, temp3_1); v3OuterProduct(dr1_hat, r1_hat, temp33_1); m33Scale(2.0, temp33_1, temp33_1); v3OuterProduct(r1_hat, dr1_hat, temp33_2); m33Add(temp33_1, temp33_2, temp33); m33MultV3(temp33, configData->v_P1B_N, temp3_2); v3Subtract(temp3_1, temp3_2, temp3); v3Scale(1.0 / v3Norm(configData->R_P1B_N), temp3, ddr1_hat); /* Eq 13a*/ m33MultV3(C3, a_N, temp3_1); v3OuterProduct(dr3_hat, r3_hat, temp33_1); m33Scale(2.0, temp33_1, temp33_1); v3OuterProduct(r3_hat, dr3_hat, temp33_2); m33Add(temp33_1, temp33_2, temp33); m33MultV3(temp33, v_N, temp3_2); v3Subtract(temp3_1, temp3_2, temp3); v3Scale(1.0 / v3Norm(R_N), temp3, ddr3_hat); /* Eq 13b*/ v3Cross(ddr3_hat, r1_hat, temp3_1); v3Cross(r3_hat, ddr1_hat, temp3_2); v3Add(temp3_1, temp3_2, temp3_3); v3Cross(dr3_hat, dr1_hat, temp3); v3Scale(2.0, temp3, temp3); v3Add(temp3, temp3_3, ddr2_hat); /* Eq 13c*/ /* - Angular acceleration computation */ domega_RN_R[0] = v3Dot(dr3_hat, dr2_hat) + v3Dot(r3_hat, ddr2_hat) - v3Dot(omega_RN_R, dr1_hat); domega_RN_R[1] = v3Dot(dr1_hat, dr3_hat) + v3Dot(r1_hat, ddr3_hat) - v3Dot(omega_RN_R, dr2_hat); domega_RN_R[2] = v3Dot(dr2_hat, dr1_hat) + v3Dot(r2_hat, ddr1_hat) - v3Dot(omega_RN_R, dr3_hat); m33tMultV3(dcm_RN, domega_RN_R, configData->attRefOut.domega_RN_N); return; }
def merge_sort(arr): if len(arr) > 1: mid = len(arr)//2 left_half = arr[:mid] right_half = arr[mid:] merge_sort(left_half) merge_sort(right_half) i, j, k = 0, 0, 0 while i < len(left_half) and j < len(right_half): if left_half[i] < right_half[j]: arr[k] = left_half[i] i += 1 else: arr[k] = right_half[j] j += 1 k += 1 while i < len(left_half): arr[k] = left_half[i] i += 1 k += 1 while j < len(right_half): arr[k] = right_half[j] j += 1 k += 1 def print_list(arr): for i in range(len(arr)): print(arr[i], end=" ") print() # Example usage: if __name__ == "__main__": arr = [12, 11, 13, 5, 6, 7] print("Original array:", arr) merge_sort(arr) print("Sorted array:", arr)
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\PostController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/',[PostController::class,'index'])->name('post.index'); Route::get('/post-read',[PostController::class,'read'])->name('post.read'); Route::get('/post-create',[PostController::class,'create'])->name('post.create'); Route::post('/post-store',[PostController::class,'store'])->name('post.store'); Route::get('/post-show/{id}',[PostController::class,'show'])->name('post.show'); Route::delete('/post-delete/{id}',[PostController::class,'delete'])->name('post.delete'); Route::get('/post-edit/{id}',[PostController::class,'edit'])->name('post.edit'); Route::put('/post-update/{id}',[PostController::class,'update'])->name('post.update'); Route::get('/users',[\App\Http\Controllers\UserController::class,'index']);
import styled from '@emotion/styled'; import { FunctionComponent, ReactNode } from 'react'; import { Color } from './tokens/colors' import { OutsideClick } from './utils/outside-click'; import { Wrapper } from './wrapper'; import { Box } from './box'; interface OverlayProps { title: string; description: string; children: ReactNode; onOutsideClick: () => void; } const StyledContainer = styled.div` position: fixed; top: 0; left: 0; bottom: 0; right: 0; z-index: 50; display: flex; justify-content: center; align-items: center; background: ${Color.Shadow}; `; export const Overlay: FunctionComponent<OverlayProps> = props => { return ( <StyledContainer> <Wrapper> <OutsideClick onOutsideClick={props.onOutsideClick}> <Box title={props.title} description={props.description}> {props.children} </Box> </OutsideClick> </Wrapper> </StyledContainer> ) }
package com.beck.springbootebookaws.api.payload.book; import com.beck.springbootebookaws.db.enums.BookLanguage; import com.beck.springbootebookaws.db.enums.Genre; import com.beck.springbootebookaws.db.enums.RequestStatus; import com.beck.springbootebookaws.db.enums.TypeOfBook; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonNaming; import lombok.*; @Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) public class BookRequest { private String image; private String title; private String author; private String publishingHouse; private String aboutTheBook; private String bookFragment; private BookLanguage bookLanguage; private int yearOfIssue; private int pageVolume; private double price; private int amountOfBooks; private int discount; private Boolean bestseller; private String audioBookFragment; private String eBookFragment; private String paperBookFragment; private RequestStatus status; private String comments; private Genre genreEnum; private TypeOfBook typeOfBook; private Double basketPrice; }
import React from 'react'; import Stack from '@mui/material/Stack'; import { ComponentMeta, ComponentStory } from '@storybook/react'; import ToggleButtonComp from './mui/ToggleButton'; export default { title: 'Pano/ToggleButtonComp', component: ToggleButtonComp, } as ComponentMeta<typeof ToggleButtonComp>; const Template: ComponentStory<typeof ToggleButtonComp> = (args) => <ToggleButtonComp {...args} />; const options = [ { label: 'one', value: '1', }, { label: 'two', value: '2', }, { label: 'three', value: '3', }, { label: 'four', value: '4', }, { label: 'five', value: '5', }, { label: 'six', value: '6', }, ]; export const Playground = Template.bind({}); Playground.args = { options, orientation: 'horizontal', }; export const orientation: ComponentStory<typeof ToggleButtonComp> = () => ( <Stack spacing={4} maxWidth={300}> <ToggleButtonComp orientation='horizontal' options={options} /> <ToggleButtonComp orientation='vertical' options={options} /> </Stack> );
package com.vogulev.list_randomizing_telegram_bot.service; import com.vogulev.list_randomizing_telegram_bot.entity.PbClient; import com.vogulev.list_randomizing_telegram_bot.entity.PbUser; import com.vogulev.list_randomizing_telegram_bot.repository.NamesRepository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import java.util.List; import java.util.stream.Collectors; @Slf4j @Service @RequiredArgsConstructor public class CommandService { private final NamesRepository namesRepository; private final ShuffleService shuffleService; private final ClientService clientService; private boolean isSaveUserCmd = false; private boolean isDeleteCmd = false; @Value("#{'${bot.admins}'.split(',')}") private List<String> admins; protected String startCmdReceived(Long chatId, String name) { var pbClientOpt = clientService.get(chatId); if (pbClientOpt.isEmpty()) { clientService.save(chatId, name); return "Привет, " + name + "!\n" + "Это бот для выбора порядка выступления на Daily, созданный инициативным парнем ;-)\n" + "Он присылает список в 9:45 по МСК каждый день за исключением выходных!\n" + "Кстати, вы уже автоматически подписаны на утреннюю рассылку!\n" + "Желаю хорошего и продуктивного дня! :-*"; } var pbClient = pbClientOpt.get(); if (pbClient.getActive()) { return "Вы и так уже подписаны на ежедневную рассылку в ЛС"; } pbClient.setActive(true); clientService.save(pbClient); return "Вы снова подписались на ежедневную рассылку в ЛС"; } protected String listCmdReceived() { var allUsers = namesRepository.findAll(); if (allUsers.isEmpty()) { return "Нет добавленных сотрудников, если вы администратор - воспользуйся командой \"/add\"\n\n"; } var allUsersStr = allUsers.stream() .map(PbUser::getName) .map(Object::toString) .collect(Collectors.joining("\n")); return "Список всех сотрудников:\n\n" + allUsersStr; } protected String shuffleCmdReceived() { var users = namesRepository.findAll(); return shuffleService.shuffle(users); } protected String delCmdReceived(Update update) { if (admins.contains(update.getMessage().getFrom().getUserName())) { isDeleteCmd = true; return "Введите имя сотрудника для удаления его из списка"; } return "Вы не являетесь администратором бота"; } protected String addCmdReceived(Update update) { if (admins.contains(update.getMessage().getFrom().getUserName())) { isSaveUserCmd = true; return "Введите имя сотрудника для добавления его в список"; } return "Вы не являетесь администратором бота"; } protected String unsubscribeCmdReceived(long chatId, String firstName) { PbClient pbClient; try { pbClient = clientService.get(chatId) .orElseThrow(() -> new TelegramApiRequestException("Не удалось получить пользователя")); } catch (TelegramApiRequestException e) { throw new RuntimeException(e); } if (pbClient.getActive()) { pbClient.setActive(false); clientService.save(pbClient); return firstName + " вы успешно отписались от назойливой рассылки по утрам, " + "теперь сообщение можно увидеть только в группе PB!"; } return firstName + " вы и так уже отписаны от получения сообщений в ЛС!"; } protected String unknownCmdReceived(Update update, String messageText) { String answer; if (isSaveUserCmd && update.hasMessage() && update.getMessage().hasText()) { try { var pbUser = new PbUser(); pbUser.setName(messageText); namesRepository.save(pbUser); answer = "Вы добавили сотрудника " + messageText; } catch (DataIntegrityViolationException ex) { log.error(ex.getMessage()); answer = "Ошибка сохранения сотрудника: возможно такое имя уже присутствует в списке"; } finally { isSaveUserCmd = false; } } else if (isDeleteCmd && update.hasMessage() && update.getMessage().hasText()) { var isDeleted = namesRepository.deletePbUserByName(messageText); if (isDeleted == 1) { answer = "Вы успешно удалили сотрудника " + messageText; } else { answer = "Сотрудник с именем " + messageText + " не найден!"; } isDeleteCmd = false; } else { answer = "Не знаю такой команды, попробуйте выбрать нужное действие"; } return answer; } }
--- title: "taskScope vars in callee" date: 2020-10-07T00:11:18+1010:00 draft: false weight: 1190 --- ##### This is a test case to show that the taskScope var could be passed to callee task and it will override what has been defined in callee if the var name is same ### Demo [source](https://github.com/upcmd/up/blob/master/tests/functests/c0109.yml) ##### Main task yaml file ``` vars: tom: this is tom tasks: - name: task task: - func: cmd dvars: - name: jerry value: this is jerry in task scope flags: - taskScope do: - name: print desc: this should print out the dvar value of jerry cmd: '{{.jerry}}' - func: call do: - subtask1 - name: subtask1 task: - func: cmd do: - name: print desc: this should print out the dvar value of jerry as it is declared jerry is in taskScope cmd: '{{.jerry}}' - name: trace cmd: ===> - func: cmd vars: jerry: jerry is overriden in local scope do: - name: print desc: | remember that the caller's vars should override callee's vars so jerry's value should the one from caller instead this local value cmd: '{{.jerry}}' - name: trace cmd: <=== - name: trace cmd: '--->' - func: cmd do: - name: print desc: this should print out the jerry defined in caller's task var scope cmd: '{{.jerry}}' - name: trace cmd: <--- ``` ##### Main log file ``` loading [Config]: ./tests/functests/upconfig.yml Main config: Version -> 1.0.0 RefDir -> ./tests/functests WorkDir -> cwd AbsWorkDir -> /up_project/up TaskFile -> c0109 Verbose -> vvv ModuleName -> self ShellType -> /bin/sh MaxCallLayers -> 8 Timeout -> 3600000 MaxModuelCallLayers -> 256 EntryTask -> task ModRepoUsernameRef -> ModRepoPasswordRef -> work dir: /up_project/up -exec task: task loading [Task]: ./tests/functests/c0109 module: [self], instance id: [dev], exec profile: [] profile - envVars: (*core.Cache)({ }) Task1: [task ==> task: ] -Step1: self: final context exec vars: (*core.Cache)({ "tom": "this is tom", "up_runtime_task_layer_number": 0, "jerry": "this is jerry in task scope" }) ~SubStep1: [print: this should print out the dvar value of jerry ] this is jerry in task scope -Step2: self: final context exec vars: (*core.Cache)({ "tom": "this is tom", "up_runtime_task_layer_number": 0, "jerry": "this is jerry in task scope" }) =Task2: [task ==> subtask1: ] --Step1: self: final context exec vars: (*core.Cache)({ "jerry": "this is jerry in task scope", "tom": "this is tom", "up_runtime_task_layer_number": 1 }) ~~SubStep1: [print: this should print out the dvar value of jerry as it is declared jerry is in taskScope ] this is jerry in task scope ~~SubStep2: [trace: ] Trace:===> --Step2: self: final context exec vars: (*core.Cache)({ "jerry": "this is jerry in task scope", "tom": "this is tom", "up_runtime_task_layer_number": 1 }) ~~SubStep1: [print: remember that the caller's vars should override callee's vars so jerry's value should the one from caller instead this local value ] this is jerry in task scope ~~SubStep2: [trace: ] Trace:<=== ~~SubStep3: [trace: ] Trace:---> --Step3: self: final context exec vars: (*core.Cache)({ "up_runtime_task_layer_number": 1, "jerry": "this is jerry in task scope", "tom": "this is tom" }) ~~SubStep1: [print: this should print out the jerry defined in caller's task var scope ] this is jerry in task scope ~~SubStep2: [trace: ] Trace:<--- ``` ##### Logs with different verbose level * [c0109 log - verbose level v](../../logs/c0109_v) * [c0109 log - verbose level vv](../../logs/c0109_vv) * [c0109 log - verbose level vvv](../../logs/c0109_vvvv) * [c0109 log - verbose level vvvv](../../logs/c0109_vvvv) * [c0109 log - verbose level vvvvv](../../logs/c0109_vvvvv) ##### Raw logs with different verbose level * [c0109 raw log - verbose level v](../../reflogs/c0109_v.log) * [c0109 raw log - verbose level vv](../../reflogs/c0109_vv.log) * [c0109 raw log - verbose level vvv](../../reflogs/c0109_vvv.log) * [c0109 raw log - verbose level vvvv](../../reflogs/c0109_vvvv.log) * [c0109 raw log - verbose level vvvvv](../../reflogs/c0109_vvvvv.log)
use std::fmt::Debug; use std::fs::File; use std::io::{BufRead, BufReader}; use std::iter::Flatten; use std::path::Path; use std::str::FromStr; pub fn read_lines<T: AsRef<Path>>(filename: T) -> Flatten<std::io::Lines<BufReader<File>>> { let file = File::open(filename).unwrap(); BufReader::new(file).lines().flatten() } /// Creates an iterator that iterates over the parsed values in a string. /// String is split using 'pattern', and the first 'skip' values are skipped /// before parsing. pub fn string_to_iter<'a, T>( string: &'a str, pattern: &'a str, skip: usize, ) -> impl Iterator<Item = T> + 'a where T: FromStr, <T as FromStr>::Err: Debug, { string .split(pattern) .filter(|c| !c.is_empty()) .skip(skip) .map(|c| { c.parse() .unwrap_or_else(|_| panic!("Could not parse string: {:?}", c)) }) } /// Creates a vector that contains the parsed values in a string. /// String is split using 'pattern', and the first 'skip' values are skipped /// before parsing. pub fn string_to_array<T>(string: &str, pattern: &str, skip: usize) -> Vec<T> where T: FromStr, <T as FromStr>::Err: Debug, { string_to_iter(string, pattern, skip).collect() }
/* -*- C++ -*- */ /** * @file Dirent_Selector.h * * Dirent_Selector.h,v 4.8 2003/11/01 11:15:12 dhinton Exp * * Define a portable C++ interface to the <ACE_OS_Dirent::scandir> method. * * @author Rich Newman <RNewman@directv.com> */ #ifndef ACE_DIRENT_SELECTOR_H #define ACE_DIRENT_SELECTOR_H #include /**/ "ace/pre.h" #include "ace/ACE_export.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) #pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #include "ace/os_include/os_dirent.h" /** * @class ACE_Dirent_Selector * * @brief Define a portable C++ directory-entry iterator based on the * POSIX scandir API. */ class ACE_Export ACE_Dirent_Selector { public: /// Constructor ACE_Dirent_Selector (void); /// Destructor. virtual ~ACE_Dirent_Selector (void); /// Return the length of the list of matching directory entries. int length (void) const; /// Return the entry at @a index. dirent *operator[] (const int index) const; /// Free up resources. int close (void); /// Open the directory @a dir and populate the <namelist_> array with /// directory entries that match the @a selector and @a comparator. int open (const ACE_TCHAR *dir, int (*selector)(const dirent *d) = 0, int (*comparator)(const dirent **d1, const dirent **d2) = 0); protected: /// Ptr to the namelist array. dirent **namelist_; /// # of entries in the array. int n_; }; #if defined (__ACE_INLINE__) #include "ace/Dirent_Selector.inl" #endif /* __ACE_INLINE__ */ #include /**/ "ace/post.h" #endif /* ACE_DIRENT_SELECTOR_H */
package com.jgitfx.base.dialogs; import java.util.List; import org.eclipse.jgit.api.CheckoutCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.Ref; import org.reactfx.value.Val; /** * A base class RevertChangesDialog class that handles most of the JGit code needed to revert tracked modified files * back to their previous states in the most recent commit. * * <p>Note: the result converter is not set in this class and leaves that up to subclasses. However, * the result converter should follow something along these lines:</p> * <pre> * {@code * RevertChangesDialog dialog = // creation code; * dialog.setResultConverter(buttonType -> { * if (buttonType.equals(revertButtonType) { * return dialog.revertChanges(); * } else { * return null; * } * } * } * </pre> * * @param <R> * @param <P> */ public abstract class RevertChangesDialogBase<R, P extends RevertChangesDialogPaneBase> extends GitDialog<R, P> { private final Val<Git> git; protected final Git getGitOrThrow() {return git.getOrThrow(); } public RevertChangesDialogBase(Val<Git> git) { super(); this.git = git; } /** * Reverts the selected files back to their previous state in the most recent commit * @return whatever {@link #createResult(Ref)} returns or null if a {@link GitAPIException} was thrown. */ public final R revertChanges() { CheckoutCommand checkout = getGitOrThrow().checkout(); List<String> selectedFiles = getDialogPane().getSelectedFiles(); selectedFiles.forEach(checkout::addPath); try { Ref ref = checkout.call(); return createResult(ref); } catch (GitAPIException e) { e.printStackTrace(); return null; } } /** * Optional method that creates the result using the result of the {@link CheckoutCommand}. * Note: {@link #getDialogPane()} can be used to get more arguments if need be. * @param ref the returned result of the {@link CheckoutCommand}. * @return the created result */ protected abstract R createResult(Ref ref); /** * If a {@link GitAPIException} is thrown, a developer can handle it here. Defaults to printing out stacktrace. * @param e the exception that might be thrown from {@link #revertChanges()} */ protected void handleGitAPIException(GitAPIException e) { e.printStackTrace(); } }
package main //BU kod Udemy Cihan Özhan Golang kursundan alntılanmıştır. import ( "fmt" "strconv" ) func CarExecute(c Carface) { fmt.Print("\n") fmt.Println("Araç Bilgisi : \n" + c.Information()) fmt.Print("\n") msg := "" isRun := c.Run() if isRun { msg = "Calismiyor" } else { msg = "Calisiyor" } fmt.Println("Arac " + msg + ".") isStop := c.Stop() if isStop { msg = "Durdu" } else { msg = "Duramadi fren tutmuyor" } fmt.Println("Arac " + msg + ".") } func main() { ferr := new(Ferrari) ferr.Brand = "Ferrari" ferr.Model = "F50" ferr.Color = "Red" ferr.Speed = 340 ferr.Price = 1 ferr.Special = true fmt.Println(ferr.Information()) merc := new(Mercedes) merc.Brand = "Mercedes" merc.Model = "CLX" merc.Color = "Black" merc.Speed = 290 merc.Price = 2 fmt.Println(merc.Information()) //CarExecute CarExecute(ferr) CarExecute(merc) } // base strcuts type Car struct { Brand string Model string Color string Speed int Price float64 } //InterFace type Carface interface { Run() bool Stop() bool Information() string } type SpecialProduction struct { Special bool } type Ferrari struct { Car //composition SpecialProduction } func (_ Ferrari) Run() bool { return true } func (_ Ferrari) Stop() bool { return true } func (x *Ferrari) Information() string { ret := "\t" + x.Brand + " " + x.Model + "\n" + "\t" + "Color: " + x.Color + "\t" + "Speed: " + strconv.Itoa(x.Speed) + "\n" + "\t" + "Price: " + strconv.Itoa(int(x.Price)) + "Million" add := "Yes" if x.Special { ret += "\n" + "\t" + "Special : " + add } return ret } // Lambo type Lambo struct { Car //composition SpecialProduction } func (_ Lambo) Run() bool { return true } func (_ Lambo) Stop() bool { return true } func (x *Lambo) Information() string { ret := "\t" + x.Brand + " " + x.Model + "\n" + "\t" + "Color: " + x.Color + "\t" + "Speed: " + strconv.Itoa(x.Speed) + "\n" + "\t" + "Price: " + strconv.Itoa(int(x.Price)) + "Million" add := "Yes" if x.Special { ret += "\n" + "\t" + "Special : " + add } return ret } // Mercedes type Mercedes struct { Car //composition SpecialProduction } func (_ Mercedes) Run() bool { return true } func (_ Mercedes) Stop() bool { return true } func (x *Mercedes) Information() string { ret := "\t" + x.Brand + " " + x.Model + "\n" + "\t" + "Color: " + x.Color + "\t" + "Speed: " + strconv.Itoa(x.Speed) + "\n" + "\t" + "Price: " + strconv.Itoa(int(x.Price)) + "Million" return ret }
#define private public #include "directory.h" #undef private #define protected public #include "orch.h" #undef protected #include "ut_helper.h" #include "mock_orchagent_main.h" #include "mock_sai_api.h" #include "mock_orch_test.h" #include "gtest/gtest.h" #include <string> EXTERN_MOCK_FNS namespace mux_rollback_test { DEFINE_SAI_API_MOCK(neighbor); DEFINE_SAI_API_MOCK(route); DEFINE_SAI_GENERIC_API_MOCK(acl, acl_entry); DEFINE_SAI_GENERIC_API_MOCK(next_hop, next_hop); using namespace std; using namespace mock_orch_test; using ::testing::Return; using ::testing::Throw; static const string TEST_INTERFACE = "Ethernet4"; class MuxRollbackTest : public MockOrchTest { protected: void SetMuxStateFromAppDb(std::string state) { Table mux_cable_table = Table(m_app_db.get(), APP_MUX_CABLE_TABLE_NAME); mux_cable_table.set(TEST_INTERFACE, { { STATE, state } }); m_MuxCableOrch->addExistingData(&mux_cable_table); static_cast<Orch *>(m_MuxCableOrch)->doTask(); } void SetAndAssertMuxState(std::string state) { m_MuxCable->setState(state); EXPECT_EQ(state, m_MuxCable->getState()); } void ApplyInitialConfigs() { Table peer_switch_table = Table(m_config_db.get(), CFG_PEER_SWITCH_TABLE_NAME); Table tunnel_table = Table(m_app_db.get(), APP_TUNNEL_DECAP_TABLE_NAME); Table mux_cable_table = Table(m_config_db.get(), CFG_MUX_CABLE_TABLE_NAME); Table port_table = Table(m_app_db.get(), APP_PORT_TABLE_NAME); Table vlan_table = Table(m_app_db.get(), APP_VLAN_TABLE_NAME); Table vlan_member_table = Table(m_app_db.get(), APP_VLAN_MEMBER_TABLE_NAME); Table neigh_table = Table(m_app_db.get(), APP_NEIGH_TABLE_NAME); Table intf_table = Table(m_app_db.get(), APP_INTF_TABLE_NAME); auto ports = ut_helper::getInitialSaiPorts(); port_table.set(TEST_INTERFACE, ports[TEST_INTERFACE]); port_table.set("PortConfigDone", { { "count", to_string(1) } }); port_table.set("PortInitDone", { {} }); neigh_table.set( VLAN_1000 + neigh_table.getTableNameSeparator() + SERVER_IP1, { { "neigh", "62:f9:65:10:2f:04" }, { "family", "IPv4" } }); vlan_table.set(VLAN_1000, { { "admin_status", "up" }, { "mtu", "9100" }, { "mac", "00:aa:bb:cc:dd:ee" } }); vlan_member_table.set( VLAN_1000 + vlan_member_table.getTableNameSeparator() + TEST_INTERFACE, { { "tagging_mode", "untagged" } }); intf_table.set(VLAN_1000, { { "grat_arp", "enabled" }, { "proxy_arp", "enabled" }, { "mac_addr", "00:00:00:00:00:00" } }); intf_table.set( VLAN_1000 + neigh_table.getTableNameSeparator() + "192.168.0.1/21", { { "scope", "global" }, { "family", "IPv4" }, }); tunnel_table.set(MUX_TUNNEL, { { "dscp_mode", "uniform" }, { "dst_ip", "2.2.2.2" }, { "ecn_mode", "copy_from_outer" }, { "encap_ecn_mode", "standard" }, { "ttl_mode", "pipe" }, { "tunnel_type", "IPINIP" } }); peer_switch_table.set(PEER_SWITCH_HOSTNAME, { { "address_ipv4", PEER_IPV4_ADDRESS } }); mux_cable_table.set(TEST_INTERFACE, { { "server_ipv4", SERVER_IP1 + "/32" }, { "server_ipv6", "a::a/128" }, { "state", "auto" } }); gPortsOrch->addExistingData(&port_table); gPortsOrch->addExistingData(&vlan_table); gPortsOrch->addExistingData(&vlan_member_table); static_cast<Orch *>(gPortsOrch)->doTask(); gIntfsOrch->addExistingData(&intf_table); static_cast<Orch *>(gIntfsOrch)->doTask(); m_TunnelDecapOrch->addExistingData(&tunnel_table); static_cast<Orch *>(m_TunnelDecapOrch)->doTask(); m_MuxOrch->addExistingData(&peer_switch_table); static_cast<Orch *>(m_MuxOrch)->doTask(); m_MuxOrch->addExistingData(&mux_cable_table); static_cast<Orch *>(m_MuxOrch)->doTask(); gNeighOrch->addExistingData(&neigh_table); static_cast<Orch *>(gNeighOrch)->doTask(); m_MuxCable = m_MuxOrch->getMuxCable(TEST_INTERFACE); // We always expect the mux to be initialized to standby EXPECT_EQ(STANDBY_STATE, m_MuxCable->getState()); } void PostSetUp() override { INIT_SAI_API_MOCK(neighbor); INIT_SAI_API_MOCK(route); INIT_SAI_API_MOCK(acl); INIT_SAI_API_MOCK(next_hop); MockSaiApis(); } void PreTearDown() override { RestoreSaiApis(); } }; TEST_F(MuxRollbackTest, StandbyToActiveNeighborAlreadyExists) { EXPECT_CALL(*mock_sai_neighbor_api, create_neighbor_entry) .WillOnce(Return(SAI_STATUS_ITEM_ALREADY_EXISTS)); SetAndAssertMuxState(ACTIVE_STATE); } TEST_F(MuxRollbackTest, ActiveToStandbyNeighborNotFound) { SetAndAssertMuxState(ACTIVE_STATE); EXPECT_CALL(*mock_sai_neighbor_api, remove_neighbor_entry) .WillOnce(Return(SAI_STATUS_ITEM_NOT_FOUND)); SetAndAssertMuxState(STANDBY_STATE); } TEST_F(MuxRollbackTest, StandbyToActiveRouteNotFound) { EXPECT_CALL(*mock_sai_route_api, remove_route_entry) .WillOnce(Return(SAI_STATUS_ITEM_NOT_FOUND)); SetAndAssertMuxState(ACTIVE_STATE); } TEST_F(MuxRollbackTest, ActiveToStandbyRouteAlreadyExists) { SetAndAssertMuxState(ACTIVE_STATE); EXPECT_CALL(*mock_sai_route_api, create_route_entry) .WillOnce(Return(SAI_STATUS_ITEM_ALREADY_EXISTS)); SetAndAssertMuxState(STANDBY_STATE); } TEST_F(MuxRollbackTest, StandbyToActiveAclNotFound) { EXPECT_CALL(*mock_sai_acl_api, remove_acl_entry) .WillOnce(Return(SAI_STATUS_ITEM_NOT_FOUND)); SetAndAssertMuxState(ACTIVE_STATE); } TEST_F(MuxRollbackTest, ActiveToStandbyAclAlreadyExists) { SetAndAssertMuxState(ACTIVE_STATE); EXPECT_CALL(*mock_sai_acl_api, create_acl_entry) .WillOnce(Return(SAI_STATUS_ITEM_ALREADY_EXISTS)); SetAndAssertMuxState(STANDBY_STATE); } TEST_F(MuxRollbackTest, StandbyToActiveNextHopAlreadyExists) { EXPECT_CALL(*mock_sai_next_hop_api, create_next_hop) .WillOnce(Return(SAI_STATUS_ITEM_ALREADY_EXISTS)); SetAndAssertMuxState(ACTIVE_STATE); } TEST_F(MuxRollbackTest, ActiveToStandbyNextHopNotFound) { SetAndAssertMuxState(ACTIVE_STATE); EXPECT_CALL(*mock_sai_next_hop_api, remove_next_hop) .WillOnce(Return(SAI_STATUS_ITEM_NOT_FOUND)); SetAndAssertMuxState(STANDBY_STATE); } TEST_F(MuxRollbackTest, StandbyToActiveRuntimeErrorRollbackToStandby) { EXPECT_CALL(*mock_sai_route_api, remove_route_entry) .WillOnce(Throw(runtime_error("Mock runtime error"))); SetMuxStateFromAppDb(ACTIVE_STATE); EXPECT_EQ(STANDBY_STATE, m_MuxCable->getState()); } TEST_F(MuxRollbackTest, ActiveToStandbyRuntimeErrorRollbackToActive) { SetAndAssertMuxState(ACTIVE_STATE); EXPECT_CALL(*mock_sai_route_api, create_route_entry) .WillOnce(Throw(runtime_error("Mock runtime error"))); SetMuxStateFromAppDb(STANDBY_STATE); EXPECT_EQ(ACTIVE_STATE, m_MuxCable->getState()); } TEST_F(MuxRollbackTest, StandbyToActiveLogicErrorRollbackToStandby) { EXPECT_CALL(*mock_sai_neighbor_api, create_neighbor_entry) .WillOnce(Throw(logic_error("Mock logic error"))); SetMuxStateFromAppDb(ACTIVE_STATE); EXPECT_EQ(STANDBY_STATE, m_MuxCable->getState()); } TEST_F(MuxRollbackTest, ActiveToStandbyLogicErrorRollbackToActive) { SetAndAssertMuxState(ACTIVE_STATE); EXPECT_CALL(*mock_sai_neighbor_api, remove_neighbor_entry) .WillOnce(Throw(logic_error("Mock logic error"))); SetMuxStateFromAppDb(STANDBY_STATE); EXPECT_EQ(ACTIVE_STATE, m_MuxCable->getState()); } TEST_F(MuxRollbackTest, StandbyToActiveExceptionRollbackToStandby) { EXPECT_CALL(*mock_sai_next_hop_api, create_next_hop) .WillOnce(Throw(exception())); SetMuxStateFromAppDb(ACTIVE_STATE); EXPECT_EQ(STANDBY_STATE, m_MuxCable->getState()); } TEST_F(MuxRollbackTest, ActiveToStandbyExceptionRollbackToActive) { SetAndAssertMuxState(ACTIVE_STATE); EXPECT_CALL(*mock_sai_next_hop_api, remove_next_hop) .WillOnce(Throw(exception())); SetMuxStateFromAppDb(STANDBY_STATE); EXPECT_EQ(ACTIVE_STATE, m_MuxCable->getState()); } }
\chapter{Objetivos} % En este apartado deberán aparecer con claridad los objetivos inicialmente previstos en la % propuesta de TFG y los finalmente alcanzados con indicación de dificultades, cambios y % mejoras respecto a la propuesta inicial. Si procede, es conveniente apuntar de manera precisa % las interdependencias entre los distintos objetivos y conectarlos con los diferentes apartados % de la memoria. % Se pueden destacar aquí los aspectos formativos previos más utilizados. %%%%%%%%%% % Incertidumbre tiene, porque no sabes cuál va a ser el resultado % En realidad, lo tuyo sería un primer paso hacia la optimización % Me refiero que aunque en un paso determinado tu algoritmo diga que lo va a petar, hay una cierta incertidumbre. % Por lo tanto si tienes que optimizar la estrategia en base a las predicciones hechas por tu algoritmo hay que prever ese posible "ruido" % Puedes intentar justificarlo diciendo que la predicción en diferentes etapas del juego trata de reducir la incertidumbre a la hora de predecir el resultado. % Y que la predicción del resultado es imprescindeibol para algoritmos que modifiquen sus estrategias durante el juego, online, no offline y sin alterar la estrategia una vez se está jugando. % Ese tipo de estrategias de predecir el resultado se llaman "Montecarlo runs" y se usan un montón en Deep Learning en juegos. %%%%%%%%% % Dentro de la línea de investigación de inteligencia computacional en juegos de nuestro grupo, el alumno investigará la optimización de estrategias para juegos de estrategia en tiempo real tales como el Starcraft, haciendo especial énfasis en el tratamiento estadístico del coste de una estrategia, que es de tipo ruidoso. % Objetivos planteados % Objetivo % Nivel de dificultad (bajo, medio o alto) % Conocer el estado del arte en inteligencia computacional en juegos % bajo % Conocer el estado del arte en optimización con incertidumbre % medio % Crear un bot competitivo en un juego de estrategia en tiempo real que avance el estado del arte en los dos aspectos anteriores % alto Los objetivos inicialmente previstos de este trabajo eran realizar un estudio sobre la optimización de estrategias para juegos de estrategia en tiempo real, como StarCraft, además del desarrollo de un bot competitivo a partir de este estudio. En cambio, se ha variado un poco el objetivo principal un paso atrás: se realiza un análisis de un conjunto de estrategias tomadas por jugadores reales del videojuego para intentar realizar predicciones sobre el resultado final de éstas. Esto se ha decidido así ya que para optimizar una estrategia se debe intentar prever la incertidumbre de éstas, para así poder tomar decisiones más precisas a lo largo de una partida, modificándolas durante la misma en un momento determinado si es necesario. A la hora de predecir el resultado, será un aspecto clave el tiempo actual de la partida: cuanto más avanzada está, menos incertidumbre existe en su desenlace. Este objetivo se ha alcanzado en~\ref{sec:informatica}. Para poder abordar este objetivo, se precisa de conocimiento de técnicas de \emph{aprendizaje estadístico}, por lo que se ha hecho un estudio desde abajo, matemáticamente hablando, de estas técnicas, para asegurar de manera formal que la metodología usada se comporta según lo esperado. Este objetivo se ha alcanzado durante la sección~\ref{sec:matematicas}. Se exponen aquí las asignaturas del Doble Grado cuyo conocimiento ha estado relacionado con este trabajo. \begin{enumerate} \item Cálculo I y II. \item Estadística Descriptiva e Introducción a la Probabilidad. \item Probabilidad. \item Estadística Computacional. \item Fundamentos de programación. \item Metodología de la programación. \item Lógica y Métodos Discretos. \item Algorítmica. \item Estructuras de datos. \item Fundamentos de bases de datos. \item Diseño y Desarrollo de Sistemas de Información. \item Ingeniería de Servidores. \item Servidores Web de Altas Prestaciones. \item Aprendizaje Automático. \end{enumerate}
import { chromium } from 'playwright' import { compareTwoStrings } from 'string-similarity' import csv from 'csv-parser' import chalk from 'chalk' import inquirer from 'inquirer' import { createReadStream, existsSync } from 'fs' import * as fs from 'fs' class Scraper { constructor() { this.FALLBACK_URL = 'https://www.paramountplus.com/brands/nickelodeon/' this.SEARCH_URL = 'https://www.paramountplus.com/search/' this.SHOWS_URL = 'https://www.paramountplus.com/shows/' this.DATA_CSV = 'nickjr-output.csv' this.RESULT_CSV = 'nick-clip-redirects.csv' this.MATCHES_CSV = 'matches.csv' this.MIN_CONFIDENCE = 0.7 this.MIN_SEARCH_LENGTH = 3 this.browser = null this.page = null this.notFoundList = [] this.missingShows = [] this.matchesList = [] this.episodeMap = {} this.currentRow = null this.totalRows = 0 this.completedRows = 0 this.lastLog = '' } closeBrowser = async () => await this.browser.close() slugify = searchTerm => searchTerm .split(' - ')[0] .toLowerCase() .replace(/[^a-z0-9 -]/g, '') .replace(/\s+/g, '-') .replace(/-+/g, '-') .trim() findBestMatch = (searchTerm, urlList) => { const normalizedInput = this.slugify(searchTerm) const bestMatch = urlList.reduce( (best, url) => { const normalizedUrl = url .toLowerCase() .replace(this.SHOWS_URL, '') .replace(/\/$/, '') const score = compareTwoStrings(normalizedInput, normalizedUrl) return score > this.MIN_CONFIDENCE && score > best.score ? { url, score } : best }, { score: 0 } ) if (bestMatch.score > 0) { this.matchesList.push({ searchTerm, bestMatch: bestMatch.url }) this.log( chalk.greenBright( `Best match for ${chalk.white.bold(searchTerm)} is ${chalk.white.bold(bestMatch.url)} with a score of ${chalk.white.bold(Math.round(bestMatch.score * 100))}%` ) ) } return bestMatch.url } scrape = async () => { const data = await this.readCSV(this.DATA_CSV) this.totalRows = data.length for (let i = 0; i < data.length; i++) { const row = data[i] this.currentRow = row await this.processRow() this.completedRows = i + 1 } } processRow = async () => { const { Show } = this.currentRow const searchTerm = Show?.replace(/\s+/g, ' ') if (!this.notFoundList.includes(searchTerm)) { const existingMatch = this.findExistingMatch(searchTerm) if (existingMatch) { await this.handleExistingMatch(existingMatch, searchTerm) } else { await this.searchProperty(searchTerm) } } else { this.handleBrandFallback(searchTerm) } } handleBrandFallback = searchTerm => { this.log( chalk.magentaBright( `Skipped ${chalk.white.bold(searchTerm)} as it was not found previously` ) ) const { Title, Season, Episode, URL } = this.currentRow this.writeOutput(Title, searchTerm, Season, Episode, URL, this.FALLBACK_URL) } findExistingMatch = searchTerm => this.matchesList.find(match => match.searchTerm === searchTerm) handleExistingMatch = async ({ bestMatch, searchTerm }) => { const { Title, Season, Episode, URL } = this.currentRow if (bestMatch.includes?.('/video/')) { this.log( chalk.greenBright( `Identified video link for ${chalk.white.bold(searchTerm)}: ${chalk.white.bold(bestMatch)}` ) ) this.writeOutput(Title, searchTerm, Season, Episode, URL, bestMatch) } else { await this.findEpisodeTarget(bestMatch) } } isErrorPage = async () => { const pageTitle = await this.page.title() if (pageTitle.includes('404') || pageTitle.includes('Error')) { return true } const h2 = await this.page.$('h2') if (h2) { const text = await h2.innerText() return text.includes('404') } } searchProperty = async searchTerm => { this.log( chalk.blueBright( `Searching Paramount+ for: ${chalk.white.bold(searchTerm)}` ) ) await this.page.goto(this.SEARCH_URL) const bestMatch = await this.performSearch(searchTerm) const { Title, Season, Episode, URL } = this.currentRow if (!bestMatch) { this.writeOutput( Title, searchTerm, Season, Episode, URL, this.FALLBACK_URL ) this.notFoundList.push(searchTerm.trim()) } else { this.log( chalk.greenBright( `Already processed ${chalk.white.bold(searchTerm)} checking for episodes` ) ) this.writeOutput(Title, searchTerm, Season, Episode, URL, bestMatch) await this.findEpisodeTarget(bestMatch) } } performSearch = async searchTerm => { let bestMatch = null await this.page.type('input[name="q"]', '') for (let i = 0; i < searchTerm.length; i++) { const char = searchTerm[i] await this.page.type('input[name="q"]', char) await this.page.waitForTimeout(600) // P+ keyup debounce is 500ms const hrefs = await this.page.$$eval( '[data-ci="search-results"] a', results => results .map(result => result.href) // we only care about shows .filter(href => href.includes('/shows/')) ) if (i > this.MIN_SEARCH_LENGTH && !hrefs[0]) { this.log( chalk.red( `No search results for ${chalk.whiteBright.bold(searchTerm)} found after ${chalk.whiteBright.bold(i)} characters` ) ) i = searchTerm.length this.notFoundList.push(searchTerm.trim()) continue } bestMatch = this.findBestMatch(searchTerm, hrefs) if (bestMatch) { this.matchesList.push({ searchTerm, bestMatch }) this.log( chalk.greenBright( `Found a match for ${chalk.whiteBright.bold(searchTerm)} after ${chalk.whiteBright.bold(i)} characters` ) ) break } } return bestMatch } gotoSeason = async seasonUrl => { if (this.page.url().trim() !== seasonUrl.trim()) { const { Season, Show } = this.currentRow this.log( chalk.magenta(`Identified link for ${chalk.white.bold(Show + ' S' + Season)}: ${chalk.white.bold(seasonUrl)}`) ) return await this.page .goto(seasonUrl, { waitUntil: 'domcontentloaded' }) .catch(error => { console.error('Error during seasons navigation:', error) }) } } convertEpisodeNumber(episodeNumber, seasonNumber) { if (typeof episodeNumber === 'string' && episodeNumber.length >= 3) { const seasonPrefix = seasonNumber.toString(); if (episodeNumber.startsWith(seasonPrefix)) { const episodePart = parseInt(episodeNumber.slice(seasonPrefix.length), 10); return episodePart; } } return parseInt(episodeNumber, 10); } findEpisodeTarget = async bestMatch => { const { URL, Title, Episode, Season, Show } = this.currentRow if (!Episode || !Season || !bestMatch) { if (bestMatch) { this.writeOutput(Title, Show, Season, Episode, URL, bestMatch) } return } const seasonUrl = `${bestMatch}episodes/${Season}/` if (this.notFoundList.includes(seasonUrl)) { this.log( chalk.magentaBright( `Skipped ${chalk.white.bold(seasonUrl)} as it was not found previously` ) ) this.writeOutput(Title, Show, Season, Episode, URL, bestMatch) return } await this.gotoSeason(seasonUrl) if (await this.isErrorPage()) { this.notFoundList.push(seasonUrl) this.log( chalk.red(`Error page found for ${chalk.whiteBright.bold(seasonUrl)}`) ) return } const cleanEpisode = this.convertEpisodeNumber(Episode, Season); const stringToFind = `E${cleanEpisode}` try { await this.page.waitForSelector('.episode .epNum', { timeout: 600 }) const episodes = await this.page.$$('.episode .epNum') const { Title, Show, Season, URL } = this.currentRow let episodeLink = false for (const episodeHandle of episodes) { const text = await episodeHandle.innerText() if (text === stringToFind) { episodeLink = await this.getEpisodeHref(episodeHandle) if (episodeLink) { this.log( chalk.greenBright( `Identified episode link for ${chalk.white.bold(stringToFind)}: ${chalk.white.bold(episodeLink)}` ) ) this.writeOutput(Title, Show, Season, Episode, URL, episodeLink) continue } } } if (!episodeLink) { this.writeOutput(Title, Show, Season, Episode, URL, seasonUrl) } } catch ({ message }) { const error = message.split('\n')?.[0] ?? message this.writeOutput(Title, Show, Season, Episode, URL, bestMatch) this.log( chalk.red( `Error finding and processing episode: ${chalk.whiteBright.bold(error)}` ) ) } } getEpisodeHref = async episodeHandle => { return await episodeHandle.evaluate(element => { const findClosestEpisodeParent = el => { while (el && !el.classList.contains('episode')) { el = el.parentElement } return el } const closestEpisodeParent = findClosestEpisodeParent(element) if (closestEpisodeParent) { const anchor = closestEpisodeParent.querySelector('a') return anchor ? anchor.getAttribute('href') : null } return null }) } writeOutput = (Title, Show, Season, Episode, URL, target) => { fs.appendFileSync( this.RESULT_CSV, `"${Title}",${Show},${Season},${Episode},${URL},${target}\n` ) } splashScreen = () => createReadStream('pplus-logo.txt', { encoding: 'utf8' }).on('data', data => console.log(chalk.bgRgb(1, 100, 255).bold(data)) ) getProgressBar = () => { const progressBarWidth = 20 const progress = this.totalRows > 0 ? Math.floor((this.completedRows / this.totalRows) * 100) : 0 const percentageString = `${this.completedRows}/${this.totalRows} ${progress}%` const padLength = Math.max( 0, Math.ceil((progressBarWidth - percentageString.length) / 2) ) const padding = ' '.repeat(padLength) const progressString = `${padding}${percentageString}${' '.repeat( progressBarWidth - percentageString.length - padLength )}` const completedWidth = Math.floor((progress / 100) * progressBarWidth) const completeString = progressString.slice(0, completedWidth) const incompleteString = progressString.slice(completedWidth) const completePercentagePart = chalk.bgRgb(73, 215, 97).bold(completeString) const incompletePercentagePart = chalk .bgRgb(1, 100, 255) .bold(incompleteString) return `${completePercentagePart}${incompletePercentagePart}` } log = message => { const progressBar = this.getProgressBar() if (this.lastLog !== message) { console.log(`${progressBar} ${message}`) this.lastLog = message } } readCSV = async file => { const data = [] return new Promise((resolve, reject) => { fs.createReadStream(file) .pipe(csv()) .on('data', row => data.push(row)) .on('end', () => resolve(data)) .on('error', error => reject(error)) }) } sortResults = records => records.sort((a, b) => { if (a['Title'] < b['Title']) return -1 if (a['Title'] > b['Title']) return 1 if (parseInt(a['Season']) < parseInt(b['Season'])) return -1 if (parseInt(a['Season']) > parseInt(b['Season'])) return 1 if (parseInt(a['Episode']) < parseInt(b['Episode'])) return -1 if (parseInt(a['Episode']) > parseInt(b['Episode'])) return 1 return 0 }) initialize = async () => { console.clear() const isCSVFile = file => file.trim().toLowerCase().endsWith('.csv') const { inputFile, outputFile } = await inquirer.prompt([ { type: 'input', name: 'inputFile', message: 'Enter the input file name:', default: this.DATA_CSV, validate: filename => { if (!isCSVFile(filename)) { return chalk.red('Please enter a valid input file name.') } if (!existsSync(filename)) { return chalk.red('The input file does not exist.') } return true } }, { type: 'input', name: 'outputFile', message: 'Enter the output file name:', default: this.RESULT_CSV, validate: filename => { if (!isCSVFile(filename)) { return chalk.red('Please enter a valid output file name.') } if (existsSync(filename)) { return chalk.red( 'The output file already exists. Please enter a different name.' ) } return true } } ]) this.DATA_CSV = inputFile this.RESULT_CSV = outputFile // uncomment for headless mode // this.browser = await chromium.launch() this.splashScreen() this.browser = await chromium.launch() this.page = await this.browser.newPage() // load existing matches to speed up the process try { const data = await this.readCSV(this.MATCHES_CSV) this.matchesList = data.map(row => ({ searchTerm: row.item, bestMatch: row.url })) } catch (error) { console.error('Error reading matches list:', error) } } } // IIFE ;(async () => { const scraper = new Scraper() try { await scraper.initialize() await scraper.scrape() } catch (error) { console.error(chalk.red('Error during scraping:'), error) } finally { await scraper.closeBrowser() } })()
import React from "react"; import Greeting from "./Greeting"; import Login from "./Login"; import Logout from "./Logout"; class Auth extends React.Component { constructor(props) { super(props); this.state = { isLoggedIn: false } console.log(props) } handleLogin = () => { this.setState({ isLoggedIn: true }) } handleLogout = () => { this.setState({ isLoggedIn: false }) } render() { let button; this.state.isLoggedIn ? button = <Logout onLogout={this.handleLogout} /> : button = <Login onLogin={this.handleLogin} /> return ( <div className="panel"> <Greeting isLoggedIn={this.state.isLoggedIn} /> {button} </div> ) } } export default Auth
#include "variadic_functions.h" #include <stdarg.h> /** * sum_them_all - return the sum of all its parameters. * @n: the number of parameters to the function. * @...: a variable number of parameters to calculate the sum of. * Return: if n == 0 - 0. */ int sum_them_all(const unsigned int n, ...) { va_list sa; unsigned int i, sum = 0; va_start(sa, n); for (i = 0; i < n; i++) sum += va_arg(sa, int); va_end(sa); return (sum); }
<!-- FORM CONTAINER --> <div fxFlex="100" fxLayout="column" class="basic-info-container" *ngIf="formCreate" id="textCreateBasicInfo"> <p>{{'secure.products.create_product_unit.basic_information.basic_product_information' | translate}}</p> <!-- BASIC INFORMATION FORM--> <form class="basic-info" [formGroup]="formBasicInfo" (ngSubmit)="saveBasicInfo()"> <!-- NAME AND CATEGORY --> <div fxLayout="row" fxLayoutAlign="space-between center" fxLayoutAlign.xs="center center" fxLayout.xs="column"> <mat-form-field class="name-product field"> <input matInput [placeholder]="'secure.products.create_product_unit.list_products.product_name' | translate" class="input-name-product" formControlName="Name" (change)="detectForm()" id="nameProduct" maxlength="120" autofocus required> <mat-error *ngIf="formBasicInfo.get('Name').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.format_invalidate' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.get('Name').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> <mat-form-field class="category-product field"> <input matInput [placeholder]="'shared.category' | translate" class="input-category-product" formControlName="Category" (change)="detectForm()" id="categoryProduct"> </mat-form-field> </div> <!-- BRAND AND SHIPPING SIZE --> <div fxLayout="row" fxLayoutAlign="space-between center" fxLayoutAlign.xs="center center" fxLayout.xs="column"> <mat-form-field [ngClass]="isAdmin ? 'field' : 'fieldBrands'" class="" [hidden]="show"> <input matInput [placeholder]="'shared.brand' | translate" [matAutocomplete]="auto" formControlName="Brand" (change)="detectForm()" required> <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let brand of filterBrands" [value]="brand.Name"> {{brand.Name}} </mat-option> </mat-autocomplete> <mat-error *ngIf="formBasicInfo.get('Brand').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.get('Brand').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.brand_invalidate' | translate}}</mat-error> </mat-form-field> <mat-form-field class="fieldBrands" [hidden]="!show"> <input matInput [placeholder]="'shared.brand' | translate" formControlName="Brand" [errorStateMatcher]="matcher" class="text-transform-uppercase" (change)="detectForm()" required> <mat-error *ngIf="formBasicInfo.get('Brand').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.get('Brand').hasError('pattern')">{{'errors.format_invalidate' | translate}} </mat-error> </mat-form-field> <mat-checkbox class="margin-right-70" [matTooltip]="'secure.products.create_product_unit.basic_information.enter_new_brand'| translate" [hidden]="isAdmin" (click)="showBrandsInput(show)"> {{'secure.products.create_product_unit.basic_information.enter_new_brand'| translate}}</mat-checkbox> <div class="shipping-product field"> <label class="label-shipping">{{'secure.products.create_product_unit.basic_information.shipping_size' | translate}}</label> <mat-slider min="1" max="5" tickInterval="true" class="shipping-slider" (change)="detectForm()" formControlName="shippingSize" id="shippingProduct"></mat-slider> <div fxLayout="row" fxLayoutAlign="space-between center" class="items-slider"> <label class="items-slider-label">1</label> <label class="items-slider-label">2</label> <label class="items-slider-label">3</label> <label class="items-slider-label">4</label> <label class="items-slider-label">5</label> </div> </div> </div> <!-- PACKING AND PRODUCT SIZE --> <div fxLayout="row" fxLayoutAlign="space-between center" fxLayoutAlign.xs="center center" fxLayout.xs="column" class="container-sub-forms"> <div class="sub-form" formGroupName="packing"> <label class="label-shipping">{{'secure.products.create_product_unit.basic_information.packaging' | translate}} </label> <div fxLayout="row" fxLayout.xs="column" fxLayoutAlign="space-between center"> <div class="packing-sub-level" fxLayout="row" fxLayoutAlign="space-between center"> <mat-form-field class="packing-field"> <input matInput [placeholder]="'secure.products.create_product_unit.list_products.expanded_product.height' | translate" class="input-packing-high" formControlName="HighPacking" (change)="detectForm()" id="highPackingProduct" required> <mat-error *ngIf="formBasicInfo.controls.packing.get('HighPacking').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.dimension_invalid' | translate}} </mat-error> <mat-error *ngIf="formBasicInfo.controls.packing.get('HighPacking').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> <mat-form-field class="packing-field"> <input matInput [placeholder]="'secure.products.create_product_unit.list_products.expanded_product.length' | translate" class="input-packing-long" formControlName="LongPacking" (change)="detectForm()" id="longPackingProduct" required> <mat-error *ngIf="formBasicInfo.controls.packing.get('LongPacking').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.dimension_invalid' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.controls.packing.get('LongPacking').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> </div> <div class="packing-sub-level" fxLayout="row" fxLayoutAlign="space-between center"> <mat-form-field class="packing-field"> <input matInput [placeholder]="'secure.products.create_product_unit.list_products.expanded_product.width' | translate" class="input-packing-width" formControlName="WidthPacking" (change)="detectForm()" id="widthPackingProduct" required> <mat-error *ngIf="formBasicInfo.controls.packing.get('WidthPacking').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.dimension_invalid' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.controls.packing.get('WidthPacking').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> <mat-form-field class="packing-field"> <input matInput [placeholder]="'secure.products.create_product_unit.list_products.expanded_product.weight' | translate" class="input-packing-weight" formControlName="WeightPacking" (change)="detectForm()" id="weightPackingProduct" required> <mat-error *ngIf="formBasicInfo.controls.packing.get('WeightPacking').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.dimension_invalid' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.controls.packing.get('WeightPacking').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> </div> </div> </div> <div class="sub-form product-form" formGroupName="product"> <label class="label-shipping">{{'shared.product' | translate}} (cm/kg)</label> <div fxLayout="row" fxLayout.xs="column" fxLayoutAlign="space-between center"> <div class="packing-sub-level" fxLayout="row" fxLayoutAlign="space-between center"> <mat-form-field class="packing-field"> <input matInput [placeholder]="'secure.products.create_product_unit.list_products.expanded_product.height' | translate" class="input-packing-high" formControlName="HighProduct" (change)="detectForm()" id="highProduct" required> <mat-error *ngIf="formBasicInfo.controls.product.get('HighProduct').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.dimension_invalid' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.controls.product.get('HighProduct').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> <mat-form-field class="packing-field"> <input matInput [placeholder]="'secure.products.create_product_unit.list_products.expanded_product.length' | translate" class="input-packing-long" formControlName="LongProduct" (change)="detectForm()" id="longProduct" required> <mat-error *ngIf="formBasicInfo.controls.product.get('LongProduct').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.dimension_invalid' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.controls.product.get('LongProduct').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> </div> <div class="packing-sub-level" fxLayout="row" fxLayoutAlign="space-between center"> <mat-form-field class="packing-field"> <input matInput [placeholder]="'secure.products.create_product_unit.list_products.expanded_product.width' | translate" class="input-packing-width" formControlName="WidthProduct" (change)="detectForm()" id="widthProduct" required> <mat-error *ngIf="formBasicInfo.controls.product.get('WidthProduct').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.dimension_invalid' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.controls.product.get('WidthProduct').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> <mat-form-field class="packing-field"> <input matInput [placeholder]="'secure.products.create_product_unit.list_products.expanded_product.weight' | translate" class="input-packing-weight" formControlName="WeightProduct" (change)="detectForm()" id="weightProduct" required> <mat-error *ngIf="formBasicInfo.controls.product.get('WeightProduct').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.dimension_invalid' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.controls.product.get('WeightProduct').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> </div> </div> </div> </div> <div fxLayout="row" fxLayoutAlign="space-between center" fxLayoutAlign.xs="center center" fxLayout.xs="column"> <mat-form-field class="field"> <mat-select [placeholder]="'secure.products.create_product_unit.basic_information.mesasuring' | translate" formControlName="MeasurementUnit" (change)="detectForm()" required> <mat-option *ngFor="let unit of UnitMeasurementList" [value]="unit | translate"> {{unit | translate}} </mat-option> </mat-select> <mat-error *ngIf="formBasicInfo.get('MeasurementUnit').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> <mat-form-field class="field"> <input matInput [placeholder]="'secure.products.table_load_product.conversion_factor' | translate" class="input-packing-width" formControlName="ConversionFactor" (change)="detectForm()" id="conversionFactorProduct" required> <mat-error *ngIf="formBasicInfo.get('ConversionFactor').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.get('ConversionFactor').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.format_invalidate' | translate}}</mat-error> </mat-form-field> </div> <div *ngIf="productData.ProductType === 'Clothing'"> <mat-form-field class="field"> <input matInput [placeholder]="'secure.orders.order_list.product_order.reference' | translate" class="input-packing-long" formControlName="parentReference" (change)="detectForm()" id="parentReference" required> <mat-error *ngIf="formBasicInfo.get('parentReference').hasError('required') && formBasicInfo.get('parentReference').touched"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.get('parentReference').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.format_invalidate' | translate}}</mat-error> </mat-form-field> </div> <div fxLayout="column" fxLayoutAlign="space-between center" fxLayoutAlign.xs="center center" fxLayout.xs="column" class="width-100"> <angular-editor formControlName="Description" id="Description" [config]="config" class="width-100" (change)="detectForm()" required></angular-editor> <mat-error *ngIf="formBasicInfo.get('Description').hasError('required') && formBasicInfo.get('Description').touched"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.get('Description').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.format_invalidate' | translate}}</mat-error> </div> <mat-divider></mat-divider> <mat-form-field class="keyword-field"> <input type="tel" matInput [placeholder]="'secure.products.create_product_unit.list_products.expanded_product.keywords' | translate" formControlName="Keyword" id="keywordProduct" (keyup.enter)="saveKeyword()" (change)="detectForm()" (focus)="setValidatorKeywords()" required> <mat-icon matSuffix class="material-icons add-keyword-icon" (click)="saveKeyword()"> add_circle_outline </mat-icon> <mat-error *ngIf="formBasicInfo.get('Keyword').hasError('required') && formBasicInfo.get('Keyword').touched"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.get('Keyword').hasError('pattern') && formBasicInfo.get('Keyword').touched"> {{'secure.products.create_product_unit.basic_information.only_up_to_20_keywords' | translate}}</mat-error> </mat-form-field> <div class="flex-wrap-display"> <mat-chip-list> <mat-chip *ngFor="let key of keywords; let i= index" (removed)="deleteKeywork(i)"> {{key}} <mat-icon class="material-icons" matChipRemove>cancel</mat-icon> </mat-chip> </mat-chip-list> </div> <mat-divider class="my-1"></mat-divider> <mat-checkbox formControlName="IsCombo" (click)="checkVerify(IsCombo.value)"> {{'secure.products.create_product_unit.basic_information.kit' | translate}}</mat-checkbox> <ng-container *ngIf="!!IsCombo.value"> <div> <mat-form-field class="keyword-field my-1"> <input matInput [placeholder]="'secure.products.create_product_unit.basic_information.kit_ean' | translate" class="input-packing-width" formControlName="EanCombo" (keyup.enter)="addEanCombo()"> <mat-icon matSuffix class="material-icons" (click)="addEanCombo()" class="add-keyword-icon"> add_circle_outline </mat-icon> <mat-error *ngIf="formBasicInfo.get('EanCombo').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.invalid_ean' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.get('EanCombo').hasError('existBD')"> {{'secure.products.create_product_unit.basic_information.not_exist_ean' | translate}}</mat-error> <mat-error *ngIf="formBasicInfo.get('EanCombo').hasError('exist')"> {{'secure.products.create_product_unit.basic_information.alredy_added_ean' | translate}}</mat-error> </mat-form-field> </div> </ng-container> <div class="flex-wrap-display"> <mat-chip-list> <mat-chip *ngFor="let ean of combos; let i= index" (removed)="deleteEan(i)"> {{ean}} <mat-icon class="material-icons" matChipRemove>cancel</mat-icon> </mat-chip> </mat-chip-list> </div> <mat-divider></mat-divider> </form> <!-- BUTTON TO ADD SONS --> <div fxLayout="row" fxLayoutAlign="space-between center" *ngIf="productData.ProductType === 'Clothing'" class="sticky-position"> <div> </div> <button fxLayout="row" [disabled]="disabledEanChildren" fxLayoutAlign="center center" class="add-son-button" mat-button (click)="addSon()"> <mat-icon class="material-icons"> add_circle_outline </mat-icon> <span>{{'secure.products.create_product_unit.basic_information.add_variation' | translate}}</span> </button> </div> <!-- SON LIST --> <div *ngFor="let son of sonList; let i= index" fxLayout="column"> <div fxLayout="row" fxLayoutAlign="space-between center" class="border-bottom-gray"> <label> {{'secure.products.create_product_unit.basic_information.add_variation' | translate}} {{i+1}} </label> <button mat-icon-button (click)="toggleSon(son)"> <mat-icon class="material-icons" *ngIf="son.Show"> expand_less </mat-icon> <mat-icon class="material-icons" *ngIf="!son.Show"> expand_more </mat-icon> </button> </div> <!-- SHOW FORM --> <div *ngIf="son.Show" class="son-container"> <div class="text-right"> <button mat-icon-button [disabled]="disabledEanChildren" [matTooltip]="'secure.products.create_product_unit.basic_information.delete_variation'" (click)="deleteSon(i)"> <mat-icon class="material-icons"> delete </mat-icon> </button> </div> <!-- SON FORM --> <form [formGroup]="son.form" (ngSubmit)="saveBasicInfo()"> <!-- EAN SON AND SIZE --> <div fxLayout="row" fxLayoutAlign="space-between center" fxLayoutAlign.xs="center center" fxLayout.xs="column"> <!-- EAN --> <div class="name-product field"> <mat-form-field id="inputValidEanSon"> <input matInput [placeholder]="'secure.products.create_product_unit.basic_information.ean_son' | translate" class="input-name-product" formControlName="Ean" (blur)="validateEanSon()" (change)="detectForm()"> <mat-error *ngIf="son.form.get('Ean').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.ean_invalida' | translate}}</mat-error> <mat-error *ngIf="son.form.controls.Ean.errors && son.form.controls.Ean.errors.validExistEanSonDB">El {{'secure.products.create_product_unit.basic_information.ean_invalida_multioffer' | translate}} </mat-error> <mat-error *ngIf="son.form.get('Ean').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> <div class="distanceComponetInt"> <mat-checkbox #asignatedEanSonCheckBox (change)="onAsignatedEanSonChanged(asignatedEanSonCheckBox.checked, son.form.get('Ean'))" formControlName="associateEanSon"> {{'secure.products.create_product_unit.basic_information.dont_have_ean' | translate}}</mat-checkbox> </div> </div> <mat-form-field class="category-product field"> <mat-label>{{'secure.products.create_product_unit.basic_information.size' | translate}}</mat-label> <mat-select formControlName="Size"> <mat-option *ngFor="let size of sizes" (change)="detectForm()" class="input-category-product" [value]="size.size"> {{size.size}} </mat-option> </mat-select> <mat-error *ngIf="son.form.get('Size').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.size_invalid' | translate}}</mat-error> <mat-error *ngIf="son.form.get('Size').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> </div> <div fxLayout="row" class="basic-information-margin-top"> <div> <span>{{'secure.products.create_product_unit.basic_information.color_list' | translate}} </span> <span *ngIf="son.colorSelected"> <span class="basic-information-font-size-12"> ({{'secure.products.create_product_unit.basic_information.selected_color' | translate}}: </span><span class="basic-information-font-size-12">{{son.colorSelected}})</span> </span> </div> </div> <div fxLayout="row wrap" class="basic-information-component-container-color basic-information-container-margin-bottom" fxLayoutAlign="start stretch"> <div class="basic-information-padding" *ngFor="let color of son.listColor"> <div *ngIf="color.code !== 'FF90C8' && color.code !== 'D2691E'" (click)="select(color.code, color.name ,color.selected, son)" class="basic-information-component-container" fxFlex.xs="100" fxFlex.xl="100" [ngStyle]="{'background-color': '#' + color.code, 'border': color.border ,'transition' : 'transform .5s'}"> <div class="basic-information-height-30"> <mat-icon class="basic-information-container-color" *ngIf="color.selected">check_circle</mat-icon> </div> <div class="text-select-color basic-information-container-line-height" [ngStyle]="{'color': '#'+ color.colorText}"> {{color.name}} </div> </div> <div *ngIf="color.code === 'FF90C8'" (click)="select(color.code, color.name ,color.selected, son)" class="colorPallet basic-information-component-container" [ngStyle]="{'transition' : 'transform .5s'}" fxFlex.xs="100" fxFlex.xl="100"> <div class="basic-information-height-30"> <mat-icon class="basic-information-container-color" *ngIf="color.selected">check_circle</mat-icon> </div> <div class="text-select-color basic-information-container-line-height" [ngStyle]="{'color': '#'+ color.colorText}"> {{color.name}} </div> </div> <div *ngIf="color.code === 'D2691E'" (click)="select(color.code, color.name ,color.selected, son)" class="colorSurtido basic-information-component-container" [ngStyle]="{'transition' : 'transform .5s'}" fxFlex.xs="100" fxFlex.xl="100"> <div class="basic-information-height-30"> <mat-icon class="basic-information-container-color" *ngIf="color.selected">check_circle</mat-icon> </div> <div class="text-select-color basic-information-container-line-height" [ngStyle]="{'color': '#'+ color.colorText}"> {{color.name}} </div> </div> </div> </div> <mat-form-field class="category-product field"> <input matInput [placeholder]="'secure.products.create_product_unit.basic_information.color_spec' | translate" formControlName="HexColorCodeName" (change)="detectForm()" id="hexColorNameProduct"> <mat-error *ngIf="son.form.get('HexColorCodeName').hasError('pattern')"> {{'secure.products.create_product_unit.basic_information.specific_name_invalid' | translate}}</mat-error> <mat-error *ngIf="son.form.get('HexColorCodeName').hasError('required')"> {{'secure.products.create_product_unit.basic_information.input_mandatory' | translate}}</mat-error> </mat-form-field> </form> </div> </div> </div>
import argparse import glob import json import os from shutil import copyfile, copytree from diff import diff_dir def get_crispresso2_info_path(result_dir): potential_paths = glob.glob(os.path.join(result_dir, 'CRISPResso2*_info.json')) if len(potential_paths) > 1: raise Exception('More than one CRISPResso2 info file found in {0}'.format(result_dir)) elif len(potential_paths) == 0: raise Exception('No CRISPResso2 info file found in {0}'.format(result_dir)) return potential_paths[0] def get_crispresso2_info(result_directory): crispresso2_info = {} with open(get_crispresso2_info_path(result_directory)) as fh: crispresso2_info = json.load(fh) return crispresso2_info def add_test_to_makefile(command, name, directory, input_files): with open('Makefile', 'r') as fh: makefile_lines = fh.readlines() with open('Makefile', 'w') as fh: for line in makefile_lines: if line.startswith('all:'): fh.write('{0} {1}\n'.format(line.strip(), name)) elif line.startswith('cli_integration_tests/CRISPRessoBatch_on_large_batch* \\'): fh.write(line) fh.write('cli_integration_tests/{0}* \\\n'.format(directory)) elif line.startswith('CRISPRessoWGS_on_Both.Cas9.fastq.smallGenome \\'): fh.write(line) fh.write('{0} \\\n'.format(directory)) else: fh.write(line) fh.write('\n.PHONY: {name}\n{name}: cli_integration_tests/{directory}\n'.format(name=name, directory=directory)) fh.write('\ncli_integration_tests/{directory}: install {input_files}\n'.format( directory=directory, input_files=' '.join('cli_integration_tests/inputs/{0}'.format(os.path.basename(i)) for i in input_files) )) fh.write('\tcd cli_integration_tests && cmd="{command}"; $(RUN)'.format(command=command)) def add_test(args): crispresso2_info = get_crispresso2_info(args.directory) test_command = crispresso2_info['running_info']['command_used'] run_name = crispresso2_info['running_info']['args']['value']['name'] input_file_keys = ['fastq_r1', 'r1', 'fastq_r2', 'r2', 'bam_input', 'batch_settings', 'amplicons_file'] command_parts = test_command.split(' ') command_parts[0] = os.path.basename(command_parts[0]) test_command = ' '.join(command_parts) print('Adding a new test case!\n') print('Test command: {0}'.format(test_command)) command_input = input('Is this correct? [y/n]: ') if command_input.lower() == 'n': test_command = input('Enter the correct test command: ') if run_name: print('\nRun name: {0}'.format(run_name)) print('This should be short and descriptive of the test case. No spaces, and use - to separate words. Do not append with `-test`.') print('This will be used as a short keyword to run the test.') run_name_input = input('Is this correct? [y/n]: ') if run_name_input.lower() == 'n': run_name = input('Enter the correct run name: ') else: run_name = input('Enter the run name: ') print('Copying files to cli_integration_tests/inputs directory...') input_files = [ crispresso2_info['running_info']['args']['value'][input_file_key] for input_file_key in input_file_keys if input_file_key in crispresso2_info['running_info']['args']['value'] ] # check for more input files found in batch file if 'batch_settings' in crispresso2_info['running_info']['args']['value']: try: with open(crispresso2_info['running_info']['args']['value']['batch_settings']) as fh: column_headers = fh.readline().strip().split('\t') column_indexes_to_copy = [] for column_index, column_header in enumerate(column_headers): if column_header in input_file_keys: column_indexes_to_copy += [column_index] for line in fh: columns = line.strip().split('\t') input_files.extend(columns[column_index] for column_index in column_indexes_to_copy) except: print('Could not find batch file {0}, please copy the batch file and the files found therein to cli_integration_tests/inputs manually!'.format(crispresso2_info['running_info']['args']['value']['batch_settings'])) for input_file in input_files: if input_file: try: copyfile(input_file, os.path.join('cli_integration_tests/inputs', os.path.basename(input_file))) print('Copied {0} to cli_integration_tests/inputs/'.format(input_file)) except: print('Could not copy {0} to cli_integration_tests/inputs, please manually copy!'.format(input_file)) print('If there are other input files, please copy them to cli_integration_tests/inputs manually!') directory_name = os.path.basename(os.path.normpath(args.directory)) print('\nAdding results to cli_integration_tests/expected_results/{0}'.format(directory_name)) try: copytree(args.directory, os.path.join('cli_integration_tests/expected_results', directory_name), dirs_exist_ok=True) except: print('Could not copy {0} to cli_integration_tests/expected_results, please manually copy!'.format(args.directory)) try: copyfile('{0}.html'.format(args.directory), os.path.join('cli_integration_tests/expected_results', '{0}.html'.format(directory_name))) except: print('Could not copy {0}.html to cli_integration_tests/expected_results, please manually copy!'.format(args.directory)) print('\nAdding test to Makefile...') add_test_to_makefile(test_command, run_name, directory_name, input_files) print('\nAdding actual files to .gitignore...') with open('.gitignore', 'a') as fh: fh.write('\ncli_integration_tests/{0}*\n'.format(directory_name)) print('\nYou can now run the command with `make {0}`'.format(run_name)) print('And test with the command `make {0}-test`'.format(run_name)) def update_test(args): if not diff_dir(args.actual, args.expected, prompt_to_update=True): print('No changes to update!') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.set_defaults(func=lambda _: parser.print_help()) subparsers = parser.add_subparsers() parser_add = subparsers.add_parser('add', help='Add a new test') parser_add.set_defaults(func=add_test) parser_add.add_argument('directory', help='Path to the result directory of the test to add') parser_update = subparsers.add_parser('update', help='Update an existing test') parser_update.set_defaults(func=update_test) parser_update.add_argument('actual', help='Path to the result directory of the test to update') parser_update.add_argument('expected', help='Path to the expected result directory of the test to update') args = parser.parse_args() args.func(args)
# NJUPT-login 南京邮电大学校园网登录脚本。大概是Python新手的第一次尝试(不要喷我)。 [English](https://github.com/WiIIiamWei/NJUPT-login/blob/main/README-EN.md) ## 如何使用 **! 请注意:本脚本会在当前文件夹生成config.bin储存你的登录信息,请不要随意删除或传播该文件,此举会导致你的密码泄露!** 您可以直接在Release界面找到使用`pyinstaller`生成的可执行文件,也可以下载源代码直接运行(需要`requests`库)。 为了方便辨认,可执行程序使用了南京邮电大学的logo。此行为未经授权,故只用于学术目的,请不要将其用于商业目的。 推荐您将可执行文件单独放在一个文件夹里,然后创建桌面快捷方式或将快捷方式放到“启动”文件夹内开机自启(也可创建计划任务)。 ## 其他的方案 ### 使用`curl`进行登录请求 对于校园网账户,可以使用以下命令: ```bash curl --insecure "https://p.njupt.edu.cn:802/eportal/portal/login?&&user_account=<BID>&&user_password=<PASSWORD>" ``` 对于中国移动账户,可以使用以下命令: ```bash curl --insecure "https://p.njupt.edu.cn:802/eportal/portal/login?&&user_account=<BID>%40cmcc&&user_password=<PASSWORD>" ``` 对于中国电信账户,可以使用以下命令: ```bash curl --insecure "https://p.njupt.edu.cn:802/eportal/portal/login?&&user_account=<BID>%40njxy&&user_password=<PASSWORD>" ``` 使用时,请将`<BID>`替换为自己的学号,`<PASSWORD>`替换为自己的统一身份验证密码。 **此方法不适用于Windows PowerShell中的`curl`,因为其已被alias为`Invoke-WebRequest`。若想在Windows上设置,您可使用Cygwin或Git Bash等其他shell,或者安装适用于Windows的`curl`,或参照下方方案使用`Invoke-WebRequest`。** 您还可以为此命令设置alias,以便能在您的shell中使用。例如,对于bash和zsh,请分别在`.bashrc`和`.zshrc`(通常位于`~/.bashrc`或`~/.zshrc`)加入以下行: ```bash alias njupt-login='curl --insecure "https://p.njupt.edu.cn:802/eportal/portal/login?&&user_account=<BID>&&user_password=<PASSWORD>"' ``` *请根据您的账户类型选择正确的URL(参照`curl`中的URL),以上仅为一个例子。* ### 使用`Invoke-WebRequest`进行登录请求 使用以下命令: ```powershell Invoke-WebRequest -Uri "https://p.njupt.edu.cn:802/eportal/portal/login?&&user_account=<BID>&&user_password=<PASSWORD>" -UseBasicParsing ``` *请根据您的账户类型选择正确的URL(参照`curl`中的URL),以上仅为一个例子。* 若需要在PowerShell中创建alias,您可以在`$profile$`加入下列函数(可以通过在PowerShell中键入`$profile$`找到该文件的位置): ```powershell function njupt-login { $response = Invoke-WebRequest -Uri "https://p.njupt.edu.cn:802/eportal/portal/login?&&user_account=<BID>&&user_password=<PASSWORD>" -UseBasicParsing $response.Content } ``` *请根据您的账户类型选择正确的URL(参照`curl`中的URL),以上仅为一个例子。* ## 版权声明 本项目的可执行程序图标使用了南京邮电大学商标(仅为方便辨识使用,如涉及侵权请与我联系),此商标版权归南京邮电大学所有。 其余所有的项目代码均遵守GNU GPLv3协议。
import React from 'react' function GuideBtn () { return ( <div className='guide-container'> <div className="guide-inner"> <h2>가이드페이지</h2> <div className='guide-item'> <p className='guide-title'>1. 기본타입 버튼 <p className='guide-sub'>기본타입 버튼입니다.</p> </p> <div className='flex'> <button className='btn type-bg'>배경있는 버튼</button> <button className='btn type-line'>라인있는 버튼</button> </div> </div> <div className='guide-item'> <p className='guide-title'>2. hover <p className='guide-sub'>hover 버튼입니다.</p> </p> <div className='flex'> <button className='btn type-bg hover'>배경있는 버튼</button> <button className='btn type-line hover'>라인있는 버튼</button> </div> </div> <div className='guide-item'> <p className='guide-title'>3. 아이콘 있는 버튼 <p className='guide-sub'>아이콘 버튼입니다.</p> </p> <div className='flex'> <button className='btn type-bg hover'> 배경있는 버튼 <em className='ico plus'></em> </button> <button className='btn type-line hover'> 라인있는 버튼 <em className='ico plus ico-black'></em> </button> </div> </div> <div className='guide-item'> <p className='guide-title'>4. disabled <p className='guide-sub'>disabled 버튼입니다.</p> </p> <div className='flex'> <button className='btn type-bg hover disabled'> 배경있는 버튼 <em className='ico plus'></em> </button> <button className='btn type-line hover disabled'> 라인있는 버튼 <em className='ico plus ico-black'></em> </button> </div> </div> <div className='guide-item'> <p className='guide-title'>5. 버튼 사이즈 <p className='guide-sub'>작은 사이즈부터 ~</p> </p> <div className='flex'> <button className='btn type-bg size-sm'> 배경있는 버튼 <em className='ico plus'></em> </button> <button className='btn type-line size-sm'> 라인있는 버튼 <em className='ico plus ico-black'></em> </button> </div> </div> <div className='guide-item'> <p className='guide-title'>6. 큰 버튼 <p className='guide-sub'>로그인 페이지에 사용됨</p> </p> <div className='flex'> <button className='btn type-bg size-lg'> 로그인 </button> </div> </div> <div className='guide-item'> <p className='guide-title'>7. 기타 <p className='guide-sub'>테이블 내부에 사용됨. 호버효과 있음</p> </p> <div className='flex'> <a href="#!" className='btn_tb'> <span>확인하기</span> <em className='ico arrow_right'></em> </a> <a href="#!" className='btn_tb size-sm'> <span>더작은</span> <em className='ico arrow_right'></em> </a> </div> </div> </div> </div> ) } export default GuideBtn
import { FaTicketAlt, FaHockeyPuck, FaChair } from "react-icons/fa"; import { getUserCount, requireUserSession } from "~/data/auth.server"; import { useLoaderData, Link } from "@remix-run/react"; import SideNav from "~/components/NavigationMenu"; import { getTicketsCount } from "~/data/tickets.server"; export default function Index() { const { userId, userCount, ticketCount } = useLoaderData(); const profileUrl = `/profile/${userId}`; return ( <div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.8" }}> <SideNav /> {/* <MainHeader /> */} <h1 className="text-xl font-bold text-white flex justify-center text-center py-10"> Welcome to the New York Rangers Season Ticket Exchange </h1> <div className="grid justify-center items-center"> <p className="text-white text-center px-5"> Season Ticket Exchange is for the real fans of the game. It's for the season ticket holders looking to put their seats in the hands of fans who are looking for tickets at face value without all the absurd fees like on other sites. </p> <p className="text-white text-center px-5"> If you have any feature requests please email{" "} <a className="underline" href="mailto:djreale@gmail.com?subject=MBB%20Feedback" > djreale@gmail.com </a> </p> <div className="flex justify-center pt-5 py-5 flex-wrap"> <p className="text-white text-center text-white"> Fill out your </p> <Link to={profileUrl} className="underline px-1 text-white"> profile, </Link> <p className="text-white text-center text-white"> {" "} get verified, and start selling{" "} </p> <Link to="/mytickets" className="underline px-2"> <FaTicketAlt className="text-gray text-3xl" /> </Link> <p className="text-white text-center text-white"> today!</p> </div> <div className="flex justify-center pt-5 py-5"> <p className="text-white text-center text-white">Find great </p> <Link to="/tickets" className="underline px-2"> <FaChair className="text-gray text-3xl" /> </Link> <p className="text-white text-center text-white"> today!</p> </div> </div> <div className="grid justify-center items-center text-white text-center space-x-2 pt-10 pb-5"> <h2 className="font-bold text-xl underline">Season Ticket Stats</h2> <div className="flex justify-center space-x-2"> <label>User Count:</label> <p className="font-bold text-yellow underline">{userCount}</p> </div> <div className="flex justify-center space-x-2"> <label>Ticket Count:</label> <p className="font-bold text-yellow underline">{ticketCount}</p> </div> {/* <div className="flex justify-center"> <label>Sold Ticket Count:</label> <p className="font-bold text-yellow underline">{spiritsCount}</p> </div> */} <div> <h2 className="font-bold text-xl underline py-2">FAQS</h2> <label className="font-bold underline" htmlFor=""> Ticket Statuses </label> <p> <strong>AVAILABLE</strong> - Ticket is available for purchase </p> <p> <strong>RESERVED</strong> - Ticket has been reserved by a user who wishes to purchase </p> <p> <strong>PENDING</strong> - User has paid for the ticket and is awaiting receipty from seller </p> <p> <strong>SOLD</strong> - Seller has accepted the buyers payment and the ticket is now sold. </p> <label className="font-bold underline" htmlFor=""> Paid Statuses </label> <p> <strong>AVAILABLE</strong> - Ticket is available and there is no paid status at this time </p> <p> <strong>PENDING_PAYMENT</strong> - Ticket has been reserved by a buyer but payment has not been made yet. </p> <p> <strong>PENDING_SELLER_ACCEPTANCE</strong> - Buyer has sent the seller a payment for the tickets </p> <p> <strong>PAYMENT_COMPLETE</strong> - Buyer has acknowledged and reeived the payment from the buyer. </p> </div> </div> </div> ); } export async function loader({ request }) { const userId = await requireUserSession(request); //TODO: get user session without redirecting const userCount = await getUserCount(); const ticketCount = await getTicketsCount(); return { userId, userCount, ticketCount }; }
import { css, html, TemplateResult } from 'lit'; import { customElement, property, state } from 'lit/decorators.js'; import { classMap } from 'lit/directives/class-map.js'; import '@material/web/checkbox/checkbox'; import '@material/web/icon/icon'; import '@material/web/list/list'; import '@material/web/list/list-item'; import { FilterListBase } from './base-list.js'; export type SelectItem = { /** The main information of the list item */ headline: string; /** Supporting information rendered in a second line */ supportingText?: string; /** An attached XML element */ attachedElement?: Element; /** An icon rendered left to the list item content */ startingIcon?: string; /** Whether an icon is selected */ selected: boolean; }; @customElement('selection-list') /** List component to select from a set of options */ export class SelectionList extends FilterListBase { @property({ type: Array }) items: SelectItem[] = []; @property({ type: Array }) get selectedElements(): Element[] { const elements: Element[] = []; this.items.forEach(item => { if (item.selected && item.attachedElement) elements.push(item.attachedElement); }); return elements; } private renderCheckboxListItem(item: SelectItem): TemplateResult { return html`<md-list-item class="${classMap({ hidden: !this.searchRegex.test( `${item.headline} ${item.supportingText ?? ''}` ), })}" > <div slot="headline">${item.headline}</div> ${item.supportingText ? html`<div slot="headline">${item.supportingText}</div>` : html``} <md-checkbox slot="end" ?checked=${item.selected} @change="${() => { // eslint-disable-next-line no-param-reassign item.selected = !item.selected; }}" ></md-checkbox> </md-list-item>`; } private renderListItem(item: SelectItem): TemplateResult { return this.renderCheckboxListItem(item); } render(): TemplateResult { return html`<section> ${this.renderSearchField()} <div style="display: flex;"> <md-list class="listitems"> ${this.items.map(item => this.renderListItem(item))}</md-list > </div> </section>`; } static styles = css` section { display: flex; flex-direction: column; } md-outlined-text-field { background-color: var(--md-sys-color-surface, #fef7ff); --md-outlined-text-field-container-shape: 32px; padding: 8px; } .listitems { flex: auto; } .hidden { display: none; } `; }
<template> <div> <!-- 面包屑导航区域 --> <el-breadcrumb separator-class="el-icon-arrow-right"> <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item> <el-breadcrumb-item>商品管理</el-breadcrumb-item> <el-breadcrumb-item>添加商品</el-breadcrumb-item> </el-breadcrumb> <!-- 卡片视图 --> <el-card> <!-- 提示区域 --> <el-alert title="消息提示的文案" type="info" center show-icon :closable="false"> </el-alert> <!-- 步骤条区域 --> <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center> <el-step title="基本信息"></el-step> <el-step title="商品参数"></el-step> <el-step title="商品属性"></el-step> <el-step title="商品图片"></el-step> <el-step title="商品内容"></el-step> <el-step title="完成"></el-step> </el-steps> <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm" label-position="top"> <!-- tab栏区域 --> <el-tabs v-model="activeIndex" tab-position="left" :before-leave="beforeTabLeave" @tab-click="tabClicked"> <el-tab-pane label="基本信息" name="0"> <el-form-item label="商品名称" prop="goods_name"> <el-input v-model="addForm.goods_name"></el-input> </el-form-item> <el-form-item label="商品价格" prop="goods_price"> <el-input v-model="addForm.goods_price"></el-input> </el-form-item> <el-form-item label="商品重量" prop="goods_weight"> <el-input v-model="addForm.goods_weight"></el-input> </el-form-item> <el-form-item label="商品数量" prop="goods_number"> <el-input v-model="addForm.goods_number"></el-input> </el-form-item> <el-form-item label="商品分类" prop="goods_cat"> <el-cascader v-model="addForm.goods_cat" :options="catelist" :props="cateProps" @change="handleChange"></el-cascader> </el-form-item> </el-tab-pane> <el-tab-pane label="商品参数" name="1"> <!-- 渲染表单的item项 --> <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id"> <el-checkbox-group v-model="item.attr_vals"> <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border></el-checkbox> </el-checkbox-group> </el-form-item> </el-tab-pane> <el-tab-pane label="商品属性" name="2"> <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id"> <el-input v-model="item.attr_vals"></el-input> </el-form-item> </el-tab-pane> <el-tab-pane label="商品图片" name="3"> <el-upload :headers="headerObj" :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :on-success="handleSuccess"> <el-button size="small" type="primary">点击上传</el-button> </el-upload> </el-tab-pane> <el-tab-pane label="商品内容" name="4"> <!-- 富文本编辑器组件 --> <quill-editor v-model="addForm.goods_introduce"></quill-editor> <!-- 添加商品的按钮 --> <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button> </el-tab-pane> </el-tabs> </el-form> </el-card> <!-- 图片预览 --> <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%"> <img :src="previewPath" alt=""> </el-dialog> </div> </template> <script> import _ from 'lodash' export default { data() { return { activeIndex: '0', //添加商品的数据对象 addForm: { goods_name: '', goods_price: 10, goods_weight: 0, goods_number: 10, //商品分类数组 goods_cat: [], // 图片的数组 pics: [], //商品的详情描述 goods_introduce: '', // attrs: [] }, addFormRules: { goods_name: [ {required: true, message: '请输入商品名称', trigger: 'blur'} ], goods_price: [ {required: true, message: '请输入商品价格', trigger: 'blur'} ], goods_weight: [ {required: true, message: '请输入商品重量', trigger: 'blur'} ], goods_number: [ {required: true, message: '请输入商品数量', trigger: 'blur'} ], goods_cat: [ {required: true, message: '请选择分类', trigger: 'blur'} ] }, //商品分类列表 catelist: [], cateProps: { label: 'cat_name', value: 'cat_id', children: 'children' }, // 动态参数列表数据 manyTableData: [], //静态属性列表数据 onlyTableData:[], //上传图片的URL地址 uploadURL: 'http://www.ysqorz.top:8888/api/private/v1/upload', //图片上传组件的headers请求头对象 headerObj: { Authorization: window.sessionStorage.getItem('token') }, previewPath: '', previewVisible: false, } }, created() { this.getCateList() }, methods: { //获取所有商品分类数据 async getCateList() { const {data: res} = await this.$http.get('categories') if (res.meta.status !== 200) { return this.$message.error('获取商品分类数据失败') } this.catelist = res.data }, handleChange() { if (this.addForm.goods_cat.length !== 3) { this.addForm.goods_cat = [] } }, beforeTabLeave(activeName, oldActiveName) { if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) { this.$message.error('请先选择商品分类!') return false; } }, async tabClicked() { //证明访问的是动态参数面板 if (this.activeIndex === '1') { const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {params: {sel: 'many'}} ) res.data.forEach(item => { item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ') }) if (res.meta.status !== 200) { return this.$message.error('获取动态参数列表失败') } this.manyTableData = res.data } else if (this.activeIndex === '2') { const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {params: {sel: 'only'}} ) if (res.meta.status !== 200) { return this.$message.error('获取静态属性失败') } this.onlyTableData = res.data } }, // 处理图片预览效果 handlePreview(file){ this.previewPath = 'http://www.ysqorz.top:8888/api/private/v1/'+file.response.data.tmp_path console.log(file.response) this.previewVisible = true }, //删除图片前的操作 handleRemove(file){ //1.获取将要删除的图片的临时路径 const filePath = file.response.data.tmp_path //2.从 pics 数组中,找到这个图片对应的索引值 const i = this.addForm.pics.findIndex(x => x.pic === filePath ) //3.调用数组的 solice 方法,把图片信息对象,从 pics 数组中一出 this.addForm.pics.splice(i,1) }, //监听图片上传成功的事件 handleSuccess(response) { //1.拼接得到一个图片信息对象 const picInfo = {pic: response.data.tmp_path} //2.将图片信息对象,push到pics数组中 this.addForm.pics.push(picInfo) }, //添加商品 add(){ this.$refs.addFormRef.validate(async valid => { if (!valid) { return this.$message.error('请填写必要的表单项') } //执行添加的业务逻辑 const form = _.cloneDeep(this.addForm) form.goods_cat = form.goods_cat.join(',') //处理动态参数 this.manyTableData.forEach(item => { const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') } this.addForm.attrs.push(newInfo) }) //处理静态属性 this.onlyTableData.forEach(item => { const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals } this.addForm.attrs.push(newInfo) }) form.attrs = this.addForm.attrs console.log(form,this.addForm) const {data: res} = await this.$http.post('goods', form) console.log(res) if (res.meta.status !== 201) { this.$message.error('添加商品失败!') } this.$message.success('添加商品成功!') this.$router.push('/goods') }); } }, computed: { cateId() { if (this.addForm.goods_cat.length === 3) { return this.addForm.goods_cat[2]; } return null } } } </script> <style lang="less" scoped> .el-checkbox { margin: 0 5px 0 0 !important; } .btnAdd{ margin-top: 15px; } </style>
import React, { useState, useEffect } from "react"; import { View, Linking, ScrollView, FlatList } from "react-native"; import { getAuth, signOut } from "firebase/auth"; import { Layout, Button, TopNav, useTheme, themeColor, } from "react-native-rapi-ui"; import { Ionicons } from "@expo/vector-icons"; import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs'; import Topic from "../components/Topic"; const Tab = createMaterialTopTabNavigator(); function TopicTabs() { const { isDarkmode, setTheme } = useTheme(); return ( <Tab.Navigator screenOptions={{ tabBarLabelStyle: { fontSize: 10,fontWeight:"bold", color:isDarkmode?themeColor.white:themeColor.black }, tabBarItemStyle: { width: 80 }, tabBarScrollEnabled:true, tabBarStyle: { backgroundColor: isDarkmode?themeColor.dark:themeColor.white }, lazy:true }} > <Tab.Screen name="All" > {(props) => <Topic {...props} topic="general" />} </Tab.Screen> <Tab.Screen name="Tech" > {(props) => <Topic {...props} topic="technology" />} </Tab.Screen> <Tab.Screen name="Business" > {(props) => <Topic {...props} topic="business" />} </Tab.Screen> <Tab.Screen name="Entertainment" > {(props) => <Topic {...props} topic="entertainment" />} </Tab.Screen> <Tab.Screen name="Health" > {(props) => <Topic {...props} topic="health" />} </Tab.Screen> <Tab.Screen name="Science" > {(props) => <Topic {...props} topic="science" />} </Tab.Screen> <Tab.Screen name="Sports" > {(props) => <Topic {...props} topic="sports" />} </Tab.Screen> </Tab.Navigator> ); } export default function ({ navigation }) { const { isDarkmode, setTheme } = useTheme(); const auth = getAuth(); const [articles, setArticles] = useState([]); const [isLoading, setIsLoading] = useState(true); const [isError, setIsError] = useState(false); return ( <Layout> <TopNav style={{ elevation:0 }} middleContent="Home" leftContent={ <Ionicons name={isDarkmode ? "sunny" : "moon"} size={20} color={isDarkmode ? themeColor.white100 : themeColor.dark} /> } leftAction={() => { if (isDarkmode) { setTheme("light"); } else { setTheme("dark"); } }} rightContent={ <Ionicons name= "log-out" size={20} color="red" /> } rightAction={() => { signOut(auth); }} /> <TopicTabs /> </Layout> ); }
import { SlashCommandBuilder } from '@discordjs/builders' import axios from 'axios' import Vibrant from 'node-vibrant' import { MessageActionRow, MessageButton, MessageEmbed } from 'discord.js' import type { CommandInteraction, ColorResolvable } from 'discord.js' import type { Command } from '../../Types/Command' import type { Bot } from '../../Structures/Client' const Tweak: Command = { data: new SlashCommandBuilder() .setName('tweak') .setDescription('Search For A Jailbreak Tweak.') .addStringOption(option => option.setName('query') .setDescription('What to search for') .setRequired(true)), async run (Client: Bot, Interaction: CommandInteraction): Promise<void> { type CanisterResponse = { status: string date: string data: Array<{ identifier: string name: string description: string packageIcon: string author: string latestVersion: string depiction: string section: string price: string repository: {uri: string name: string} }> } Interaction.deferReply() let author = 'null' const { data } = await axios.get(`https://api.canister.me/v1/community/packages/search?query=${Interaction.options.getString('query')}&searchFields=identifier,name,author,maintainer&responseFields=identifier,name,description,packageIcon,repository.uri,repository.name,author,latestVersion,depiction,section,price`) const res = data as CanisterResponse try { if (res.data[0].name === undefined || res.data[0].name === null) return await Interaction.reply({ content: 'Your search returned no results!', ephemeral: true }) } catch { return await Interaction.reply({ content: 'Something went wrong. Try again', ephemeral: true }) } if (res.data[0].author === null || res.data[0].author === undefined) { author = 'Unknown' } else { author = res.data[0].author } let color = null if (res.data[0].packageIcon !== null) { if (res.data[0].packageIcon.startsWith('http:') || res.data[0].packageIcon.startsWith('https:')) { color = await Vibrant.from(res.data[0].packageIcon || 'https://repo.packix.com/api/Packages/60bfb71987ca62001c6585e6/icon/download?size=medium&hash=2').getPalette() color = color.Vibrant.hex } else { res.data[0].packageIcon = undefined } } if (color === null) { color = '#fccc04' } const row = new MessageActionRow() .addComponents( new MessageButton() .setStyle('LINK') .setURL(res.data[0].depiction || 'https://404.github.io/') .setEmoji('🔍') .setLabel('View Depiction'), new MessageButton() .setEmoji('931391570320715887') .setStyle('LINK') .setURL(`https://sharerepo.stkc.win/v2/?pkgman=cydia&repo=${res.data[0].repository.uri}`) .setLabel('Add Repo To Cydia'), new MessageButton() .setEmoji('931390952411660358') .setStyle('LINK') .setURL(`https://sharerepo.stkc.win/v2/?pkgman=sileo&repo=${res.data[0].repository.uri}`) .setLabel('Add Repo To Sileo'), new MessageButton() .setEmoji('931391570639478834') .setStyle('LINK') .setURL(`https://sharerepo.stkc.win/v2/?pkgman=zebra&repo=${res.data[0].repository.uri}`) .setLabel('Add Repo To Zebra'), new MessageButton() .setEmoji('931391570404573235') .setStyle('LINK') .setURL(`https://sharerepo.stkc.win/v2/?pkgman=installer&repo=${res.data[0].repository.uri}`) .setLabel('Add Repo To Installer') ) const embed = new MessageEmbed() .setColor(color as ColorResolvable) .setTitle(res.data[0].name) .setThumbnail(res.data[0].packageIcon || 'https://repo.packix.com/api/Packages/60bfb71987ca62001c6585e6/icon/download?size=medium&hash=2') .setDescription(res.data[0].description) .addField('Author', author, true) .addField('Version', res.data[0].latestVersion, true) .addField('Price', res.data[0].price, true) .addField('Repo', `[${res.data[0].repository.name}](${res.data[0].repository.uri})`, true) .addField('Bundle ID', res.data[0].identifier, true) .setFooter('Powered by Canister', 'https://cdn.discordapp.com/attachments/866173562120306699/931379303290142730/canister.png') await Interaction.editReply({ embeds: [embed], components: [row] }) } } module.exports = Tweak
.. _sm_install_license: ***************** Install a License ***************** Before running the Solution Manager for the first time, you have to configure the global license. The *Solution Manager Installation Guide* explains how to install its first license either :ref:`during the installation <sm-configure-local-license-installation>` or :ref:`afterwards <sm-install-license>`. To install a new global license on the Denodo License Manager, you can use the Denodo Solution Manager Administration Tool. Open the **Licenses** menu and then click **Install License**. .. figure:: license_menu.png :align: center :alt: Open Licenses menu and click on Install License :name: Open Licenses menu and click on Install License Licenses menu A dialog will open where you can drag and drop the license file. Alternatively, you can click in the drop area to browse the file system and select the license file. Then, click **Install** to start the license installation. .. figure:: license_dialog.png :align: center :alt: Install license dialog :name: Install license dialog Install license dialog If the new license has been successfully installed, the Solution Manager Administration Tool shows an informative message. Take into account that, at this moment, the previous global license has already been removed from the License Manager. On the other hand, if anything goes wrong during the license installation, an error message will warn you and the License Manager will keep its previous global license. Check Global License Information At any moment you can check the content of the current global license from the Solution Manager Administration Tool. Go to the **Licenses** menu and click **Global License Information**. A new tab will open with the features and the restrictions that apply to the Solution Manager itself and to each one of the available scenarios. .. figure:: global_license_information.png :align: center :alt: Global license information :name: Global license information Global license information
module.exports = function categorySchema(opts) { const { categoryController, Joi } = opts; const read = ({ fastify }) => { return { method: "GET", url: "/category/read", handler: categoryController.getCategories, }; }; const readByID = ({ fastify }) => { return { method: "GET", url: "/category/read/:id", handler: categoryController.getCategoryByID, }; }; const add = ({ fastify }) => { return { method: "POST", url: "/category/add", schema: { body: Joi.object().keys({ name: Joi.string().required(), description: Joi.string().allow(null, ""), display_title: Joi.string().allow(null, ""), image_url: Joi.string().allow(null, ""), }), }, preHandler: async (request, reply) => { await fastify.verifyAdminToken(request, reply); }, handler: categoryController.addCategory, }; }; const update = ({ fastify }) => { return { method: "PUT", url: "/category/update/:id", schema: { body: Joi.object().keys({ name: Joi.string().required(), display_title: Joi.string().allow(null, ""), description: Joi.string().allow(null, ""), image_url: Joi.string().allow(null, ""), }), }, preHandler: async (request, reply) => { await fastify.verifyAdminToken(request, reply); }, handler: categoryController.updateCategory, }; }; const deleteByID = ({ fastify }) => { return { method: "DELETE", url: "/category/delete/:id", preHandler: async (request, reply) => { await fastify.verifyAdminToken(request, reply); }, handler: categoryController.deleteCategoryByID, }; }; const searchCategory = ({ fastify }) => { return { method: "GET", url: "/category/search/:name", handler: categoryController.searchCategory, }; }; return { read, readByID, add, update, deleteByID, searchCategory }; };
package com.vg7.messenger.adapter; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.vg7.messenger.ChatActivity; import com.vg7.messenger.R; import com.vg7.messenger.model.UserModel; import com.vg7.messenger.utils.AndroidUtil; import com.vg7.messenger.utils.FirebaseUtil; import com.firebase.ui.firestore.FirestoreRecyclerAdapter; import com.firebase.ui.firestore.FirestoreRecyclerOptions; public class SearchUserRecyclerAdapter extends FirestoreRecyclerAdapter<UserModel, SearchUserRecyclerAdapter.UserModelViewHolder> { Context context; // Конструктор адаптера для пошуку користувачів public SearchUserRecyclerAdapter(@NonNull FirestoreRecyclerOptions<UserModel> options, Context context) { super(options); this.context = context; } // Метод для прив'язки даних до представлення RecyclerView @Override protected void onBindViewHolder(@NonNull UserModelViewHolder holder, int position, @NonNull UserModel model) { // Встановити ім'я та телефон користувача holder.usernameText.setText(model.getUsername()); holder.phoneText.setText(model.getPhone()); // Якщо це поточний користувач, ігнор if (model.getUserId().equals(FirebaseUtil.currentUserId())) { holder.itemView.setVisibility(View.GONE); return; } else { holder.itemView.setVisibility(View.VISIBLE); } // Отримати посилання на профільне зображення користувача getProfilePicUri(model.getUserId(), uri -> { if (uri != null) { AndroidUtil.setProfilePic(context, uri, holder.profilePic); } }); // Обробка натискання на елемент holder.itemView.setOnClickListener(v -> { // Перехід до активності чату Intent intent = new Intent(context, ChatActivity.class); AndroidUtil.passUserModelAsIntent(intent, model); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("source", "SearchUserActivity"); context.startActivity(intent); }); } // Метод для створення нового ViewHolder @NonNull @Override public UserModelViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Заповнити макет для рядка пошуку користувачів View view = LayoutInflater.from(context).inflate(R.layout.search_user_recycler_row, parent, false); return new UserModelViewHolder(view); } // Метод для отримання Uri профільного зображення користувача private void getProfilePicUri(String userId, ProfilePicCallback callback) { FirebaseUtil.getOtherProfilePicStorageRef(userId).getDownloadUrl() .addOnCompleteListener(t -> { if (t.isSuccessful()) { callback.onCallback(t.getResult()); } else { callback.onCallback(null); } }); } // Інтерфейс для обробки URI зображення профілю public interface ProfilePicCallback { // Метод зворотного виклику, який викликається з URI зображення профілю void onCallback(Uri uri); } // ViewHolder для рядків пошуку користувачів class UserModelViewHolder extends RecyclerView.ViewHolder { TextView usernameText; TextView phoneText; ImageView profilePic; // Конструктор ViewHolder public UserModelViewHolder(@NonNull View itemView) { super(itemView); // Знайти всі елементи макету usernameText = itemView.findViewById(R.id.user_name_text); phoneText = itemView.findViewById(R.id.phone_text); profilePic = itemView.findViewById(R.id.profile_pic_image_view); } } }
/***************************************************************************** * VLCMediaList.m: VLCKit.framework VLCMediaList implementation ***************************************************************************** * Copyright (C) 2007 Pierre d'Herbemont * Copyright (C) 2007 the VideoLAN team * $Id: 65522536d81ffcc311ffeb098e14c5efebada6e0 $ * * Authors: Pierre d'Herbemont <pdherbemont # videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #import "VLCMediaList.h" #import "VLCLibrary.h" #import "VLCEventManager.h" #import "VLCLibVLCBridging.h" #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc/vlc.h> #include <vlc/libvlc.h> /* Notification Messages */ NSString * VLCMediaListItemAdded = @"VLCMediaListItemAdded"; NSString * VLCMediaListItemDeleted = @"VLCMediaListItemDeleted"; // TODO: Documentation @interface VLCMediaList (Private) /* Initializers */ - (void)initInternalMediaList; /* Libvlc event bridges */ - (void)mediaListItemAdded:(NSArray *)args; - (void)mediaListItemRemoved:(NSNumber *)index; @end /* libvlc event callback */ static void HandleMediaListItemAdded(const libvlc_event_t * event, void * user_data) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; id self = user_data; [[VLCEventManager sharedManager] callOnMainThreadObject:self withMethod:@selector(mediaListItemAdded:) withArgumentAsObject:[NSArray arrayWithObject:[NSDictionary dictionaryWithObjectsAndKeys: [VLCMedia mediaWithLibVLCMediaDescriptor:event->u.media_list_item_added.item], @"media", [NSNumber numberWithInt:event->u.media_list_item_added.index], @"index", nil]]]; [pool release]; } static void HandleMediaListItemDeleted( const libvlc_event_t * event, void * user_data) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; id self = user_data; [[VLCEventManager sharedManager] callOnMainThreadObject:self withMethod:@selector(mediaListItemRemoved:) withArgumentAsObject:[NSNumber numberWithInt:event->u.media_list_item_deleted.index]]; [pool release]; } @implementation VLCMediaList - (id)init { if (self = [super init]) { // Create a new libvlc media list instance libvlc_exception_t p_e; libvlc_exception_init( &p_e ); p_mlist = libvlc_media_list_new( [VLCLibrary sharedInstance], &p_e ); catch_exception( &p_e ); // Initialize internals to defaults cachedMedia = [[NSMutableArray alloc] init]; delegate = flatAspect = hierarchicalAspect = hierarchicalNodeAspect = nil; [self initInternalMediaList]; } return self; } - (void)release { @synchronized(self) { if([self retainCount] <= 1) { /* We must make sure we won't receive new event after an upcoming dealloc * We also may receive a -retain in some event callback that may occcur * Before libvlc_event_detach. So this can't happen in dealloc */ libvlc_event_manager_t * p_em = libvlc_media_list_event_manager(p_mlist, NULL); libvlc_event_detach(p_em, libvlc_MediaListItemDeleted, HandleMediaListItemDeleted, self, NULL); libvlc_event_detach(p_em, libvlc_MediaListItemAdded, HandleMediaListItemAdded, self, NULL); } [super release]; } } - (void)dealloc { // Release allocated memory delegate = nil; libvlc_media_list_release( p_mlist ); [cachedMedia release]; [flatAspect release]; [hierarchicalAspect release]; [hierarchicalNodeAspect release]; [super dealloc]; } - (NSString *)description { NSMutableString * content = [NSMutableString string]; int i; for( i = 0; i < [self count]; i++) { [content appendFormat:@"%@\n", [self mediaAtIndex: i]]; } return [NSString stringWithFormat:@"<%@ %p> {\n%@}", [self className], self, content]; } - (void)lock { libvlc_media_list_lock( p_mlist ); } - (void)unlock { libvlc_media_list_unlock( p_mlist ); } - (int)addMedia:(VLCMedia *)media { int index = [self count]; [self insertMedia:media atIndex:index]; return index; } - (void)insertMedia:(VLCMedia *)media atIndex: (int)index { [media retain]; // Add it to the libvlc's medialist libvlc_exception_t p_e; libvlc_exception_init( &p_e ); libvlc_media_list_insert_media( p_mlist, [media libVLCMediaDescriptor], index, &p_e ); catch_exception( &p_e ); } - (void)removeMediaAtIndex:(int)index { [[self mediaAtIndex:index] release]; // Remove it from the libvlc's medialist libvlc_exception_t p_e; libvlc_exception_init( &p_e ); libvlc_media_list_remove_index( p_mlist, index, &p_e ); catch_exception( &p_e ); } - (VLCMedia *)mediaAtIndex:(int)index { return [cachedMedia objectAtIndex:index]; } - (int)indexOfMedia:(VLCMedia *)media { libvlc_exception_t p_e; libvlc_exception_init( &p_e ); int result = libvlc_media_list_index_of_item( p_mlist, [media libVLCMediaDescriptor], &p_e ); catch_exception( &p_e ); return result; } /* KVC Compliance: For the @"media" key */ - (int)countOfMedia { return [self count]; } - (id)objectInMediaAtIndex:(int)i { return [self mediaAtIndex:i]; } - (int)count { return [cachedMedia count]; } @synthesize delegate; - (BOOL)isReadOnly { libvlc_exception_t p_e; libvlc_exception_init( &p_e ); BOOL isReadOnly = libvlc_media_list_is_readonly( p_mlist ); catch_exception( &p_e ); return isReadOnly; } /* Media list aspect */ - (VLCMediaListAspect *)hierarchicalAspect { if( hierarchicalAspect ) return hierarchicalAspect; libvlc_media_list_view_t * p_mlv = libvlc_media_list_hierarchical_view( p_mlist, NULL ); hierarchicalAspect = [[VLCMediaListAspect mediaListAspectWithLibVLCMediaListView:p_mlv andMediaList:self] retain]; libvlc_media_list_view_release( p_mlv ); return hierarchicalAspect; } - (VLCMediaListAspect *)hierarchicalNodeAspect { if( hierarchicalNodeAspect ) return hierarchicalNodeAspect; libvlc_media_list_view_t * p_mlv = libvlc_media_list_hierarchical_node_view( p_mlist, NULL ); hierarchicalNodeAspect = [[VLCMediaListAspect mediaListAspectWithLibVLCMediaListView:p_mlv andMediaList:self] retain]; libvlc_media_list_view_release( p_mlv ); return hierarchicalNodeAspect; } - (VLCMediaListAspect *)flatAspect { if( flatAspect ) return flatAspect; libvlc_media_list_view_t * p_mlv = libvlc_media_list_flat_view( p_mlist, NULL ); flatAspect = [[VLCMediaListAspect mediaListAspectWithLibVLCMediaListView:p_mlv andMediaList:self] retain]; libvlc_media_list_view_release( p_mlv ); return flatAspect; } @end @implementation VLCMediaList (LibVLCBridging) + (id)mediaListWithLibVLCMediaList:(void *)p_new_mlist; { return [[[VLCMediaList alloc] initWithLibVLCMediaList:p_new_mlist] autorelease]; } - (id)initWithLibVLCMediaList:(void *)p_new_mlist; { if( self = [super init] ) { p_mlist = p_new_mlist; libvlc_media_list_retain( p_mlist ); libvlc_media_list_lock( p_mlist ); cachedMedia = [[NSMutableArray alloc] initWithCapacity:libvlc_media_list_count( p_mlist, NULL )]; int i, count = libvlc_media_list_count( p_mlist, NULL ); for( i = 0; i < count; i++ ) { libvlc_media_t * p_md = libvlc_media_list_item_at_index( p_mlist, i, NULL ); [cachedMedia addObject:[VLCMedia mediaWithLibVLCMediaDescriptor:p_md]]; libvlc_media_release(p_md); } [self initInternalMediaList]; libvlc_media_list_unlock(p_mlist); } return self; } - (void *)libVLCMediaList { return p_mlist; } @end @implementation VLCMediaList (Private) - (void)initInternalMediaList { // Add event callbacks libvlc_exception_t p_e; libvlc_exception_init( &p_e ); libvlc_event_manager_t * p_em = libvlc_media_list_event_manager( p_mlist, &p_e ); libvlc_event_attach( p_em, libvlc_MediaListItemAdded, HandleMediaListItemAdded, self, &p_e ); libvlc_event_attach( p_em, libvlc_MediaListItemDeleted, HandleMediaListItemDeleted, self, &p_e ); catch_exception( &p_e ); } - (void)mediaListItemAdded:(NSArray *)arrayOfArgs { /* We hope to receive index in a nide range, that could change one day */ int start = [[[arrayOfArgs objectAtIndex: 0] objectForKey:@"index"] intValue]; int end = [[[arrayOfArgs objectAtIndex: [arrayOfArgs count]-1] objectForKey:@"index"] intValue]; NSRange range = NSMakeRange(start, end-start); [self willChange:NSKeyValueChangeInsertion valuesAtIndexes:[NSIndexSet indexSetWithIndexesInRange:range] forKey:@"media"]; for( NSDictionary * args in arrayOfArgs ) { int index = [[args objectForKey:@"index"] intValue]; VLCMedia * media = [args objectForKey:@"media"]; /* Sanity check */ if( index && index > [cachedMedia count] ) index = [cachedMedia count]; [cachedMedia insertObject:media atIndex:index]; } [self didChange:NSKeyValueChangeInsertion valuesAtIndexes:[NSIndexSet indexSetWithIndexesInRange:range] forKey:@"media"]; // Post the notification // [[NSNotificationCenter defaultCenter] postNotificationName:VLCMediaListItemAdded // object:self // userInfo:args]; // Let the delegate know that the item was added // if (delegate && [delegate respondsToSelector:@selector(mediaList:mediaAdded:atIndex:)]) // [delegate mediaList:self mediaAdded:media atIndex:index]; } - (void)mediaListItemRemoved:(NSNumber *)index { [self willChange:NSKeyValueChangeInsertion valuesAtIndexes:[NSIndexSet indexSetWithIndex:[index intValue]] forKey:@"media"]; [cachedMedia removeObjectAtIndex:[index intValue]]; [self didChange:NSKeyValueChangeInsertion valuesAtIndexes:[NSIndexSet indexSetWithIndex:[index intValue]] forKey:@"media"]; // Post the notification [[NSNotificationCenter defaultCenter] postNotificationName:VLCMediaListItemDeleted object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys: index, @"index", nil]]; // Let the delegate know that the item is being removed if (delegate && [delegate respondsToSelector:@selector(mediaList:mediaRemovedAtIndex:)]) [delegate mediaList:self mediaRemovedAtIndex:[index intValue]]; } @end
library(shiny) library(tidyverse) library(leaflet) library(excelR) # Define UI for application that draws a histogram ui <- fluidPage( column(width = 6, leafletOutput(outputId = "plot",height = 700), h3(textOutput("compile_status"), align = "center"), div(style = "display: flex;", actionButton("backButton", "Back", width = '75px'), actionButton("nextButton", "Next", width = '75px'), #p("Proof the next individual") selectInput(inputId = "dropdown", label = NULL, choices = c())# choices = animal_list ) ), column(width = 6, excelOutput("table", height = 400)) ) # ui <- fluidPage( # fluidRow( # column(width = 6, # leafletOutput(outputId = "plot",height = 700), # h3(textOutput("compile_status"), align = "center"), # selectInput(inputId = "dropdown", label = NULL, # choices = animal_list), # actionButton("backButton", "Back"), # actionButton("nextButton", "Next") #p("Proof the next individual") # ), # column(width = 6, # excelOutput("table", height = 400)) # # )) # Define server logic required to draw a histogram server <- function(input, output) { #amwoData.sm <- read.csv('HMMmale.csv') amwoData.sm <- readRDS(here::here("classifier_integrated", "fac_primary_state_delineation.rds")) amwoData.sm <- amwoData.sm %>% mutate(animal_name = as.character(animal_name), x = long, y = lat, date = as.Date(time), point_state = primary_point_state, step_state = primary_step_state) %>% arrange(animal_name, time) animal_list <- amwoData.sm$animal_name %>% unique() updateSelectInput(inputId = "dropdown", choices = animal_list) individual_stepper <- reactiveValues() #These values can be defined w/in a reactive expression and will be remembered in other reactive expressions # individual_stepper$compiled <- 0 individual_stepper$count <- which(animal_list == animal_list[1]) individual_stepper$current_id <- animal_list[1] individual_stepper$amwoDataID <- filter(amwoData.sm, animal_name == animal_list[1]) selected_columns <- filter(amwoData.sm, animal_name == animal_list[1]) %>% dplyr::select("animal_name", "point_state", "step_state", "time") output$table <- excelTable(data = selected_columns, tableHeight = "800px") %>% renderExcel() getColor <- function(state) { sapply(state$point_state, function(states) { # individual_stepper$amwoDataID$point_state # Assignments # stationary- cyan # mig summer- pink # Migratory (fall)- pink # mig spring- green # foray loop (spring)- yellow # foray loop (summer)- yellow # foray loop (winter)- yellow # foray loop (fall)- yellow # dispersal (winter)- white # "Unknown- bugged frequent schedule"- orange if(states == "Stationary") { "blue" } else if(states == "Migratory (fall)") { "pink" } else if(states == "Migratory (summer)") { "red" } else if(states == "Migratory (spring)"){ "green" } else if(states == "Foray loop"){ "cadetblue" } else if(states == "Dispersal"){ "darkred" } else{ "orange" } }) } individual_stepper$icons <- awesomeIcons( icon = 'ios-close', iconColor = 'black', library = 'ion', markerColor = as.character(getColor(filter(amwoData.sm, animal_name == unique(amwoData.sm$animal_name)[1]))) ) #Reactive plotting: anything within this expression reruns every time input is modified output$plot <- renderLeaflet({ leaflet(options = leafletOptions(zoomControl = TRUE, minZoom = 1, maxZoom = 22, dragging = TRUE)) %>% addTiles() %>% # Default base mape addProviderTiles("Esri.WorldImagery") %>% # ortho image addProviderTiles(providers$Stamen.TonerLines) %>% # state lines and roads. #addProviderTiles(providers$Stamen.TonerLabels) %>% # add location and road labels addScaleBar() %>% addLegend("bottomright", pal = colorFactor(palette = c("darkred", "cadetblue", "cadetblue", "cadetblue", "cadetblue", "pink", "green", "red", "cyan", "orange"), #c("grey", "white", "black", "cyan", "yellow", "red", "green", "pink", "blue", "orange") domain = c("Stationary", "Migratory (spring)", "Migratory (summer)", "Foray loop (spring)", "Foray loop (summer)", "Migratory (fall)", "Foray loop (winter)", "Dispersal (winter)", "Foray loop (fall)", "Unknown- bugged frequent schedule")), values = individual_stepper$amwoDataID$point_state) %>% addAwesomeMarkers(lng=individual_stepper$amwoDataID$x, lat=individual_stepper$amwoDataID$y, icon=individual_stepper$icons, popup = individual_stepper$amwoDataID$date) %>% addPolylines(lng =individual_stepper$amwoDataID$x, lat = individual_stepper$amwoDataID$y, weight=3, color="red") })#end of reactive plotting #updating when go button is pressed observeEvent(input$nextButton, { if(which(animal_list == individual_stepper$current_id) == length(animal_list)){ #If we're on the last ID, stay on the last ID individual_stepper$current_id <- animal_list[which(animal_list == individual_stepper$current_id)] print(individual_stepper$current_id) } else { individual_stepper$current_id <- animal_list[which(animal_list == individual_stepper$current_id) + 1] print(individual_stepper$current_id) } updateSelectInput(inputId = "dropdown", selected = individual_stepper$current_id) individual_stepper$amwoDataID <- filter(amwoData.sm, animal_name == individual_stepper$current_id) selected_columns <- individual_stepper$amwoDataID %>% dplyr::select("animal_name", "point_state", "step_state", "time") output$table <- renderExcel(excelTable(data = selected_columns, tableHeight = "800px")) individual_stepper$icons <- awesomeIcons( icon = 'ios-close', iconColor = 'black', library = 'ion', markerColor = as.character(getColor(individual_stepper$amwoDataID)) ) }) observeEvent(input$backButton, { if(which(animal_list == individual_stepper$current_id) == 1){ #If we're on the last ID, stay on the last ID individual_stepper$current_id <- animal_list[which(animal_list == individual_stepper$current_id)] print(individual_stepper$current_id) } else { individual_stepper$current_id <- animal_list[which(animal_list == individual_stepper$current_id) - 1] print(individual_stepper$current_id) } updateSelectInput(inputId = "dropdown", selected = individual_stepper$current_id) individual_stepper$amwoDataID <- filter(amwoData.sm, animal_name == individual_stepper$current_id) selected_columns <- individual_stepper$amwoDataID %>% dplyr::select("animal_name", "point_state", "step_state", "time") output$table <- renderExcel(excelTable(data = selected_columns, tableHeight = "800px")) individual_stepper$icons <- awesomeIcons( icon = 'ios-close', iconColor = 'black', library = 'ion', markerColor = as.character(getColor(individual_stepper$amwoDataID)) ) }) observeEvent(input$dropdown, { individual_stepper$current_id <- input$dropdown print(individual_stepper$current_id) individual_stepper$amwoDataID <- filter(amwoData.sm, animal_name == individual_stepper$current_id) selected_columns <- individual_stepper$amwoDataID %>% dplyr::select("animal_name", "point_state", "step_state", "time") output$table <- renderExcel(excelTable(data = selected_columns, tableHeight = "800px")) individual_stepper$icons <- awesomeIcons( icon = 'ios-close', iconColor = 'black', library = 'ion', markerColor = as.character(getColor(individual_stepper$amwoDataID)) ) }) output$compile_status <- renderText({ individual_stepper$current_id }) }#end of server call # Run the application shinyApp(ui = ui, server = server)
@page "/Admin/Operations" @inject IOperationsService OperationsService @inject NavigationManager NavigationManager @inherits FragmentNavigationBase <link href="css/admin.css?v=@(DateTime.Now.ToString("MMddyyyyHHmmss"))" rel="stylesheet" /> <AuthorizeView Roles="Admin"> <Authorized Context="Auth"> <div id="wrapper" class="@(isClosed ? "toggled" : "")"> <div class="overlay"></div> <Andeanpm.Client.Components.Admin.Sidebar /> <div id="page-content-wrapper"> <button type="button" class="hamburger animated fadeInLeft @(isClosed ? "is-open" : "is-closed")" @onclick="OpenMenu" data-toggle="offcanvas"> <span class="hamb-top"></span> <span class="hamb-middle"></span> <span class="hamb-bottom"></span> </button> <div class="container"> <div class="row justify-content-end"> <div class="col-sm-12 col-lg-6"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="/Admin">Admin</a></li> <li class="breadcrumb-item active" aria-current="page">Operations</li> </ol> </nav> </div> </div> <div class="row"> <div class="col-sm-12 col-lg-12"> <div class="card"> <h5 class="card-header">@Module</h5> </div> <div class="card-body"> <div class="row"> <div class="col-sm-10"> <select @onchange="SelectedInput"> <option value="">Select Operation</option> <option value="CachiLaguna">Cachi Laguna</option> <option value="CerroRicoDeposits">Cerro Rico Deposits</option> <option value="ElAsiento">El Asiento</option> <option value="TatasiPortugalete">Tatasi Portugalete</option> <option value="Monserrat">Monserrat</option> <option value="SanPablo">San Pablo</option> <option value="RioBlanco">Rio Blanco</option> </select> </div> <br /> <br /> <div class="col-sm-12"> @if (operations.Count > 0) { <div class="table-responsive-sm"> <table class="table table-striped"> <thead> <tr> <th scope="col">Image</th> <th scope="col">Module</th> <th scope="col">Actions</th> </tr> </thead> <tbody> @foreach (var item in operations) { <tr> <td> <img src="@item.ImageLink" alt="" style="width:70px;" /> </td> <td>@item.Module</td> <td> <button type="button" class="btn btn-sm btn-outline-primary" @onclick="(() => Edit(item.Id))"><i class="fa-solid fa-pen-to-square"></i> Update</button> </td> </tr> } </tbody> </table> </div> <div class="row justify-content-end"> <div class="col-sm-12"> <Andeanpm.Client.Components.Admin.Pagination MetaData="MetaData" Spread="2" SelectedPage="SelectedPage" /> </div> </div> } else { <span> Loading products... </span> } </div> </div> </div> </div> </div> </div> </div> </div> </Authorized> <NotAuthorized> <Andeanpm.Client.Components.Admin.SignIn /> </NotAuthorized> </AuthorizeView> @code { [Parameter] public string Module { get; set; } = string.Empty; private bool isClosed { get; set; } = true; private List<Operation> operations { get; set; } = new(); private MetaData MetaData { get; set; } = new(); private PaginationParameters paginationParameters = new(); private int numeroPalabras = 15; private string aux { get; set; } = string.Empty; private bool cumpleCondicion = true; protected override async Task OnInitializedAsync() { await Get(); } private async Task SelectedPage(int page) { paginationParameters.PageNumber = page; await Get(); } private async Task Get() { var pagingResponse = await OperationsService.Get(paginationParameters, Module); operations = pagingResponse.Items; MetaData = pagingResponse.MetaData; } private void OpenMenu() { isClosed = !isClosed; } private async Task SelectedInput(ChangeEventArgs e) { if (!string.IsNullOrEmpty(e.Value.ToString())) { Module = e.Value.ToString(); await Get(); } else { operations = new(); } } private void Edit(int id) { NavigationManager.NavigateTo($"/Admin/Operation/Form/{Module}/{id}"); } }
#ifndef RAY_H #define RAY_H #include "vec3.h" /** * @file ray.h * @description representation of ray * * @author Rohit Nimkar * @verion 1.0 * @date 2023-06-18 * * @copyright Copyright 2023 Rohit Nimkar * @attention * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * opensource.org/licenses/BSD-3-Clause */ class ray { public: ray(){}; ray(const point3 &origin, const vec3 &direction): org(origin), dir(direction){}; point3 origin() const { return org;} vec3 direction() const { return dir;} point3 at(const double t) const { return org + dir * t;} private: point3 org; vec3 dir; }; #endif // !RAY_H
/* * str.c - String helper functions that don't need string.h or ctype.h * * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Author(s): David Cantrell <dcantrell@redhat.com> */ #include <stdio.h> #include <stdlib.h> #include "str.h" /** * Called by str2upper() or str2lower() to do the actual work. * * @param str String to convert. * @param lower Lower bound for the character range (e.g., a - z). * @param upper Upper bound for the character range (e.g., a - z). * @param shift Shift value (32 for lowercase, -32 for uppercase). * @return Pointer to str. */ char *str2case(char *str, char lower, char upper, int shift) { char *tmp; if (str == NULL) return NULL; /* man ascii(7) */ tmp = str; while (*tmp != '\0') { if (*tmp >= lower && *tmp <= upper) *tmp += shift; tmp++; } return str; } /** * Convert given string to uppercase. Modifies the argument in the caller's * stack. If you must ask simply "why?" for this function, it's so we don't * need toupper() and the same for loop all over the place. * * LIMITATIONS: Only deals with ASCII character set. * * @param str String to convert to uppercase. * @return Pointer to str. */ char *str2upper(char *str) { return str2case(str, 'a', 'z', -32); } /** * Convert given string to lowercase. Modifies the argument in the caller's * stack. If you must ask simply "why?" for this function, it's so we don't * need tolower() and the same for loop all over the place. * * LIMITATIONS: Only deals with ASCII character set. * * @param str String to convert to lowercase. * @return Pointer to str. */ char *str2lower(char *str) { return str2case(str, 'A', 'Z', 32); } /** * Pretty much an exact copy of index(3) from the C library. * @param str String to scan. * @param ch Character to scan for. * @return Position of ch in str, NULL if not found. */ char *strindex(char *str, int ch) { if (str == NULL) return NULL; do { if (*str == ch) return str; else str++; } while (*str != '\0'); return NULL; } /** * Return number of occurrences of a character in a string. * @param str String to scan. * @param ch Character to scan for. * @return Number of occurrences of ch in str. */ int strcount(char *str, int ch) { int retval = 0; char *tmp = str; if (tmp == NULL) return retval; do { if ((tmp = strindex(tmp, ch)) != NULL) { tmp++; retval++; } } while (tmp != NULL); return retval; } /* vim:set shiftwidth=4 softtabstop=4: */
function fcn_VD_plotCompareLongitudinalTireForce(ref_time,ref_lon_tire_force,... ref_sim_name,time,lon_tire_force,sim_name,varargin) %% fcn_VD_plotCompareLongitudinalTireForce % Purpose: % To plot longitudinal tire force(s) against time % % Inputs: % ref_time, time: A Nx1 vector of time [sec] % ref_lon_tire_force, lon_tire_force: A Nx2 matrix of longitudinal tire force(s) [N] % ref_sim_name, sim_name: Simulation name as string % % Returned Results: % A plot % % Author: Satya Prasad % Created: 2021_08_13 % %% Check input arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % _____ _ % |_ _| | | % | | _ __ _ __ _ _| |_ ___ % | | | '_ \| '_ \| | | | __/ __| % _| |_| | | | |_) | |_| | |_\__ \ % |_____|_| |_| .__/ \__,_|\__|___/ % | | % |_| % See: http://patorjk.com/software/taag/#p=display&f=Big&t=Inputs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Are there the right number of inputs? if 6>nargin || 7<nargin error('Incorrect number of input arguments') end %% Plots the inputs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % __ __ _ % | \/ | (_) % | \ / | __ _ _ _ __ % | |\/| |/ _` | | '_ \ % | | | | (_| | | | | | % |_| |_|\__,_|_|_| |_| % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if 7==nargin fig_num = varargin{1}; else fig = figure; fig_num = fig.Number; end max_value = max([ref_lon_tire_force, lon_tire_force], [], 'all'); min_value = min([ref_lon_tire_force, lon_tire_force], [], 'all'); offset = 0.1*(max_value-min_value); if 0 == offset offset = 25; end h_fig = figure(fig_num); set(h_fig, 'Name', 'fcn_VD_plotCompareLongitudinalTireForce'); width = 600; height = 400; right = 100; bottom = 400; set(gcf, 'position', [right, bottom, width, height]) clf subplot(2,1,1) plot(ref_time, ref_lon_tire_force(:,1), 'b', 'Linewidth', 1.2) hold on plot(time, lon_tire_force(:,1), 'r--', 'Linewidth', 1.2) grid on legend(['Front ' ref_sim_name], ['Front ' sim_name], 'Location', 'best',... 'Interpreter','Latex','Fontsize',13) set(gca,'Fontsize',13) ylabel('Longitudinal Tire Force $[N]$','Interpreter','Latex','Fontsize',11) ylim([min_value-offset max_value+offset]) subplot(2,1,2) plot(ref_time, ref_lon_tire_force(:,2), 'b', 'Linewidth', 1.2) hold on plot(time, lon_tire_force(:,2), 'r--', 'Linewidth', 1.2) grid on legend(['Rear ' ref_sim_name], ['Rear ' sim_name], 'Location', 'best',... 'Interpreter','Latex','Fontsize',13) set(gca,'Fontsize',13) ylabel('Longitudinal Tire Force $[N]$','Interpreter','Latex','Fontsize',11) xlabel('Time $[s]$','Interpreter','Latex','Fontsize',13) ylim([min_value-offset max_value+offset]) end
import { useState } from "react" import UseFetchHook from "../../common/hooks/UseFetchHook"; import { getFullDay } from "../../common/utils/utils"; import { Line } from 'react-chartjs-2'; import { weatherInfo } from "../../common/models/weathermodel"; interface IData { label: string; data: weatherInfo } function Stat() { const [latitude, setLatitude] = useState(8.9806); const [longtiude, setLongtude] = useState(38.7578); const [data, setData] = useState<weatherInfo>(); const [error, setError] = useState(null); const [graphData, setGraphData] = useState<IData[]>([]); const [filters, setFilters] = useState<string[]>([]); const query = () => { let searchFilters = filters; if (filters.length == 0) { searchFilters = ["temperature_2m_max"]; } let search: string = searchFilters.join(','); setGraphData([]) let url = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longtiude}&daily=${search}&timezone=auto`; fetch(url) .then(res => res.json()) .then(data => { setData(data) searchFilters.map((value: string, index: number) => { let dataset = { label: value.split('_').join(' '), data: data.daily[value] } setGraphData(prevData => [...prevData, dataset]) }) }) .catch((reason: any) => { setError(reason); }) } return ( <div className="h-full w-fit "> <h1 className="font-semibold text-3xl dark:text-gray-300">Stats</h1> <div className="grid grid-flow-row gap-5 md:gap-5"> <div className="w-full"> <div className="flex shadow-sm md:flex-row flex-col justify-center h-fit border-2 dark:border-0 dark:bg-black dark:shadow-black mt-5 md:w-[90%] lg:w-fit p-10 items-center gap-10 rounded-lg"> <div className="lg:ml-28 "> <input className="rounded-lg border-2 p-2 w-96" type="number" placeholder="latitude" onChange={(e) => setLatitude (parseInt(e.target.value))} /> </div> <div> <input className="rounded-lg border-2 p-2 w-96" type="number" placeholder="longtude" onChange={(e) => setLongtude (parseInt(e.target.value))} /> </div> <div className=""> <button className="border-2 rounded-lg p-2 px-6 bg-gray-100" onClick={query}>Search</button> </div> </div> <div className="mt-2 "> <button data-target="defaultModal" data-toggle="defaultModal" className="block shadow-sm w-full border-2 hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-black dark:text-white dark:border-0 dark:focus:outline-none" type="button"> <svg className="w-8 h-8 mx-auto" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"> <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" /> </svg> </button> </div> <div id="defaultModal" aria-hidden="true" className="hidden dark:bg-black block-foucs:block dark:text-white w-full mt-3 justify-center items-center rounded-lg shadow-xl p-2"> <div className="grid grid-cols-3"> <div className="flex justify-center items-center gap-2"> <label htmlFor="max_temp">Maximum Temperature</label> <input type="checkbox" name="" id="max_temp" onChange={(e) => { e.target.checked ? setFilters(prevFilter => [...prevFilter, "temperature_2m_max"]) : "" }} /> </div> <div className="flex justify-center items-center gap-2"> <label htmlFor="max_temp">Precipitation Sum</label> <input type="checkbox" name="" id="max_temp" onChange={(e) => { e.target.checked ? setFilters(prevFilter => [...prevFilter, "precipitation_sum"]) : "" }} /> </div> <div className="flex justify-center items-center gap-2"> <label htmlFor="max_temp">Maximum Wind Speed</label> <input type="checkbox" name="" id="max_temp" onChange={(e) => { e.target.checked ? setFilters(prevFilter => [...prevFilter, "windspeed_10m_max"]) : "" }} /> </div> </div> </div> </div> <div className="dark:bg-black"> {data && <Line className="w-full" datasetIdKey='id' data={{ labels: data.daily.time.map((value: any, index: number) => getFullDay(new Date(value).getDay())), datasets: graphData }} />} </div> </div> </div> ) } export default Stat
import { type Dispatch, type SetStateAction } from "react"; import { Input } from "./ui/input"; import { Label } from "./ui/label"; interface ImageUploaderProps { setValue: Dispatch<SetStateAction<File | undefined>>; isLoading: boolean; isUploading: boolean; label: string; } export default function ImageUploader({ setValue, isLoading, label, isUploading, }: ImageUploaderProps) { return ( <div className="flex flex-col gap-2"> <Label>{label}</Label> <Input type="file" className="cursor-pointer" disabled={isUploading || isLoading} onChange={(e) => { if (!e.target.files) return; setValue(e.target.files[0]); }} accept="image/png, image/jpeg, image/jpg" /> </div> ); }
<template> <div class="chat-container"> <!-- 顶部导航栏 --> <van-nav-bar class="app-nav-bar" title="小智同学" left-arrow @click-left="$router.back()" /> <!-- 消息展示区 --> <div class="msgList" ref="msgList"> <van-cell v-for="(msg, index) in msgList" :key="index" :title="msg" :class="{ my: !/^小智:/.test(msg) }" ></van-cell> <!-- <div v-for="(msg, index) in msgList" :key="index" :class="{chatBox:true, my: !/^小智:/.test(msg) }" > {{ msg }} </div> --> </div> <!-- 发送消息底部 --> <div class="sendMessage"> <van-field v-model="message" center placeholder="请输入消息" /> <van-button class="send-btn" size="small" type="info" @click="sendMsg" >发送</van-button > </div> </div> </template> <script> import io from "socket.io-client"; import { mapState } from "vuex"; import { setItem, getItem } from "@/utils/storage"; import { getProfile } from "@/api/user"; export default { name: "Chat", components: {}, props: {}, data() { return { message: "", socket: null, //socket实例 msgList: getItem("msgList") || [], photo: null, }; }, computed: { ...mapState(["user"]), }, created() { // this.getPhoto() this.socket = io("http://toutiao.itheima.net", { query: { token: this.user.token, }, transports: ["websocket"], }); // 当客户端与服务器建立连接成功,触发 connect 事件 this.socket.on("connect", () => { console.log("建立连接成功!"); }); // 当客户端与服务器断开连接,触发disconnect事件 this.socket.on("disconnect", () => { console.log("断开连接了!"); }); // 监听message事件,接收服务器发送的消息 this.socket.on("message", (data) => { console.log(data); // 将接收到的消息放入消息列表 this.msgList.push("小智:" + data.msg); }); }, mounted() { this.scrollBottom(); }, methods: { // 获取用户信息 async getPhoto() { // 获取用户头像信息 const { data: res } = await getProfile(); console.log(res); this.photo=res.data.photo }, // 处理发送消息 sendMsg() { // 请求发送消息 this.socket.emit("message", { msg: this.message, timestamp: Date.now(), }); // 把发送的请求推入信息列表 this.msgList.push(this.message); // 清空发送框内容 this.message = ""; }, // 聊天内容区域随聊天列表滚动 scrollBottom() { // 获取装聊天列表的容器 const msgList = this.$refs.msgList; console.log(msgList); // 列表距离顶端的距离=列表的最大移动距离 msgList.scrollTop = msgList.scrollHeight; }, }, watch: { msgList() { // 将聊天记录存储在本地 setItem("msgList", this.msgList); // 聊天内容区域随聊天列表滚动 this.$nextTick(() => { this.scrollBottom(); }); }, }, }; </script> <style lang="less" scoped> .sendMessage { display: flex; align-items: center; padding: 10px; position: fixed; right: 0; left: 0; bottom: 0; .send-btn { margin-left: 10px; width: 60px; } } /deep/.van-cell--center { line-height: unset !important; } .msgList { box-sizing: border-box; position: fixed; right: 0; left: 0; top: 46px; bottom: 56px; padding: 10px; overflow-y: auto; .van-cell { max-width: 70%; border-top-left-radius: 2em; border-top-right-radius: 2em; border-bottom-left-radius: 2em; border-bottom-right-radius: 2em; margin-bottom: 20px; line-height: 20px; } } .my { background-color: #41c94e; margin-right: 0; margin-left: 110px; text-align: right; } </style>
package com.commafeed.frontend.resource; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.annotation.Timed; import com.commafeed.CommaFeedApplication; import com.commafeed.CommaFeedConfiguration; import com.commafeed.CommaFeedConfiguration.ApplicationSettings; import com.commafeed.backend.dao.UserDAO; import com.commafeed.backend.dao.UserRoleDAO; import com.commafeed.backend.model.User; import com.commafeed.backend.model.UserRole; import com.commafeed.backend.model.UserRole.Role; import com.commafeed.backend.service.PasswordEncryptionService; import com.commafeed.backend.service.UserService; import com.commafeed.frontend.auth.SecurityCheck; import com.commafeed.frontend.model.UserModel; import com.commafeed.frontend.model.request.AdminSaveUserRequest; import com.commafeed.frontend.model.request.IDRequest; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import io.dropwizard.hibernate.UnitOfWork; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.inject.Inject; import jakarta.inject.Singleton; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; import lombok.RequiredArgsConstructor; @Path("/admin") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @RequiredArgsConstructor(onConstructor = @__({ @Inject })) @Singleton @Tag(name = "Admin") public class AdminREST { private final UserDAO userDAO; private final UserRoleDAO userRoleDAO; private final UserService userService; private final PasswordEncryptionService encryptionService; private final CommaFeedConfiguration config; private final MetricRegistry metrics; @Path("/user/save") @POST @UnitOfWork @Operation( summary = "Save or update a user", description = "Save or update a user. If the id is not specified, a new user will be created") @Timed public Response adminSaveUser(@Parameter(hidden = true) @SecurityCheck(Role.ADMIN) User user, @Parameter(required = true) AdminSaveUserRequest req) { Preconditions.checkNotNull(req); Preconditions.checkNotNull(req.getName()); Long id = req.getId(); if (id == null) { Preconditions.checkNotNull(req.getPassword()); Set<Role> roles = Sets.newHashSet(Role.USER); if (req.isAdmin()) { roles.add(Role.ADMIN); } try { userService.register(req.getName(), req.getPassword(), req.getEmail(), roles, true); } catch (Exception e) { return Response.status(Status.CONFLICT).entity(e.getMessage()).build(); } } else { if (req.getId().equals(user.getId()) && !req.isEnabled()) { return Response.status(Status.FORBIDDEN).entity("You cannot disable your own account.").build(); } User u = userDAO.findById(id); u.setName(req.getName()); if (StringUtils.isNotBlank(req.getPassword())) { u.setPassword(encryptionService.getEncryptedPassword(req.getPassword(), u.getSalt())); } u.setEmail(req.getEmail()); u.setDisabled(!req.isEnabled()); userDAO.saveOrUpdate(u); Set<Role> roles = userRoleDAO.findRoles(u); if (req.isAdmin() && !roles.contains(Role.ADMIN)) { userRoleDAO.saveOrUpdate(new UserRole(u, Role.ADMIN)); } else if (!req.isAdmin() && roles.contains(Role.ADMIN)) { if (CommaFeedApplication.USERNAME_ADMIN.equals(u.getName())) { return Response.status(Status.FORBIDDEN).entity("You cannot remove the admin role from the admin user.").build(); } for (UserRole userRole : userRoleDAO.findAll(u)) { if (userRole.getRole() == Role.ADMIN) { userRoleDAO.delete(userRole); } } } } return Response.ok().build(); } @Path("/user/get/{id}") @GET @UnitOfWork @Operation( summary = "Get user information", description = "Get user information", responses = { @ApiResponse(content = @Content(schema = @Schema(implementation = UserModel.class))) }) @Timed public Response adminGetUser(@Parameter(hidden = true) @SecurityCheck(Role.ADMIN) User user, @Parameter(description = "user id", required = true) @PathParam("id") Long id) { Preconditions.checkNotNull(id); User u = userDAO.findById(id); UserModel userModel = new UserModel(); userModel.setId(u.getId()); userModel.setName(u.getName()); userModel.setEmail(u.getEmail()); userModel.setEnabled(!u.isDisabled()); userModel.setAdmin(userRoleDAO.findAll(u).stream().anyMatch(r -> r.getRole() == Role.ADMIN)); return Response.ok(userModel).build(); } @Path("/user/getAll") @GET @UnitOfWork @Operation( summary = "Get all users", description = "Get all users", responses = { @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = UserModel.class)))) }) @Timed public Response adminGetUsers(@Parameter(hidden = true) @SecurityCheck(Role.ADMIN) User user) { Map<Long, UserModel> users = new HashMap<>(); for (UserRole role : userRoleDAO.findAll()) { User u = role.getUser(); Long key = u.getId(); UserModel userModel = users.get(key); if (userModel == null) { userModel = new UserModel(); userModel.setId(u.getId()); userModel.setName(u.getName()); userModel.setEmail(u.getEmail()); userModel.setEnabled(!u.isDisabled()); userModel.setCreated(u.getCreated()); userModel.setLastLogin(u.getLastLogin()); users.put(key, userModel); } if (role.getRole() == Role.ADMIN) { userModel.setAdmin(true); } } return Response.ok(users.values()).build(); } @Path("/user/delete") @POST @UnitOfWork @Operation(summary = "Delete a user", description = "Delete a user, and all his subscriptions") @Timed public Response adminDeleteUser(@Parameter(hidden = true) @SecurityCheck(Role.ADMIN) User user, @Parameter(required = true) IDRequest req) { Preconditions.checkNotNull(req); Preconditions.checkNotNull(req.getId()); User u = userDAO.findById(req.getId()); if (u == null) { return Response.status(Status.NOT_FOUND).build(); } if (user.getId().equals(u.getId())) { return Response.status(Status.FORBIDDEN).entity("You cannot delete your own user.").build(); } userService.unregister(u); return Response.ok().build(); } @Path("/settings") @GET @UnitOfWork @Operation( summary = "Retrieve application settings", description = "Retrieve application settings", responses = { @ApiResponse(content = @Content(schema = @Schema(implementation = ApplicationSettings.class))) }) @Timed public Response getApplicationSettings(@Parameter(hidden = true) @SecurityCheck(Role.ADMIN) User user) { return Response.ok(config.getApplicationSettings()).build(); } @Path("/metrics") @GET @UnitOfWork @Operation(summary = "Retrieve server metrics") @Timed public Response getMetrics(@Parameter(hidden = true) @SecurityCheck(Role.ADMIN) User user) { return Response.ok(metrics).build(); } }
#include "function_pointers.h" #include <stdio.h> /** * array_iterator - Executes a function on each element of an array * * @array: The array to iterate over * @size: The size of the array * @action: A pointer to the function to be executed on each element */ void array_iterator(int *array, size_t size, void (*action)(int)) { unsigned int i; if (array && action) { for (i = 0; i < size; i++) (*action)(array[i]); } }
<!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"> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <title>Home</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <h6><a class="navbar-brand" href="Fashion.html">Fashion</a></h6> <h6> <a class="navbar-brand" href="Categories.html">Categories</a></h6> <h6><a class="navbar-brand" href="#">Included Pages</a></h6> <h6><a class="navbar-brand" href="blog.html">Blog</a></h6> <h6><a class="navbar-brand" href="FAQ's.html">FAQS</a></h6> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav m-auto mb-2 mb-lg-0"> <li class="nav-item"> <h2> <a class="nav-link active" aria-current="page" href="#">CÖUTURE</a></h2> </li> </ul> <form class="d-flex"> <input class="form-control me-2" type="text" placeholder="Search"> <button class="btn btn-dark" type="button">Search</button> </form> </div> </div> </nav> <section> <div class="container-fluid" style="align-items: centre;"> <div id="carouselExampleDark" class="carousel carousel-dark slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleDark" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleDark" data-bs-slide-to="1" aria-label="Slide 2"></button> </div> <div class="carousel-inner"> <div class="carousel-item active" data-bs-interval="10000"> <img src="/prj/img/s1 (1).webp" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h1 class="heading">Feel Strong Feel Fashionable</h1> <p class="para">Fashion is not something that exsist in dresses only. Fashion is in the sky, in the street, fashion has to do with ideas, the way we live, what is happening.</p> <button type="button" class="btn btn-dark">SHOP NOW</button> </div> </div> <div class="carousel-item" data-bs-interval="2000"> <img src="/prj/img/s2_05872cda-ab7b-4496-b07c-0cad752b95f4.webp" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h1 class="heading">Feel Pretty Feel Classy</h1> <p class="para">Fashion is not something that exsist in dresses only. Fashion is in the sky, in the street, fashion has to do with ideas, the way we live, what is happening.</p> <a href="#" class="btn btn-dark" >SHOP NOW</a> </div> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleDark" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleDark" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </div> </section> <section style="padding-top: 50px;"> <p class="para2">CÖUTURE </p> <h4 class="heading2">Our Collection</h4> </section> <section class="card_section"> <div class="card-group" style="gap: 20px;"> <div class="card"> <img src="/prj/img/c1.webp" class="card-img-top" alt="remote img"> </div> <div class="card"> <img src="/prj/img/c3.webp" class="card-img-top" alt="remote img"> </div> <div class="card"> <img src="/prj/img/c1.webp" class="card-img-top" alt="remote img"> </div> <div class="card"> <img src="/prj/img/c4.webp" class="card-img-top" alt="remote img"> </div> </div> </section> <br> <section style="padding-top: 50px;"> <p class="para2">CÖUTURE </p> <h4 class="heading2">Trending Products</h4> <p class="para3">New Arrivals </p> </section> <section class="card_section"> <div class="card-group" style="gap: 20px;"> <div class="card"> <img src="/prj/img/p1.webp" class="card-img-top" alt="remote img"> <div class="card-body">Ruffled Tshirt</div> <div class="price">$18.00</div> <p><button>Add to Cart</button></p> </div> <div class="card"> <img src="/prj/img/p2.webp" class="card-img-top" alt="remote img"> <div class="card-body">Denim Jackets</div> <div class="price">$22.00</div> <p><button>Add to Cart</button></p> </div> <div class="card"> <img src="/prj/img/p3.webp" class="card-img-top" alt="remote img"> <div class="card-body">Date Night Outfit</div> <div class="price">$18.00</div> <p><button>Add to Cart</button></p> </div> <div class="card"> <img src="/prj/img/p4.webp" class="card-img-top" alt="remote img"> <div class="card-body">Winter Fashion</div> <div class="price">$18.00</div> <p><button>Add to Cart</button></p> </div> </div> <br> <div class="btn2"> <a href="#" class="btn btn-dark" >VIEW ALL</a> </div> </section> <br> <div class="container"> <div class="row image-row"> <div class="col-lg-4 first"> <img src="/prj/img/3p1.webp" alt="remote" height="520px" width="450px"> </div> <div class="col-lg-4 second"> <p class="para2">Take An Extra </p> <br> <h4 class="heading2">50% OFF</h4> <br> <p class="para2">Everything </p> <br> <p class="para3">Lorem Ipsum is simply dummy text of the typesetting industry standard dummy text ever since the 1500s.</p> <br> <center><a href="#" class="btn btn-dark" >VIEW MORE</a></center> </div> <div class="col-lg-4 third"> <img src="/prj/img/3p2.webp" alt="remote" height="520px" width="450px"> </div> </div> </div> <br> <div class="row"> <div class="col text-center"> <img src="/prj/img/brand.png" alt="brand" style="width:100%"> </div> <div class="col text-center"> <img src="/prj/img/natural.webp" alt="brand" style="width:100%"> </div> <div class="col text-center"> <img src="/prj/img/smile.logo.webp" alt="brand" style="width:100%"> </div> <div class="col text-center"> <img src="/prj/img/butterfly.logo.webp" alt="brand" style="width:100%"> </div> <div class="col text-center"> <img src="/prj/img/branding.webp" alt="brand" style="width:100%"> </div> <div class="col text-center"> <img src="/prj/img/brand.png" alt="brand" style="width:100%"> </div> </div> <br> <section> <div id="carouselExampleCaptions" class="carousel carousel-dark slide" data-bs-ride="false"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <div class="card-group"> <div class="card"> <img src="/prj/img/cart1.webp" class="card-img-top" alt="remote" height="450px" width="100px"> <div class="card-body"> <h5 class="card-title">Long Tshirt</h5> <p class="card-text">$22.00</p> <p><button>Add to Cart</button></p> </div> </div> <div class="card"> <img src="/prj/img/cart2.webp" class="card-img-top" alt="remote" height="450px" width="100px"> <div class="card-body"> <h5 class="card-title">Date Night Outfit</h5> <p class="card-text">$20.00</p> <p><button>Add to Cart</button></p> </div> </div> <div class="card"> <img src="/prj/img/p4.webp" class="card-img-top" alt="remote" height="450px" width="100px"> <div class="card-body"> <h5 class="card-title">Gym Wear</h5> <p class="card-text">$23.00</p> <p><button>Add to Cart</button></p> </div> </div> </div> </div> <div class="carousel-item"> <div class="card-group"> <div class="card"> <img src="/prj/img/cart4.webp" class="card-img-top" alt="remote" height="450px" width="100px"> <div class="card-body"> <h5 class="card-title">Gown</h5> <p class="card-text">$15.00</p> <p><button>Add to Cart</button></p> </div> </div> <div class="card"> <img src="/prj/img/cart3.webp" class="card-img-top" alt="remote" height="450px" width="100px"> <div class="card-body"> <h5 class="card-title">Jump Suit</h5> <p class="card-text">$21.00</p> <p><button>Add to Cart</button></p> </div> </div> <div class="card"> <img src="/prj/img/p1.webp" class="card-img-top" alt="remote" height="450px" width="100px"> <div class="card-body"> <h5 class="card-title">Tank Top</h5> <p class="card-text">$18.00</p> <p><button>Add to Cart</button></p> </div> </div> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </section> <br> <video src="/prj/video/sewing_-_108009 (720p).mp4" autoplay loop width="100%"></video> <section> <div class="row"> <div class="col-sm-6"> <div class="card"> <div class="card-body"> <img src="/prj/img/banner1.webp" class="card-img-top" alt="remote" height="350px" width="100px"> <p class="card-text">New One</p> <h4 class="card-title"> Women Collection</h4> <a href="#" class="btn btn-dark">SHOP NOW</a> </div> </div> </div> <div class="col-sm-6"> <div class="card"> <div class="card-body"> <img src="/prj/img/banner2.webp" class="card-img-top" alt="remote" height="350px" width="100px"> <p class="card-text">New One</p> <h4 class="card-title"> Men Collection</h4> <a href="#" class="btn btn-dark" >SHOP NOW</a> </div> </div> </div> </div> </section> <br> <section style="padding-top: 50px;"> <p class="para2">FEATURED </p> <h4 class="heading2">Trending Now</h4> </section> <br> <section> <div class="row"> <div class="col-sm-6"> <div class="card"> <div class="card-body-cart"> <img src="/prj/img/cart3.webp" class="card-img-top" alt="remote" height="650px" width="300px"> </div> </div> </div> <div class="col-lg-6 bg-grey"> <div class="p-5"> <h3 class="fw-bold mb-5 mt-2 pt-1">Jump Suit</h3> <hr class="my-4"> <div class="d-flex justify-content-between mb-4"> <h6 class="text-uppercase">Vendor : Couture</h6> <h6 class="text-uppercase">Product Type : fashion</h6> <h5>€ 21.00</h5> </div> <h5 class="text-uppercase mb-3">Shipping</h5> <div class="mb-4 pb-2"> <select class="select"> <option value="1">Standard-Delivery- €5.00</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> </select> </div> <h5 class="text-uppercase mb-3">Give code</h5> <div class="mb-5"> <div class="form-outline"> <input type="text" id="form3Examplea2" class="form-control form-control-lg" /> <label class="form-label" for="form3Examplea2">Enter your pin code</label> </div> </div> <hr class="my-4"> <div class="d-flex justify-content-between mb-5"> <h5 class="text-uppercase">Total price</h5> <h5>€ 26.00</h5> </div> <button type="button" class="btn btn-dark active">ADD TO CART</button> <button type="button" class="btn btn-dark active">BUY IT NOW</button> <hr> </div> </div> </div> </section> <br> <section> <center><a href="#" class="btn btn-dark" >DISCRIPTIONS</a> <a href="#" class="btn btn-dark" >REVIEWS</a> <a href="#" class="btn btn-dark" >ANY QUESTIONS?</a></center> </section> <section style="padding-top: 50px;"> <p class="para2" >Faded short sleeves t-shirt with high neckline. Soft and stretchy material for a comfortable fit. Accessorize with a straw hat and you're ready for summer! </p> <h6 class="heading3">Sample Unordered List</h6> <ul class="unordered-list" style="list-style-type:circle; "> <li class="list">Comodous in tempor ullamcorper miaculis</li> <li class="list">Pellentesque vitae neque mollis urna mattis laoreet.</li> <li class="list">Divamus sit amet purus justo.</li> <li class="list">Proin molestie egestas orci ac suscipit risus posuere loremou.</li> </ul> <br> </section> <section> <h6 class="heading3">Sample Ordered List</h6> <ol class="ordered-list" type="1"> <li class="list">Comodous in tempor ullamcorper miaculis</li> <li class="list">Pellentesque vitae neque mollis urna mattis laoreet.</li> <li class="list">Divamus sit amet purus justo.</li> <li class="list">Proin molestie egestas orci ac suscipit risus posuere loremous</li> </ol> <br> <h6 class="heading3">Sample Paragraph Text</h6> <p class="para4" >Faded short sleeves t-shirt with high neckline. Soft and stretchy material for a comfortable fit. Accessorize with a straw hat and you're ready for summer!Faded short sleeves t-shirt with high neckline. Soft and stretchy material for a comfortable fit. Accessorize with a straw hat and you're ready for summe! </p> </section> <br> <section style="padding-top: 50px;"> <p class="para2">CÖUTURE </p> <h4 class="heading2">From The Blog</h4> </section> <section> <div class="row"> <div class="col-sm-4"> <div class="card"> <div class="card-body"> <img src="/prj/img/ck1.webp" class="card-img-top" alt="remote" height="350px" width="100px"> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> <h5 class="heading3">Lorem ipsum</h5> </div> </div> </div> <div class="col-sm-4"> <div class="card"> <div class="card-body"> <img src="/prj/img/ck2.webp" class="card-img-top" alt="remote" height="350px" width="100px"> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> <h5 class="heading3"> Iste blanditiis</h5> </div> </div> </div> <div class="col-sm-4"> <div class="card"> <div class="card-body"> <img src="/prj/img/ck3.webp" class="card-img-top" alt="remote" height="350px" width="100px"> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> <h5 class="heading3"> quia consequuntur </h5> </div> </div> </div> <div class="col-sm-4"> <div class="card"> <div class="card-body"> <img src="/prj/img/ck4.webp" class="card-img-top" alt="remote" height="350px" width="100px"> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> <h5 class="heading3"> quia consequuntur </h5> </div> </div> </div> <div class="col-sm-4"> <div class="card"> <div class="card-body"> <img src="/prj/img/5.webp" class="card-img-top" alt="remote" height="350px" width="100px"> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> <h5 class="heading3"> quia consequuntur </h5> </div> </div> </div> <div class="col-sm-4"> <div class="card"> <div class="card-body"> <img src="/prj/img/ck6.webp" class="card-img-top" alt="remote" height="350px" width="100px"> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> <h5 class="heading3"> quia consequuntur </h5> </div> </div> </div> </div> </section> <br> <footer> <div class="container"> <div class="row"> <div class="col-xl-3 col-lg-3 col-md-6"> <div> <h3>CÖUTURE</h3> <p class="mb-30 footer-desc">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text.</p> <span class="mt-4"> <i class="fa fa-facebook" aria-hidden="true"></i> <i class="fa fa-instagram" aria-hidden="true"></i> <i class="fa fa-snapchat" aria-hidden="true"></i> <i class="fa fa-vimeo" aria-hidden="true"></i> </span> </div> </div> <div class="col-xl-2 offset-xl-1 col-lg-2 col-md-6"> <div class=""> <h5>Your Account</h5> <ul class="list-unstyled"> <li> <a href="#" class="text-decoration-none text-reset">Address</a> </li> <li> <a href="#" class="text-decoration-none text-reset">Personal Info</a> </li> <li> <a href="#" class="text-decoration-none text-reset">Orders</a> </li> <li> <a href="#" class="text-decoration-none text-reset">Credit Slips</a> </li> <li> <a href="#" class="text-decoration-none text-reset">Wishlist</a> </li> </ul> </div> </div> <div class="col-xl-2 col-lg-2 col-md-6"> <div> <h5>Our Company</h5> <ul class="list-unstyled"> <li> <a href="#" class="text-decoration-none text-reset">About Us</a> </li> <li> <a href="#" class="text-decoration-none text-reset">Contact Us</a> </li> <li> <a href="#" class="text-decoration-none text-reset">FAQs</a> </li> <li> <a href="#" class="text-decoration-none text-reset">Shipping & Return</a> </li> <li> <a href="#" class="text-decoration-none text-reset">Sitemap</a> </li> </ul> </div> </div> <div class="col-xl-2 col-lg-2 col-md-6"> <div> <h5>Product</h5> <ul class="list-unstyled"> <li> <a href="#" class="text-decoration-none text-reset">New Product</a> </li> <li> <a href="#" class="text-decoration-none text-reset">Specials</a> </li> <li> <a href="#" class="text-decoration-none text-reset">Price Drop</a> </li> <li> <a href="#" class="text-decoration-none text-reset">Best Product</a> </li> <li> <a href="#" class="text-decoration-none text-reset">Delivery</a> </li> </ul> </div> </div> <div class="col-xl-2 col-lg-3 col-md-6"> <div> <h5>Newsletter</h5> <div> <label for="Newsletter" class="form-label">Subscribe to our Newsletter and Get 10% Off on every product</label> <input type="text" class="form-control" Placeholder="Your Email"> <button class="btn btn-dark mt-3">Subscribe</button> </div> </div> </div> </div> </div> </footer> </body> </html>
package br.com.codeflix.catalog.admin.application.genre.retrieve.get; import br.com.codeflix.catalog.admin.domain.exceptions.NotFoundException; import br.com.codeflix.catalog.admin.domain.genre.Genre; import br.com.codeflix.catalog.admin.domain.genre.GenreGateway; import br.com.codeflix.catalog.admin.domain.genre.GenreID; import java.util.Objects; public class DefaultGetGenreByIdUseCase extends GetGenreByIdUseCase { private final GenreGateway genreGateway; public DefaultGetGenreByIdUseCase(final GenreGateway genreGateway) { this.genreGateway = Objects.requireNonNull(genreGateway); } @Override public GenreOutput execute(String id) { final var genreId = GenreID.from(id); return this.genreGateway.findById(genreId) .map(GenreOutput::from) .orElseThrow(() -> NotFoundException.with(Genre.class, genreId)); } }
using deftq.BuildingBlocks.Exceptions; using deftq.Pieceworks.Application.GetDocument; using deftq.Pieceworks.Domain.projectDocument; using deftq.Pieceworks.Infrastructure; using deftq.Pieceworks.Infrastructure.projectDocument; using Xunit; namespace deftq.Pieceworks.Test.Application.GetDocument { public class GetDocumentQueryTests { [Fact] public Task Should_Throw_NotFoundException() { var repository = new ProjectDocumentInMemoryRepository(); var fileStorage = new InMemoryFileStorage(); var query = GetDocumentQuery.Create(Any.ProjectDocumentId()); var handler = new GetDocumentQueryHandler(repository, fileStorage); return Assert.ThrowsAsync<NotFoundException>( async () => await handler.Handle(query, CancellationToken.None)); } [Fact] public async Task Should_Return_File() { var repository = new ProjectDocumentInMemoryRepository(); var fileStorage = new InMemoryFileStorage(); IFileReference reference; using (var stream = new MemoryStream(new byte[] {1,2,3,4,5})) { reference = await fileStorage.StoreFileAsync(Any.ProjectId(), Any.ProjectDocumentId(), Any.ProjectDocumentName(), stream, CancellationToken.None); } var document = Any.ProjectDocument(reference); await repository.Add(document); var query = GetDocumentQuery.Create(document.ProjectDocumentId); var handler = new GetDocumentQueryHandler(repository, fileStorage); var response = await handler.Handle(query, CancellationToken.None); Assert.Equal(document.ProjectDocumentName.Value, response.Filename); Assert.Equal(new byte[] {1,2,3,4,5}, response.GetBuffer()); } } }
package uk.ac.ebi.pride.gui.component.peptide; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.bushe.swing.event.EventSubscriber; import uk.ac.ebi.pride.data.controller.DataAccessController; import uk.ac.ebi.pride.data.controller.DataAccessException; import uk.ac.ebi.pride.gui.GUIUtilities; import uk.ac.ebi.pride.gui.component.PrideInspectorTabPane; import uk.ac.ebi.pride.gui.component.exception.ThrowableEntry; import uk.ac.ebi.pride.gui.component.message.MessageType; import uk.ac.ebi.pride.gui.component.mzdata.MzDataTabPane; import uk.ac.ebi.pride.gui.component.startup.ControllerContentPane; import uk.ac.ebi.pride.gui.event.container.ExpandPanelEvent; import uk.ac.ebi.pride.gui.task.TaskEvent; import javax.swing.*; import java.awt.*; /** * PeptideTabPane provides a peptide centric view to all peptides in one experiment. * <p/> * User: rwang * Date: 03-Sep-2010 * Time: 10:46:06 */ public class PeptideTabPane extends PrideInspectorTabPane { private static final Logger logger = Logger.getLogger(MzDataTabPane.class.getName()); /** * title */ private static final String PEPTIDE_TITLE = "Peptide"; /** * resize weight for inner split pane */ private static final double INNER_SPLIT_PANE_RESIZE_WEIGHT = 0.6; /** * resize weight for outer split pane */ private static final double OUTER_SPLIT_PANE_RESIZE_WEIGHT = 0.6; /** * the size of the divider for split pane */ private static final int DIVIDER_SIZE = 5; /** * Inner split pane contains peptideDescPane and peptidePTMPane */ private JSplitPane innerSplitPane; /** * Outer split pane contains inner split pane and spectrumViewPane */ private JSplitPane outterSplitPane; /** * Display peptide details */ private PeptideDescriptionPane peptideDescPane; /** * Display ptm details */ private PeptidePTMPane peptidePTMPane; /** * Visualize spectrum and protein sequence */ private PeptideVizPane vizTabPane; /** * Subscribe to expand peptide panel */ private ExpandPeptidePanelSubscriber expandPeptidePanelSubscriber; /** * Constructor * * @param controller data access controller * @param parentComp parent container */ public PeptideTabPane(DataAccessController controller, JComponent parentComp) { super(controller, parentComp); } /** * Setup the main display main */ @Override protected void setupMainPane() { // add event subscriber expandPeptidePanelSubscriber = new ExpandPeptidePanelSubscriber(); getContainerEventService().subscribe(ExpandPanelEvent.class, expandPeptidePanelSubscriber); // set properties for IdentTabPane this.setLayout(new BorderLayout()); // title for the tab pane try { int numberOfPeptides = controller.getNumberOfPeptides(); String title = " (" + numberOfPeptides + ")"; this.setTitle(PEPTIDE_TITLE + title); } catch (DataAccessException dex) { String msg = String.format("%s failed on : %s", this, dex); logger.log(Level.ERROR, msg, dex); appContext.addThrowableEntry(new ThrowableEntry(MessageType.ERROR, msg, dex)); } // set the final icon this.setIcon(GUIUtilities.loadIcon(appContext.getProperty("peptide.tab.icon.small"))); // set the loading icon this.setLoadingIcon(GUIUtilities.loadIcon(appContext.getProperty("peptide.tab.loading.icon.small"))); } /** * Add the rest of components */ @Override protected void addComponents() { // inner split pane innerSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); innerSplitPane.setBorder(BorderFactory.createEmptyBorder()); innerSplitPane.setOneTouchExpandable(false); innerSplitPane.setDividerSize(DIVIDER_SIZE); innerSplitPane.setResizeWeight(INNER_SPLIT_PANE_RESIZE_WEIGHT); // outer split pane outterSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); outterSplitPane.setBorder(BorderFactory.createEmptyBorder()); outterSplitPane.setOneTouchExpandable(false); outterSplitPane.setDividerSize(DIVIDER_SIZE); outterSplitPane.setResizeWeight(OUTER_SPLIT_PANE_RESIZE_WEIGHT); // protein identification selection pane peptideDescPane = new PeptideDescriptionPane(controller); outterSplitPane.setTopComponent(peptideDescPane); // peptide selection pane peptidePTMPane = new PeptidePTMPane(controller); innerSplitPane.setTopComponent(peptidePTMPane); // Spectrum view pane vizTabPane = new PeptideVizPane(controller, this); vizTabPane.setMinimumSize(new Dimension(200, 200)); innerSplitPane.setBottomComponent(vizTabPane); outterSplitPane.setBottomComponent(innerSplitPane); this.add(outterSplitPane, BorderLayout.CENTER); // subscribe to local event bus peptidePTMPane.subscribeToEventBus(null); vizTabPane.subscribeToEventBus(null); } /** * Get a reference to peptide pane * * @return PeptideDescriptionPane peptide pane */ public PeptideDescriptionPane getPeptidePane() { return peptideDescPane; } @Override public void started(TaskEvent event) { showIcon(getLoadingIcon()); } @Override public void finished(TaskEvent event) { showIcon(getIcon()); } /** * Show a different icon if the parent component is not null and an instance of DataContentDisplayPane * * @param icon icon to show */ private void showIcon(Icon icon) { if (parentComponent != null && parentComponent instanceof ControllerContentPane && icon != null) { ControllerContentPane contentPane = (ControllerContentPane) parentComponent; contentPane.setTabIcon(contentPane.getPeptideTabIndex(), icon); } } /** * Event handler for expanding protein panel */ private class ExpandPeptidePanelSubscriber implements EventSubscriber<ExpandPanelEvent> { @Override public void onEvent(ExpandPanelEvent event) { boolean visible = innerSplitPane.isVisible(); innerSplitPane.setVisible(!visible); outterSplitPane.setDividerSize(visible ? 0 : DIVIDER_SIZE); outterSplitPane.resetToPreferredSizes(); } } }
import { useState, useContext } from 'react'; import { Navigate } from 'react-router-dom'; import { UserContext } from '../../context/UserContext'; import { CartContext } from '../../context/CartContext'; import DispatchCheckout from './DispatchCheckout'; import getStepContent from '../../helpers/getStepContent'; import validateAddressForm from '../../helpers/validateAddressForm'; import validatePaymentForm from '../../helpers/validatePaymentForm'; import Box from '@mui/material/Box'; import Container from '@mui/material/Container'; import Paper from '@mui/material/Paper'; import Stepper from '@mui/material/Stepper'; import Step from '@mui/material/Step'; import StepLabel from '@mui/material/StepLabel'; import Button from '@mui/material/Button'; import Typography from '@mui/material/Typography'; const steps = ['Dirección de envío', 'Detalles del pago', 'Chequeo de datos']; const Checkout = () => { const [activeStep, setActiveStep] = useState(0); const { userData, setErrors, resetUserData } = useContext(UserContext); const { cart, resetCart, totalCartPrice, amountOfItemsInCart } = useContext(CartContext); if (amountOfItemsInCart() === 0 && activeStep !== steps.length) { return <Navigate to='/' />; } const handleNext = () => { const formIsValid = activeStep === 0 ? validateAddressForm(userData, setErrors) : validatePaymentForm(userData, setErrors); if (formIsValid) setActiveStep(activeStep + 1); }; const handleBack = () => { setErrors({}); setActiveStep(activeStep - 1); }; return ( <> <Container component='main' maxWidth='sm' className='animate__animated animate__fadeIn' > <Paper sx={{ mt: { xs: 3, md: 6 }, p: { xs: 2, md: 3 } }} elevation={12} > <Typography component='h1' variant='h4' align='center'> Checkout </Typography> <Stepper activeStep={activeStep} sx={{ pt: 3, pb: 5, display: { xs: 'none', sm: 'flex' } }} > {steps.map((label) => ( <Step key={label}> <StepLabel>{label}</StepLabel> </Step> ))} </Stepper> <> {activeStep === steps.length ? ( <DispatchCheckout userData={userData} resetUserData={resetUserData} cart={cart} resetCart={resetCart} totalCartPrice={totalCartPrice} /> ) : ( <> {getStepContent(activeStep)} <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}> {activeStep !== 0 && ( <Button onClick={handleBack} sx={{ mt: 3, ml: 1 }}> Volver </Button> )} <Button variant='contained' onClick={handleNext} sx={{ mt: 3, ml: 1 }} > {activeStep === steps.length - 1 ? 'Terminar mi compra' : 'Siguiente'} </Button> </Box> </> )} </> </Paper> </Container> </> ); }; export default Checkout;
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:rive/rive.dart'; import 'package:thetiptop_client/src/presentation/themes/default_theme.dart'; import 'package:thetiptop_client/src/presentation/widgets/btn/btn_link_widget.dart'; import 'package:thetiptop_client/src/presentation/widgets/layouts/layout_client_widget.dart'; import 'package:thetiptop_client/src/presentation/widgets/menu/menu_client_widget.dart'; import 'dart:html' as html; class GameScreen extends HookConsumerWidget { const GameScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final formKey = GlobalKey<FormState>(); SMIInput<double>? lotInput; return Semantics( header: true, label: "page jeu", child: LayoutClientWidget( child: Column( children: [ const MenuClientWidget(), const SizedBox( height: 40, ), Semantics( label: "Roue de la chance", child: Form( key: formKey, autovalidateMode: AutovalidateMode.always, child: ConstrainedBox( constraints: BoxConstraints.loose( const Size(475, 350), ), child: Stack( children: [ RiveAnimation.asset( "assets/rive/roue.riv", fit: BoxFit.contain, onInit: (Artboard artboard) { /// init controller /// final controller = StateMachineController.fromArtboard(artboard, 'rotation'); artboard.addController(controller!); /// init input /// lotInput = controller.findInput<double>('lot') as SMINumber; /// Ajoute un écouteur d'événement Rive /// controller.addEventListener((RiveEvent event) { SchedulerBinding.instance.addPostFrameCallback((_) { if (formKey.currentState != null && event.name == "click" && formKey.currentState!.validate()) { lotInput?.change(0); } if (event.name == "launch") { Future.delayed(const Duration(milliseconds: 3000), () { lotInput?.change(1); }); } }); }); }, ), Container( height: 140, decoration: BoxDecoration( color: DefaultTheme.blackGreen, borderRadius: BorderRadius.circular(15), ), child: Padding( padding: const EdgeInsets.fromLTRB(15, 25, 15, 15), child: TextFormField( onFieldSubmitted: (value) { lotInput?.change(0); }, keyboardType: TextInputType.number, expands: false, maxLines: 1, minLines: 1, maxLength: 10, textAlign: TextAlign.center, textAlignVertical: TextAlignVertical.center, cursorColor: DefaultTheme.white, style: TextStyle( color: DefaultTheme.white, fontWeight: FontWeight.bold, fontSize: 25, textBaseline: TextBaseline.ideographic, ), decoration: InputDecoration( contentPadding: const EdgeInsets.fromLTRB(0, 25, 0, 25), floatingLabelAlignment: FloatingLabelAlignment.center, floatingLabelBehavior: FloatingLabelBehavior.always, alignLabelWithHint: true, filled: true, fillColor: const Color.fromARGB(20, 217, 217, 217), focusColor: DefaultTheme.inputFill, focusedBorder: OutlineInputBorder( gapPadding: 25, borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide( color: DefaultTheme.whiteCream, width: 2, ), ), enabledBorder: OutlineInputBorder( gapPadding: 25, borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide( color: DefaultTheme.whiteCream, width: 2, ), ), errorBorder: OutlineInputBorder( gapPadding: 25, borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide( color: DefaultTheme.whiteCream, width: 2, ), ), focusedErrorBorder: OutlineInputBorder( gapPadding: 25, borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide( color: DefaultTheme.whiteCream, width: 2, ), ), hintText: "", labelText: "Entrez votre numéro de ticket", labelStyle: TextStyle( color: DefaultTheme.white, fontWeight: FontWeight.bold, fontFamily: DefaultTheme.fontFamily, fontSize: 20, ), floatingLabelStyle: TextStyle( color: DefaultTheme.white, fontWeight: FontWeight.bold, fontFamily: DefaultTheme.fontFamily, fontSize: 20, ), errorStyle: TextStyle( color: DefaultTheme.white, fontWeight: FontWeight.bold, fontFamily: DefaultTheme.fontFamily, fontSize: 13, )), validator: (value) { if (!RegExp(r"^[0-9]{10}$").hasMatch(value ?? "")) { return "Veuillez entrer un numéro de ticket valide"; } return null; }, ), ), ), ], ), ), ), ), const SizedBox( height: 75, ), MergeSemantics( child: Column( children: [ RichText( textAlign: TextAlign.center, text: const TextSpan( text: "Votre n’avez pas de numéro de ticket ?", style: TextStyle( fontFamily: DefaultTheme.fontFamily, fontSize: 18, ), ), ), const SizedBox( height: 20, ), BtnLinkWidget( onPressed: () { html.window.open("https://url-boutique-the-tip-top.fr", 'new tab'); }, text: "Obtenez votre numéro de ticket pour tout achat supérieur à 49€ sur notre boutique ThéTipTop", fontSize: 18, fontFamily: DefaultTheme.fontFamilyBold, ), ], ), ) ], ), ), ); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="8dp" > <!-- 전체적인 margin == 8dp 선택 버튼의 text size == 18sp 대표 text view의 text size == 24sp text color == holo_purple 가격을 나타내는 text view의 text size == 36sp radio button click == onRadioButtonClicked check box click == onCheckBoxClicked --> <!-- Select Dough --> <TextView android:id="@+id/selectDough" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="0dp" android:layout_marginTop="0dp" android:text="@string/selectDough" android:textColor="@android:color/holo_purple" android:textSize="24sp" /> <!-- dough를 선택하는 radio group --> <RadioGroup android:id="@+id/radioGroup" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- original radio button --> <RadioButton android:id="@+id/original" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:onClick="onRadioButtonClicked" android:text="@string/original" android:textSize="18sp" /> <!-- napoli radio button --> <RadioButton android:id="@+id/napoli" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:onClick="onRadioButtonClicked" android:text="@string/napoli" android:textSize="18sp" /> <!-- thin radio button --> <RadioButton android:id="@+id/thin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:onClick="onRadioButtonClicked" android:text="@string/thin" android:textSize="18sp" /> </RadioGroup> <!-- Select Topping --> <TextView android:id="@+id/selectTopping" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="0dp" android:layout_marginTop="0dp" android:text="@string/selectTopping" android:textColor="@android:color/holo_purple" android:textSize="24sp" /> <!-- pepperoni Check Box --> <CheckBox android:id="@+id/pepperoni" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:onClick="onCheckBoxClicked" android:text="@string/pepperoni" android:textSize="18sp" /> <!-- potato Check Box --> <CheckBox android:id="@+id/potato" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:onClick="onCheckBoxClicked" android:text="@string/potato" android:textSize="18sp" /> <!-- cheese Check Box --> <CheckBox android:id="@+id/cheese" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:onClick="onCheckBoxClicked" android:text="@string/cheese" android:textSize="18sp" /> <!-- Total --> <TextView android:id="@+id/total" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="0dp" android:layout_marginTop="0dp" android:text="@string/total" android:textColor="@android:color/holo_purple" android:textSize="24sp" /> <!-- Total Price --> <TextView android:id="@+id/totalPrice" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:text="@string/zero" android:textAlignment="center" android:textSize="36sp" /> </LinearLayout>
<template> <div class="page-wrap contact"> <decoration /> <div class="parallax parallax-left"> <parallax /> </div> <v-snackbar v-model="snackbar" :timeout="4000" location="top right" class="notification" > <div class="action"> Message Sent </div> <template #actions> <v-btn variant="text" icon @click="snackbar = false" > <v-icon>mdi-close</v-icon> </v-btn> </template> </v-snackbar> <hidden point="mdUp"> <div class="logo logo-header"> <nuxt-link :to="routeLink.crypto.home"> <img :src="logo" alt="logo"> <span class="use-text-title"> {{ brand.crypto.projectName }} </span> </nuxt-link> </div> </hidden> <v-container class="inner-wrap max-md"> <v-btn :href="routeLink.crypto.home" icon variant="text" class="backtohome" > <i class="ion-ios-home-outline" /> <i class="ion-ios-arrow-round-back-outline" /> </v-btn> <v-card class="form-box fragment-fadeUp"> <div class="full-form-wrap"> <h3 class="use-text-title title-contact pb-3 text-center"> {{ $t('common.contact_title2') }} </h3> <p class="desc use-text-subtitle2 text-center"> {{ $t('common.contact_subtitle') }} </p> <div class="form"> <v-form ref="form" v-model="valid" > <v-row class="spacing6"> <v-col cols="12" sm="6" class="px-6"> <v-text-field v-model="name" :rules="nameRules" :label="$t('common.form_name')" color="primary" required /> </v-col> <v-col cols="12" sm="6" class="px-6"> <v-text-field v-model="email" :rules="emailRules" :label="$t('common.form_email')" color="primary" required /> </v-col> <v-col cols="12" sm="6" class="px-6"> <v-text-field v-model="phone" :label="$t('common.form_phone')" color="primary" /> </v-col> <v-col cols="12" sm="6" class="px-6"> <v-text-field v-model="company" :label="$t('common.form_company')" color="primary" /> </v-col> <v-col cols="12" class="px-6"> <v-textarea v-model="message" rows="6" color="primary" :label="$t('common.form_message')" /> </v-col> </v-row> <div class="btn-area flex"> <div class="form-control-label"> <v-checkbox v-model="checkbox" :rules="[v => !!v || 'You must agree to continue!']" :label="$t('common.form_terms')" :hide-details="hideDetail" color="secondary" required /> <div class="mx-2"> <a href="#" class="link"> {{ $t('common.form_privacy') }} </a> </div> </div> <v-btn :block="isMobile" color="secondary" size="large" @click="validate" > {{ $t('common.form_send') }} </v-btn> </div> </v-form> </div> </div> </v-card> </v-container> </div> </template> <style lang="scss" scoped> @import './form-style.scss'; @import '../Title/title-style.scss'; </style> <script> import logo from '@/assets/images/crypto-logo.svg'; import brand from '@/assets/text/brand'; import link from '@/assets/text/link'; import Decoration from './Decoration'; import Parallax from '../Parallax/Hexagonal'; import Hidden from '../Hidden'; export default { components: { Parallax, Decoration, Hidden, }, data() { return { valid: true, snackbar: false, hideDetail: true, name: '', nameRules: [v => !!v || 'Name is required'], email: '', emailRules: [ v => !!v || 'E-mail is required', v => /.+@.+\..+/.test(v) || 'E-mail must be valid', ], phone: '', company: '', message: '', checkbox: false, logo, brand, routeLink: link, }; }, computed: { isMobile() { const smDown = this.$vuetify.display.smAndDown; return smDown; }, }, methods: { async validate() { const { valid } = await this.$refs.form.validate(); if (valid) { this.snackbar = true; this.hideDetail = true; } else { this.hideDetail = false; } }, }, }; </script>
import create from "zustand"; import agent from "../api/agent"; import { combineAndImmer } from "./types/combineAndImmer"; import { ICard, ICreateBoard, ICreateCard, IEditCard, IGetAllBoards, IGetAllListFromBoard, IKanbanList, IList, } from "./types/kanban.types"; import { cloneDeep } from "lodash"; import dayjs from "dayjs"; export const useKanbanStore = create( combineAndImmer( { currentKanbanBoardId: "", currentBoardTitle: "", kanbanBoards: null as IGetAllBoards | null, kanbanListItems: [] as IKanbanList[], getKanbanBoardLists: null as IGetAllListFromBoard | null, kanbanListOrder: [] as string[], kanbanListInCurrentBoard: null as IList[] | null, LoadingLists: false, openEditKanbanCardModal: false, currentKanbanCard: null as IEditCard | null, getKanbanBoardCards: null as ICard[] | null, CardAdded: {} as ICreateCard, }, (set, get) => ({ GetCardText: () => { let temp = get().getKanbanBoardCards?.find( (res) => res._id === get().currentKanbanCard?.cardID ); return temp; }, setLoadingLists: (load: boolean) => { set((s) => { s.LoadingLists = load; }); }, setListOrder: (order: string[]) => { set((s) => { s.kanbanListOrder = order; }); }, setListInCurrentBoard: (board: IList[] | null) => { set((s) => { s.kanbanListInCurrentBoard = board; }); }, setGetBoardContentCards: (card: ICard[]) => { set((s) => { s.getKanbanBoardCards = card; }); }, setAllBoards: (board: IGetAllBoards | null) => { set((s) => { s.kanbanBoards = board; }); }, setCurrentBoardId: (id: string) => { set((s) => { s.currentKanbanBoardId = id; }); }, setOpenEditTodoModal: (open: boolean) => { set((s) => { s.openEditKanbanCardModal = open; }); }, setGetBoardContentList: (list: IGetAllListFromBoard) => { set((s) => { s.getKanbanBoardLists = list; }); }, setKanbanListItem: (item: IKanbanList[]) => { set((s) => { s.kanbanListItems = item; }); }, setEditCardID: (listID: string, cardID: string) => { let temp = {} as IEditCard; temp.cardID = cardID; temp.listID = listID; set((s) => { s.currentKanbanCard = temp; }); }, deleteList: (listID: string, cardID: string) => { let result = get().kanbanListItems.find((res) => res.id === listID); let filter = result?.cards?.filter((res) => res.id !== cardID); set((s) => { s.kanbanListItems.forEach((res) => { if (res.id === listID) { res.cards = filter; } }); }); }, editList: (listID: string, cardID: string, text: string) => { set((s) => { s.kanbanListItems.forEach((res) => { if (res.id === listID) { res.cards?.forEach((re) => { if (re.id === cardID) { re.text = text; } }); } }); }); }, sortKanban: ( dropIdStart: string, dropIdEnd: string, dropIndexStart: number, dropIndexEnd: number, dragableID: string, type: string ) => { //drag list if (type === "list") { set((s) => { const list: IList[] = s.kanbanListInCurrentBoard!.splice( dropIndexStart, 1 ); s.kanbanListInCurrentBoard?.splice(dropIndexEnd, 0, ...list); }); let result: string[] = []; get().kanbanListInCurrentBoard!.forEach((res) => result.push(res._id) ); useKanbanStore .getState() .ListReorder(get().currentKanbanBoardId, result); } //in same list if (dropIdStart === dropIdEnd) { set((s) => { const list = s.kanbanListInCurrentBoard!.find( (res) => dropIdStart === res._id ); const card = list?.cardIds.splice(dropIndexStart, 1); list?.cardIds.splice(dropIndexEnd, 0, ...(card as [])); if (list !== undefined) { useKanbanStore .getState() .CardReorderSameList(list!._id, list!.cardIds); } }); } //other list if (dropIdStart !== dropIdEnd) { //find list where drag happens set((s) => { const listStart = s.kanbanListInCurrentBoard?.find( (res) => dropIdStart === res._id ); //pull out card from this list const card = listStart?.cardIds?.splice(dropIndexStart, 1); //find the list where drag ends const listEnd = s.kanbanListInCurrentBoard?.find( (res) => dropIdEnd === res._id ); //put the card in new list listEnd?.cardIds?.splice(dropIndexEnd, 0, ...(card as [])); useKanbanStore .getState() .CardReorderDiffList( listStart!._id, listEnd!._id, listStart!.cardIds, listEnd!.cardIds ); }); } }, CreateBoard: (result: ICreateBoard) => { set((s) => { s.kanbanBoards?.boards.push(result.result); }); }, CreateCard: async (listId: string, title: string) => { try { const result = await agent.KanbanService.createCard(listId, title); let temp = {} as ICard; temp._id = result.card._id; temp.title = result.card.title; if (get().getKanbanBoardCards === null) { useKanbanStore.getState().setGetBoardContentCards([temp]); set((s) => { s.kanbanListInCurrentBoard?.forEach((res) => { if (res._id === result.card.list) { res.cardIds.push(result.card._id); } }); }); } else { set((s) => { s.getKanbanBoardCards?.push(temp), s.kanbanListInCurrentBoard?.forEach((res) => { if (res._id === result.card.list) { res.cardIds.push(result.card._id); } }); }); } set((s) => { s.CardAdded = result; }); } catch (error) {} }, CreateList: async (title: string, boardId: string) => { try { const result = await agent.KanbanService.createNewList( title, boardId ); set((s) => { s.kanbanListInCurrentBoard?.push(result.list); }); } catch (error) { throw error; } }, GetAllBoards: async () => { try { const result = await agent.KanbanService.getAllBoard(); useKanbanStore.getState().setAllBoards(result); } catch (error) { throw error; } }, GetBoardContent: async (boardId: string) => { try { useKanbanStore.getState().setLoadingLists(true); const result = await agent.KanbanService.getAllListFromBoard(boardId); useKanbanStore.getState().setGetBoardContentList(result); set((s) => { s.kanbanListOrder = result.board.kanbanListOrder; }); let order = cloneDeep(result.list); order.sort((a, b) => { return ( result.board.kanbanListOrder.indexOf(a._id as never) - result.board.kanbanListOrder.indexOf(b._id as never) ); }); useKanbanStore.getState().setListInCurrentBoard(order); useKanbanStore.getState().setCurrentBoardId(result.board._id); set((s) => { s.currentBoardTitle = result.board.title; }); await useKanbanStore.getState().GetBoardCards(); } catch (error) { throw error; } }, GetBoardCards: async () => { try { let temp = get().kanbanListOrder; if (get().kanbanListOrder.length === 0) { temp = [""]; } const result = await agent.KanbanService.getAllCardFromList(temp); if (result.cards.length) useKanbanStore .getState() .setGetBoardContentCards(result.cards.flat()); useKanbanStore.getState().setLoadingLists(false); } catch (error) { throw error; } }, ListReorder: async (boardId: string, newListOrder: string[]) => { try { await agent.KanbanService.updateListOrder(boardId, newListOrder); } catch (error) { throw error; } }, CardReorderSameList: async ( sameListId: string, sameListCardIds: string[] ) => { try { await agent.KanbanService.updateCardSameList( sameListId, sameListCardIds ); } catch (error) { throw error; } }, CardReorderDiffList: async ( removedListId: string, addedListId: string, removedListCardIds: string[], addedListCardIds: string[] ) => { try { await agent.KanbanService.updateCardDifferentList( removedListId, addedListId, removedListCardIds, addedListCardIds ); } catch (error) { throw error; } }, UpdateCard: async ( title: string, descriptions: string, cardId: string, dueDate?: Date ) => { try { const formatDate = !!dueDate ? dayjs(dueDate).format("YYYY-MM-DD HH:mm:ss") : undefined; const result = await agent.KanbanService.updateCard( title, descriptions, cardId, formatDate ); let indexTodo = get().getKanbanBoardCards!.findIndex( (res) => res._id === result.data._id ); if (get().getKanbanBoardCards !== null) { set((s) => { s.getKanbanBoardCards![indexTodo] = result.data; }); } } catch (error) { throw error; } }, DeleteCard: async (cardId: string) => { try { await agent.KanbanService.deleteCard(cardId); let indexTodo = get().getKanbanBoardCards!.findIndex( (res) => res._id === cardId ); if (get().getKanbanBoardCards !== null) { set((s) => { s.getKanbanBoardCards!.splice(indexTodo, 1); }); } } catch (error) { throw error; } }, UpdateList: async (title: string, listId: string) => { try { const result = await agent.KanbanService.updateList(title, listId); if (get().kanbanListInCurrentBoard !== null) { let indexList = get().kanbanListInCurrentBoard!.findIndex( (res) => res._id === result.data._id ); set((s) => { s.kanbanListInCurrentBoard![indexList].title = result.data.title; }); } } catch (error) { throw error; } }, DeleteList: async (listId: string) => { try { await agent.KanbanService.deleteList(listId); if (get().kanbanListInCurrentBoard !== null) { let indexList = get().kanbanListInCurrentBoard!.findIndex( (res) => res._id === listId ); set((s) => { s.kanbanListInCurrentBoard!.splice(indexList, 1); }); } } catch (error) { throw error; } }, DeleteBoard: async (boardId: string) => { try { await agent.KanbanService.deleteBoard(boardId); if (get().kanbanBoards !== null) { let indexBoard = get().kanbanBoards!.boards.findIndex( (res) => res._id === boardId ); set((s) => { s.kanbanBoards!.boards.splice(indexBoard, 1); }); } } catch (error) { throw error; } }, }) ) );
/* * Copyright (C) 2005-2018 Team Kodi * This file is part of Kodi - https://kodi.tv * * SPDX-License-Identifier: GPL-2.0-or-later * See LICENSES/README.md for more information. */ #pragma once #include "Window.h" #include "guilib/GUIWindow.h" namespace XBMCAddon { namespace xbmcgui { #ifndef SWIG class Window; class ref; /** * These two classes are closely associated with the Interceptor template below. * For more detailed explanation, see that class. */ class InterceptorBase { protected: AddonClass::Ref<Window> window; // This instance is in Window.cpp static thread_local ref* upcallTls; InterceptorBase() : window(NULL) { upcallTls = NULL; } /** * Calling up ONCE resets the upcall to to false. The reason is that when * a call is recursive we cannot assume the ref has cleared the flag. * so ... * * ref(window)->UpCall() * * during the context of 'UpCall' it's possible that another call will * be made back on the window from the xbmc core side (this happens in * sometimes in OnMessage). In that case, if upcall is still 'true', than * the call will wrongly proceed back to the xbmc core side rather than * to the Addon API side. */ static bool up() { bool ret = ((upcallTls) != NULL); upcallTls = NULL; return ret; } public: virtual ~InterceptorBase() { if (window.isNotNull()) { window->interceptorClear(); } } virtual CGUIWindow* get() = 0; virtual void SetRenderOrder(int renderOrder) { } virtual void setActive(bool active) { } virtual bool isActive() { return false; } friend class ref; }; /** * Guard class. But instead of managing memory or thread resources, * any call made using the operator-> results in an 'upcall.' That is, * it expects the call about to be made to have come from the XBMCAddon * xbmcgui Window API and not from either the scripting language or the * XBMC core Windowing system. * * This class is meant to hold references to instances of Interceptor<P>. * see that template definition below. */ class ref { InterceptorBase* w; public: inline explicit ref(InterceptorBase* b) : w(b) { w->upcallTls = this; } inline ~ref() { w->upcallTls = NULL; } inline CGUIWindow* operator->() { return w->get(); } inline CGUIWindow* get() { return w->get(); } }; /** * The intention of this class is to intercept calls from * multiple points in the CGUIWindow class hierarchy and pass * those calls over to the XBMCAddon API Window hierarchy. It * is a class template that uses the type template parameter * to determine the parent class. * * Since this class also maintains two way communication between * the XBMCAddon API Window hierarchy and the core XBMC CGUIWindow * hierarchy, it is used as a general bridge. For calls going * TO the window hierarchy (as in callbacks) it operates in a * straightforward manner. In the reverse direction (from the * XBMCAddon hierarchy) it uses some hackery in a "smart pointer" * overloaded -> operator. */ #define checkedb(methcall) ( window.isNotNull() ? window-> methcall : false ) #define checkedv(methcall) { if (window.isNotNull()) window-> methcall ; } template <class P /* extends CGUIWindow*/> class Interceptor : public P, public InterceptorBase { std::string classname; protected: CGUIWindow* get() override { return this; } public: Interceptor(const char* specializedName, Window* _window, int windowid) : P(windowid, ""), classname("Interceptor<" + std::string(specializedName) + ">") { #ifdef ENABLE_XBMC_TRACE_API XBMCAddonUtils::TraceGuard tg; CLog::Log(LOGDEBUG, "%sNEWADDON constructing %s 0x%lx", tg.getSpaces(),classname.c_str(), (long)(((void*)this))); #endif window.reset(_window); P::SetLoadType(CGUIWindow::LOAD_ON_GUI_INIT); } Interceptor(const char* specializedName, Window* _window, int windowid, const char* xmlfile) : P(windowid, xmlfile), classname("Interceptor<" + std::string(specializedName) + ">") { #ifdef ENABLE_XBMC_TRACE_API XBMCAddonUtils::TraceGuard tg; CLog::Log(LOGDEBUG, "%sNEWADDON constructing %s 0x%lx", tg.getSpaces(),classname.c_str(), (long)(((void*)this))); #endif window.reset(_window); P::SetLoadType(CGUIWindow::LOAD_ON_GUI_INIT); } #ifdef ENABLE_XBMC_TRACE_API ~Interceptor() override { XBMCAddonUtils::TraceGuard tg; CLog::Log(LOGDEBUG, "%sNEWADDON LIFECYCLE destroying %s 0x%lx", tg.getSpaces(),classname.c_str(), (long)(((void*)this))); } #else ~Interceptor() override = default; #endif bool OnMessage(CGUIMessage& message) override { XBMC_TRACE; return up() ? P::OnMessage(message) : checkedb(OnMessage(message)); } bool OnAction(const CAction &action) override { XBMC_TRACE; return up() ? P::OnAction(action) : checkedb(OnAction(action)); } // NOTE!!: This ALWAYS skips up to the CGUIWindow instance. bool OnBack(int actionId) override { XBMC_TRACE; return up() ? CGUIWindow::OnBack(actionId) : checkedb(OnBack(actionId)); } void OnDeinitWindow(int nextWindowID) override { XBMC_TRACE; if(up()) P::OnDeinitWindow(nextWindowID); else checkedv(OnDeinitWindow(nextWindowID)); } bool IsModalDialog() const override { XBMC_TRACE; return checkedb(IsModalDialog()); }; bool IsDialogRunning() const override { XBMC_TRACE; return checkedb(IsDialogRunning()); }; bool IsDialog() const override { XBMC_TRACE; return checkedb(IsDialog()); }; bool IsMediaWindow() const override { XBMC_TRACE; return checkedb(IsMediaWindow()); }; void SetRenderOrder(int renderOrder) override { XBMC_TRACE; P::m_renderOrder = renderOrder; } void setActive(bool active) override { XBMC_TRACE; P::m_active = active; } bool isActive() override { XBMC_TRACE; return P::m_active; } }; template <class P /* extends CGUIWindow*/> class InterceptorDialog : public Interceptor<P> { public: InterceptorDialog(const char* specializedName, Window* _window, int windowid) : Interceptor<P>(specializedName, _window, windowid) { } InterceptorDialog(const char* specializedName, Window* _window, int windowid, const char* xmlfile) : Interceptor<P>(specializedName, _window, windowid,xmlfile) { } }; #undef checkedb #undef checkedv #endif } }
<!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>Portfolio</title> <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=Raleway:wght@800&family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="./css/slyles.css" /> </head> <body class="body"> <header> <nav> <a class="logo-up link" href="./index.html">Web<span class="logo-accent">Studio</span></a> <ul class="list"> <li> <a class="navigation link" href="./index.html">Studio</a> </li> <li> <a class="navigation link" href="./portfolio.html">Portfolio</a> </li> <li> <a class="navigation link" href="">Contacts</a> </li> </ul> </nav> <address class="adress"> <ul class="list"> <li><a class="connection link" href="mailto:info@devstudio.com">info@devstudio.com</a></li> <li><a class="connection link" href="tel:+110001111111">+11 (000) 111-11-11</a></li> </ul> </address> </header> <!-- Main-section --> <main> <section> <h1 hidden>Our products</h1> <!--Button-section--> <ul class="list"> <li> <button class="portfolio-btn" type="button">All</button> </li> <li> <button class="portfolio-btn" type="button">Web Site</button> </li> <li> <button class="portfolio-btn" type="button">App</button> </li> <li> <button class="portfolio-btn" type="button">Design</button> </li> <li> <button class="portfolio-btn" type="button">Marketing</button> </li> </ul> <!--Gallery-section--> <ul class="list"> <li> <a class="link" href=""> <img src="./images/portfolio/banking-app-interface.jpg" alt="Banking App Interface Concept" width="360" height="300"> <h2 class="name-product">Banking App Interface Concept</h2> <p class="type-product">App</p> </a> </li> <li> <a class="link" href=""> <img src="./images/portfolio/cashless-payment.jpg" alt="Cashless Payment" width="360" height="300"> <h2 class="name-product">Cashless Payment</h2> <p class="type-product">Marketing</p> </a> </li> <li> <a class="link" href=""> <img src="./images/portfolio/view-of-app.jpg" alt="Meditaion App" width="360" height="300"> <h2 class="name-product">Meditation App</h2> <p class="type-product">App</p> </a> </li> <li> <a class="link" href=""> <img src="./images/portfolio/driver.jpg" alt="Taxi Service" width="360" height="300"> <h2 class="name-product">Taxi Service</h2> <p class="type-product">Marketing</p> </a> </li> <li> <a class="link" href=""> <img src="./images/portfolio/screen-ilustrarion.jpg" alt="Screen Illustrations" width="360" height="300"> <h2 class="name-product">Screen Illustrations</h2> <p class="type-product">Design</p> </a> </li> <li> <a class="link" href=""> <img src="./images/portfolio/online-courses.jpg" alt="Online Courses" width="360" height="300"> <h2 class="name-product">Online Courses</h2> <p class="type-product">Marketing</p> </a> </li> <li> <a class="link" href=""> <img src="./images/portfolio/preview.jpg" alt="Instagram Stories Concept" width="360" height="300"> <h2 class="name-product">Instagram Stories Concept</h2> <p class="type-product">Design</p> </a> </li> <li> <a class="link" href=""> <img src="./images/portfolio/grocery-bag.jpg" alt="Organic Food" width="360" height="300"> <h2 class="name-product">Organic Food</h2> <p class="type-product">Web Site</p> </a> </li> <li> <a class="link" href=""> <img src="./images/portfolio/fresh-coffee.jpg" alt="Fresh Coffee" width="360" height="300"> <h2 class="name-product">Fresh Coffee</h2> <p class="type-product">Web Site</p> </a> </li> </ul> </section> </main> <!-- Footer --> <footer class="footer"> <a class="logo-down link" href="./index.html">Web<span class="logo-footer">Studio</span></a> <p class="footer-text">Increase the flow of customers and sales for your business with digital marketing & growth solutions. </p> </footer> </body> </html>
SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) NNAAMMEE sudo_plugin - Sudo Plugin API DDEESSCCRRIIPPTTIIOONN Starting with version 1.8, ssuuddoo supports a plugin API for policy and session logging. By default, the _s_u_d_o_e_r_s policy plugin and an associated I/O logging plugin are used. Via the plugin API, ssuuddoo can be configured to use alternate policy and/or I/O logging plugins provided by third parties. The plugins to be used are specified via the _/_e_t_c_/_s_u_d_o_._c_o_n_f file. The API is versioned with a major and minor number. The minor version number is incremented when additions are made. The major number is incremented when incompatible changes are made. A plugin should be check the version passed to it and make sure that the major version matches. The plugin API is defined by the sudo_plugin.h header file. TThhee ssuuddoo..ccoonnff FFiillee The _/_e_t_c_/_s_u_d_o_._c_o_n_f file contains plugin configuration directives. Currently, the only supported keyword is the Plugin directive, which causes a plugin plugin to be loaded. A Plugin line consists of the Plugin keyword, followed by the _s_y_m_b_o_l___n_a_m_e and the _p_a_t_h to the shared object containing the plugin. The _s_y_m_b_o_l___n_a_m_e is the name of the struct policy_plugin or struct io_plugin in the plugin shared object. The _p_a_t_h may be fully qualified or relative. If not fully qualified it is relative to the _/_u_s_r_/_l_o_c_a_l_/_l_i_b_e_x_e_c directory. Any additional parameters after the _p_a_t_h are ignored. Lines that don't begin with Plugin or Path are silently ignored. The same shared object may contain multiple plugins, each with a different symbol name. The shared object file must be owned by uid 0 and only writable by its owner. Because of ambiguities that arise from composite policies, only a single policy plugin may be specified. This limitation does not apply to I/O plugins. # # Default /etc/sudo.conf file # # Format: # Plugin plugin_name plugin_path # Path askpass /path/to/askpass # # The plugin_path is relative to /usr/local/libexec unless # fully qualified. # The plugin_name corresponds to a global symbol in the plugin # that contains the plugin interface structure. # Plugin sudoers_policy sudoers.so Plugin sudoers_io sudoers.so 1.8.0rc1 February 21, 2011 1 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) PPoolliiccyy PPlluuggiinn AAPPII A policy plugin must declare and populate a policy_plugin struct in the global scope. This structure contains pointers to the functions that implement the ssuuddoo policy checks. The name of the symbol should be specified in _/_e_t_c_/_s_u_d_o_._c_o_n_f along with a path to the plugin so that ssuuddoo can load it. struct policy_plugin { #define SUDO_POLICY_PLUGIN 1 unsigned int type; /* always SUDO_POLICY_PLUGIN */ unsigned int version; /* always SUDO_API_VERSION */ int (*open)(unsigned int version, sudo_conv_t conversation, sudo_printf_t plugin_printf, char * const settings[], char * const user_info[], char * const user_env[]); void (*close)(int exit_status, int error); int (*show_version)(int verbose); int (*check_policy)(int argc, char * const argv[], char *env_add[], char **command_info[], char **argv_out[], char **user_env_out[]); int (*list)(int argc, char * const argv[], int verbose, const char *list_user); int (*validate)(void); void (*invalidate)(int remove); int (*init_session)(struct passwd *pwd); }; The policy_plugin struct has the following fields: type The type field should always be set to SUDO_POLICY_PLUGIN. version The version field should be set to SUDO_API_VERSION. This allows ssuuddoo to determine the API version the plugin was built against. open int (*open)(unsigned int version, sudo_conv_t conversation, sudo_printf_t plugin_printf, char * const settings[], char * const user_info[], char * const user_env[]); Returns 1 on success, 0 on failure, -1 if a general error occurred, or -2 if there was a usage error. In the latter case, ssuuddoo will print a usage message before it exits. If an error occurs, the plugin may optionally call the conversation or plugin_printf function with SUDO_CONF_ERROR_MSG to present additional error information to the user. The function arguments are as follows: version The version passed in by ssuuddoo allows the plugin to determine the major and minor version number of the plugin API supported 1.8.0rc1 February 21, 2011 2 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) by ssuuddoo. conversation A pointer to the conversation function that can be used by the plugin to interact with the user (see below). Returns 0 on success and -1 on failure. plugin_printf A pointer to a printf-style function that may be used to display informational or error messages (see below). Returns the number of characters printed on success and -1 on failure. settings A vector of user-supplied ssuuddoo settings in the form of "name=value" strings. The vector is terminated by a NULL pointer. These settings correspond to flags the user specified when running ssuuddoo. As such, they will only be present when the corresponding flag has been specified on the command line. When parsing _s_e_t_t_i_n_g_s, the plugin should split on the ffiirrsstt equal sign ('=') since the _n_a_m_e field will never include one itself but the _v_a_l_u_e might. debug_level=number A numeric debug level, from 1-9, if specified via the -D flag. runas_user=string The user name or uid to to run the command as, if specified via the -u flag. runas_group=string The group name or gid to to run the command as, if specified via the -g flag. prompt=string The prompt to use when requesting a password, if specified via the -p flag. set_home=bool Set to true if the user specified the -H flag. If true, set the HOME environment variable to the target user's home directory. preserve_environment=bool Set to true if the user specified the -E flag, indicating that the user wishes to preserve the environment. login_shell=bool Set to true if the user specified the -i flag, indicating that the user wishes to run a login shell. implied_shell=bool If the user does not specify a program on the command line, 1.8.0rc1 February 21, 2011 3 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) ssuuddoo will pass the plugin the path to the user's shell and set _i_m_p_l_i_e_d___s_h_e_l_l to true. This allows ssuuddoo with no arguments to be used similarly to _s_u(1). If the plugin does not to support this usage, it may return a value of -2 from the check_policy function, which will cause ssuuddoo to print a usage message and exit. preserve_groups=bool Set to true if the user specified the -P flag, indicating that the user wishes to preserve the group vector instead of setting it based on the runas user. ignore_ticket=bool Set to true if the user specified the -k flag along with a command, indicating that the user wishes to ignore any cached authentication credentials. noninteractive=bool Set to true if the user specified the -n flag, indicating that ssuuddoo should operate in non-interactive mode. The plugin may reject a command run in non-interactive mode if user interaction is required. login_class=string BSD login class to use when setting resource limits and nice value, if specified by the -c flag. selinux_role=string SELinux role to use when executing the command, if specified by the -r flag. selinux_type=string SELinux type to use when executing the command, if specified by the -t flag. bsdauth_type=string Authentication type, if specified by the -a flag, to use on systems where BSD authentication is supported. network_addrs=list A space-separated list of IP network addresses and netmasks in the form "addr/netmask", e.g. "192.168.1.2/255.255.255.0". The address and netmask pairs may be either IPv4 or IPv6, depending on what the operating system supports. If the address contains a colon (':'), it is an IPv6 address, else it is IPv4. progname=string The command name that sudo was run as, typically "sudo" or "sudoedit". sudoedit=bool Set to true when the -e flag is is specified or if invoked as ssuuddooeeddiitt. The plugin shall substitute an editor into 1.8.0rc1 February 21, 2011 4 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) _a_r_g_v in the _c_h_e_c_k___p_o_l_i_c_y function or return -2 with a usage error if the plugin does not support _s_u_d_o_e_d_i_t. For more information, see the _c_h_e_c_k___p_o_l_i_c_y section. closefrom=number If specified, the user has requested via the -C flag that ssuuddoo close all files descriptors with a value of _n_u_m_b_e_r or higher. The plugin may optionally pass this, or another value, back in the _c_o_m_m_a_n_d___i_n_f_o list. Additional settings may be added in the future so the plugin should silently ignore settings that it does not recognize. user_info A vector of information about the user running the command in the form of "name=value" strings. The vector is terminated by a NULL pointer. When parsing _u_s_e_r___i_n_f_o, the plugin should split on the ffiirrsstt equal sign ('=') since the _n_a_m_e field will never include one itself but the _v_a_l_u_e might. user=string The name of the user invoking ssuuddoo. uid=uid_t The real user ID of the user invoking ssuuddoo. gid=gid_t The real group ID of the user invoking ssuuddoo. groups=list The user's supplementary group list formatted as a string of comma-separated group IDs. cwd=string The user's current working directory. tty=string The path to the user's terminal device. If the user has no terminal device associated with the session, the value will be empty, as in tty=. host=string The local machine's hostname as returned by the gethostname() system call. lines=int The number of lines the user's terminal supports. If there is no terminal device available, a default value of 24 is used. cols=int The number of columns the user's terminal supports. If 1.8.0rc1 February 21, 2011 5 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) there is no terminal device available, a default value of 80 is used. user_env The user's environment in the form of a NULL-terminated vector of "name=value" strings. When parsing _u_s_e_r___e_n_v, the plugin should split on the ffiirrsstt equal sign ('=') since the _n_a_m_e field will never include one itself but the _v_a_l_u_e might. close void (*close)(int exit_status, int error); The close function is called when the command being run by ssuuddoo finishes. The function arguments are as follows: exit_status The command's exit status, as returned by the _w_a_i_t(2) system call. The value of exit_status is undefined if error is non- zero. error If the command could not be executed, this is set to the value of errno set by the _e_x_e_c_v_e(2) system call. The plugin is responsible for displaying error information via the conversation or plugin_printf function. If the command was successfully executed, the value of error is 0. show_version int (*show_version)(int verbose); The show_version function is called by ssuuddoo when the user specifies the -V option. The plugin may display its version information to the user via the conversation or plugin_printf function using SUDO_CONV_INFO_MSG. If the user requests detailed version information, the verbose flag will be set. check_policy int (*check_policy)(int argc, char * const argv[] char *env_add[], char **command_info[], char **argv_out[], char **user_env_out[]); The _c_h_e_c_k___p_o_l_i_c_y function is called by ssuuddoo to determine whether the user is allowed to run the specified commands. If the _s_u_d_o_e_d_i_t option was enabled in the _s_e_t_t_i_n_g_s array passed to the _o_p_e_n function, the user has requested _s_u_d_o_e_d_i_t mode. _s_u_d_o_e_d_i_t is a mechanism for editing one or more files where an editor is run with the user's credentials instead of with elevated privileges. ssuuddoo achieves this by creating user-writable temporary copies of the files to be edited and then overwriting the originals with the 1.8.0rc1 February 21, 2011 6 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) temporary copies after editing is complete. If the plugin supports ssuuddooeeddiitt, it should choose the editor to be used, potentially from a variable in the user's environment, such as EDITOR, and include it in _a_r_g_v___o_u_t (note that environment variables may include command line flags). The files to be edited should be copied from _a_r_g_v into _a_r_g_v___o_u_t, separated from the editor and its arguments by a "--" element. The "--" will be removed by ssuuddoo before the editor is executed. The plugin should also set _s_u_d_o_e_d_i_t_=_t_r_u_e in the _c_o_m_m_a_n_d___i_n_f_o list. The _c_h_e_c_k___p_o_l_i_c_y function returns 1 if the command is allowed, 0 if not allowed, -1 for a general error, or -2 for a usage error or if ssuuddooeeddiitt was specified but is unsupported by the plugin. In the latter case, ssuuddoo will print a usage message before it exits. If an error occurs, the plugin may optionally call the conversation or plugin_printf function with SUDO_CONF_ERROR_MSG to present additional error information to the user. The function arguments are as follows: argc The number of elements in _a_r_g_v, not counting the final NULL pointer. argv The argument vector describing the command the user wishes to run, in the same form as what would be passed to the _e_x_e_c_v_e_(_) system call. The vector is terminated by a NULL pointer. env_add Additional environment variables specified by the user on the command line in the form of a NULL-terminated vector of "name=value" strings. The plugin may reject the command if one or more variables are not allowed to be set, or it may silently ignore such variables. When parsing _e_n_v___a_d_d, the plugin should split on the ffiirrsstt equal sign ('=') since the _n_a_m_e field will never include one itself but the _v_a_l_u_e might. command_info Information about the command being run in the form of "name=value" strings. These values are used by ssuuddoo to set the execution environment when running a command. The plugin is responsible for creating and populating the vector, which must be terminated with a NULL pointer. The following values are recognized by ssuuddoo: command=string Fully qualified path to the command to be executed. runas_uid=uid User ID to run the command as. 1.8.0rc1 February 21, 2011 7 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) runas_euid=uid Effective user ID to run the command as. If not specified, the value of _r_u_n_a_s___u_i_d is used. runas_gid=gid Group ID to run the command as. runas_egid=gid Effective group ID to run the command as. If not specified, the value of _r_u_n_a_s___g_i_d is used. runas_groups=list The supplementary group vector to use for the command in the form of a comma-separated list of group IDs. If _p_r_e_s_e_r_v_e___g_r_o_u_p_s is set, this option is ignored. login_class=login_class BSD login class to use when setting resource limits and nice value (optional). This option is only set on systems that support login classes. preserve_groups=bool If set, ssuuddoo will preserve the user's group vector instead of initializing the group vector based on runas_user. cwd=string The current working directory to change to when executing the command. noexec=bool If set, prevent the command from executing other programs. chroot=string The root directory to use when running the command. nice=int Nice value (priority) to use when executing the command. The nice value, if specified, overrides the priority associated with the _l_o_g_i_n___c_l_a_s_s on BSD systems. umask=octal The file creation mask to use when executing the command. selinux_role=string SELinux role to use when executing the command. selinux_type=string SELinux type to use when executing the command. timeout=int Command timeout. If non-zero then when the timeout expires the command will be killed. 1.8.0rc1 February 21, 2011 8 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) sudoedit=bool Set to true when in _s_u_d_o_e_d_i_t mode. The plugin may enable _s_u_d_o_e_d_i_t mode even if ssuuddoo was not invoked as ssuuddooeeddiitt. This allows the plugin to perform command substitution and transparently enable _s_u_d_o_e_d_i_t when the user attempts to run an editor. closefrom=number If specified, ssuuddoo will close all files descriptors with a value of _n_u_m_b_e_r or higher. iolog_compress=bool Set to true if the I/O logging plugins, if any, should compress the log data. This is a hint to the I/O logging plugin which may choose to ignore it. iolog_path=string Fully qualified path to the file or directory in which I/O log is to be stored. This is a hint to the I/O logging plugin which may choose to ignore it. If no I/O logging plugin is loaded, this setting has no effect. iolog_stdin=bool Set to true if the I/O logging plugins, if any, should log the standard input if it is not connected to a terminal device. This is a hint to the I/O logging plugin which may choose to ignore it. iolog_stdout=bool Set to true if the I/O logging plugins, if any, should log the standard output if it is not connected to a terminal device. This is a hint to the I/O logging plugin which may choose to ignore it. iolog_stderr=bool Set to true if the I/O logging plugins, if any, should log the standard error if it is not connected to a terminal device. This is a hint to the I/O logging plugin which may choose to ignore it. iolog_ttyin=bool Set to true if the I/O logging plugins, if any, should log all terminal input. This only includes input typed by the user and not from a pipe or redirected from a file. This is a hint to the I/O logging plugin which may choose to ignore it. iolog_ttyout=bool Set to true if the I/O logging plugins, if any, should log all terminal output. This only includes output to the screen, not output to a pipe or file. This is a hint to the I/O logging plugin which may choose to ignore it. 1.8.0rc1 February 21, 2011 9 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) use_pty=bool Allocate a pseudo-tty to run the command in, regardless of whether or not I/O logging is in use. By default, ssuuddoo will only run the command in a pty when an I/O log plugin is loaded. Unsupported values will be ignored. argv_out The NULL-terminated argument vector to pass to the _e_x_e_c_v_e_(_) system call when executing the command. The plugin is responsible for allocating and populating the vector. user_env_out The NULL-terminated environment vector to use when executing the command. The plugin is responsible for allocating and populating the vector. list int (*list)(int verbose, const char *list_user, int argc, char * const argv[]); List available privileges for the invoking user. Returns 1 on success, 0 on failure and -1 on error. On error, the plugin may optionally call the conversation or plugin_printf function with SUDO_CONF_ERROR_MSG to present additional error information to the user. Privileges should be output via the conversation or plugin_printf function using SUDO_CONV_INFO_MSG. verbose Flag indicating whether to list in verbose mode or not. list_user The name of a different user to list privileges for if the policy allows it. If NULL, the plugin should list the privileges of the invoking user. argc The number of elements in _a_r_g_v, not counting the final NULL pointer. argv If non-NULL, an argument vector describing a command the user wishes to check against the policy in the same form as what would be passed to the _e_x_e_c_v_e_(_) system call. If the command is permitted by the policy, the fully-qualified path to the command should be displayed along with any command line arguments. validate int (*validate)(void); 1.8.0rc1 February 21, 2011 10 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) The validate function is called when ssuuddoo is run with the -v flag. For policy plugins such as _s_u_d_o_e_r_s that cache authentication credentials, this function will validate and cache the credentials. The validate function should be NULL if the plugin does not support credential caching. Returns 1 on success, 0 on failure and -1 on error. On error, the plugin may optionally call the conversation or plugin_printf function with SUDO_CONF_ERROR_MSG to present additional error information to the user. invalidate void (*invalidate)(int remove); The invalidate function is called when ssuuddoo is called with the -k or -K flag. For policy plugins such as _s_u_d_o_e_r_s that cache authentication credentials, this function will invalidate the credentials. If the _r_e_m_o_v_e flag is set, the plugin may remove the credentials instead of simply invalidating them. The invalidate function should be NULL if the plugin does not support credential caching. init_session int (*init_session)(struct passwd *pwd); The init_session function is called when ssuuddoo sets up the execution environment for the command, immediately before the contents of the _c_o_m_m_a_n_d___i_n_f_o list are applied (before the uid changes). This can be used to do session setup that is not supported by _c_o_m_m_a_n_d___i_n_f_o, such as opening the PAM session. The _p_w_d argument points to a passwd struct for the user the command will be run as if the uid the command will run as was found in the password database, otherwise it will be NULL. Returns 1 on success, 0 on failure and -1 on error. On error, the plugin may optionally call the conversation or plugin_printf function with SUDO_CONF_ERROR_MSG to present additional error information to the user. _V_e_r_s_i_o_n _m_a_c_r_o_s #define SUDO_API_VERSION_GET_MAJOR(v) ((v) >> 16) #define SUDO_API_VERSION_GET_MINOR(v) ((v) & 0xffff) #define SUDO_API_VERSION_SET_MAJOR(vp, n) do { \ *(vp) = (*(vp) & 0x0000ffff) | ((n) << 16); \ } while(0) #define SUDO_VERSION_SET_MINOR(vp, n) do { \ *(vp) = (*(vp) & 0xffff0000) | (n); \ } while(0) #define SUDO_API_VERSION_MAJOR 1 1.8.0rc1 February 21, 2011 11 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) #define SUDO_API_VERSION_MINOR 0 #define SUDO_API_VERSION ((SUDO_API_VERSION_MAJOR << 16) | \ SUDO_API_VERSION_MINOR) II//OO PPlluuggiinn AAPPII struct io_plugin { #define SUDO_IO_PLUGIN 2 unsigned int type; /* always SUDO_IO_PLUGIN */ unsigned int version; /* always SUDO_API_VERSION */ int (*open)(unsigned int version, sudo_conv_t conversation sudo_printf_t plugin_printf, char * const settings[], char * const user_info[], int argc, char * const argv[], char * const user_env[]); void (*close)(int exit_status, int error); /* wait status or error */ int (*show_version)(int verbose); int (*log_ttyin)(const char *buf, unsigned int len); int (*log_ttyout)(const char *buf, unsigned int len); int (*log_stdin)(const char *buf, unsigned int len); int (*log_stdout)(const char *buf, unsigned int len); int (*log_stderr)(const char *buf, unsigned int len); }; When an I/O plugin is loaded, ssuuddoo runs the command in a pseudo-tty. This makes it possible to log the input and output from the user's session. If any of the standard input, standard output or standard error do not correspond to a tty, ssuuddoo will open a pipe to capture the I/O for logging before passing it on. The log_ttyin function receives the raw user input from the terminal device (note that this will include input even when echo is disabled, such as when a password is read). The log_ttyout function receives output from the pseudo-tty that is suitable for replaying the user's session at a later time. The log_stdin, log_stdout and log_stderr functions are only called if the standard input, standard output or standard error respectively correspond to something other than a tty. Any of the logging functions may be set to the NULL pointer if no logging is to be performed. If the open function returns 0, no I/O will be sent to the plugin. The io_plugin struct has the following fields: type The type field should always be set to SUDO_IO_PLUGIN version The version field should be set to SUDO_API_VERSION. This allows ssuuddoo to determine the API version the plugin was built against. open 1.8.0rc1 February 21, 2011 12 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) int (*open)(unsigned int version, sudo_conv_t conversation sudo_printf_t plugin_printf, char * const settings[], char * const user_info[], int argc, char * const argv[], char * const user_env[]); The _o_p_e_n function is run before the _l_o_g___i_n_p_u_t, _l_o_g___o_u_t_p_u_t or _s_h_o_w___v_e_r_s_i_o_n functions are called. It is only called if the version is being requested or the _c_h_e_c_k___p_o_l_i_c_y function has returned successfully. It returns 1 on success, 0 on failure, -1 if a general error occurred, or -2 if there was a usage error. In the latter case, ssuuddoo will print a usage message before it exits. If an error occurs, the plugin may optionally call the conversation or plugin_printf function with SUDO_CONF_ERROR_MSG to present additional error information to the user. The function arguments are as follows: version The version passed in by ssuuddoo allows the plugin to determine the major and minor version number of the plugin API supported by ssuuddoo. conversation A pointer to the conversation function that may be used by the _s_h_o_w___v_e_r_s_i_o_n function to display version information (see show_version below). The conversation function may also be used to display additional error message to the user. The conversation function returns 0 on success and -1 on failure. plugin_printf A pointer to a printf-style function that may be used by the _s_h_o_w___v_e_r_s_i_o_n function to display version information (see show_version below). The plugin_printf function may also be used to display additional error message to the user. The plugin_printf function returns number of characters printed on success and -1 on failure. settings A vector of user-supplied ssuuddoo settings in the form of "name=value" strings. The vector is terminated by a NULL pointer. These settings correspond to flags the user specified when running ssuuddoo. As such, they will only be present when the corresponding flag has been specified on the command line. When parsing _s_e_t_t_i_n_g_s, the plugin should split on the ffiirrsstt equal sign ('=') since the _n_a_m_e field will never include one itself but the _v_a_l_u_e might. See the "Policy Plugin API" section for a list of all possible settings. user_info A vector of information about the user running the command in the form of "name=value" strings. The vector is terminated by 1.8.0rc1 February 21, 2011 13 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) a NULL pointer. When parsing _u_s_e_r___i_n_f_o, the plugin should split on the ffiirrsstt equal sign ('=') since the _n_a_m_e field will never include one itself but the _v_a_l_u_e might. See the "Policy Plugin API" section for a list of all possible strings. argc The number of elements in _a_r_g_v, not counting the final NULL pointer. argv If non-NULL, an argument vector describing a command the user wishes to run in the same form as what would be passed to the _e_x_e_c_v_e_(_) system call. user_env The user's environment in the form of a NULL-terminated vector of "name=value" strings. When parsing _u_s_e_r___e_n_v, the plugin should split on the ffiirrsstt equal sign ('=') since the _n_a_m_e field will never include one itself but the _v_a_l_u_e might. close void (*close)(int exit_status, int error); The close function is called when the command being run by ssuuddoo finishes. The function arguments are as follows: exit_status The command's exit status, as returned by the _w_a_i_t(2) system call. The value of exit_status is undefined if error is non- zero. error If the command could not be executed, this is set to the value of errno set by the _e_x_e_c_v_e(2) system call. If the command was successfully executed, the value of error is 0. show_version int (*show_version)(int verbose); The show_version function is called by ssuuddoo when the user specifies the -V option. The plugin may display its version information to the user via the conversation or plugin_printf function using SUDO_CONV_INFO_MSG. If the user requests detailed version information, the verbose flag will be set. 1.8.0rc1 February 21, 2011 14 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) log_ttyin int (*log_ttyin)(const char *buf, unsigned int len); The _l_o_g___t_t_y_i_n function is called whenever data can be read from the user but before it is passed to the running command. This allows the plugin to reject data if it chooses to (for instance if the input contains banned content). Returns 1 if the data should be passed to the command, 0 if the data is rejected (which will terminate the command) or -1 if an error occurred. The function arguments are as follows: buf The buffer containing user input. len The length of _b_u_f in bytes. log_ttyout int (*log_ttyout)(const char *buf, unsigned int len); The _l_o_g___t_t_y_o_u_t function is called whenever data can be read from the command but before it is written to the user's terminal. This allows the plugin to reject data if it chooses to (for instance if the output contains banned content). Returns 1 if the data should be passed to the user, 0 if the data is rejected (which will terminate the command) or -1 if an error occurred. The function arguments are as follows: buf The buffer containing command output. len The length of _b_u_f in bytes. log_stdin int (*log_stdin)(const char *buf, unsigned int len); The _l_o_g___s_t_d_i_n function is only used if the standard input does not correspond to a tty device. It is called whenever data can be read from the standard input but before it is passed to the running command. This allows the plugin to reject data if it chooses to (for instance if the input contains banned content). Returns 1 if the data should be passed to the command, 0 if the data is rejected (which will terminate the command) or -1 if an error occurred. The function arguments are as follows: buf The buffer containing user input. len The length of _b_u_f in bytes. log_stdout int (*log_stdout)(const char *buf, unsigned int len); The _l_o_g___s_t_d_o_u_t function is only used if the standard output does not correspond to a tty device. It is called whenever data can be 1.8.0rc1 February 21, 2011 15 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) read from the command but before it is written to the standard output. This allows the plugin to reject data if it chooses to (for instance if the output contains banned content). Returns 1 if the data should be passed to the user, 0 if the data is rejected (which will terminate the command) or -1 if an error occurred. The function arguments are as follows: buf The buffer containing command output. len The length of _b_u_f in bytes. log_stderr int (*log_stderr)(const char *buf, unsigned int len); The _l_o_g___s_t_d_e_r_r function is only used if the standard error does not correspond to a tty device. It is called whenever data can be read from the command but before it is written to the standard error. This allows the plugin to reject data if it chooses to (for instance if the output contains banned content). Returns 1 if the data should be passed to the user, 0 if the data is rejected (which will terminate the command) or -1 if an error occurred. The function arguments are as follows: buf The buffer containing command output. len The length of _b_u_f in bytes. _V_e_r_s_i_o_n _m_a_c_r_o_s Same as for the "Policy Plugin API". CCoonnvveerrssaattiioonn AAPPII If the plugin needs to interact with the user, it may do so via the conversation function. A plugin should not attempt to read directly from the standard input or the user's tty (neither of which are guaranteed to exist). The caller must include a trailing newline in msg if one is to be printed. A printf-style function is also available that can be used to display informational or error messages to the user, which is usually more convenient for simple messages where no use input is required. 1.8.0rc1 February 21, 2011 16 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) struct sudo_conv_message { #define SUDO_CONV_PROMPT_ECHO_OFF 0x0001 /* do not echo user input */ #define SUDO_CONV_PROMPT_ECHO_ON 0x0002 /* echo user input */ #define SUDO_CONV_ERROR_MSG 0x0003 /* error message */ #define SUDO_CONV_INFO_MSG 0x0004 /* informational message */ #define SUDO_CONV_PROMPT_MASK 0x0005 /* mask user input */ #define SUDO_CONV_PROMPT_ECHO_OK 0x1000 /* flag: allow echo if no tty */ int msg_type; int timeout; const char *msg; }; struct sudo_conv_reply { char *reply; }; typedef int (*sudo_conv_t)(int num_msgs, const struct sudo_conv_message msgs[], struct sudo_conv_reply replies[]); typedef int (*sudo_printf_t)(int msg_type, const char *fmt, ...); Pointers to the conversation and printf-style functions are passed in to the plugin's open function when the plugin is initialized. To use the conversation function, the plugin must pass an array of sudo_conv_message and sudo_conv_reply structures. There must be a struct sudo_conv_message and struct sudo_conv_reply for each message in the conversation. The plugin is responsible for freeing the reply buffer filled in to the struct sudo_conv_reply, if any. The printf-style function uses the same underlying mechanism as the conversation function but only supports SUDO_CONV_INFO_MSG and SUDO_CONV_ERROR_MSG for the _m_s_g___t_y_p_e parameter. It can be more convenient than using the conversation function if no user reply is needed and supports standard _p_r_i_n_t_f_(_) escape sequences. See the sample plugin for an example of the conversation function usage. SSuuddooeerrss GGrroouupp PPlluuggiinn AAPPII The _s_u_d_o_e_r_s module supports a plugin interface to allow non-Unix group lookups. This can be used to query a group source other than the standard Unix group database. A sample group plugin is bundled with ssuuddoo that implements file-based lookups. Third party group plugins include a QAS AD plugin available from Quest Software. A group plugin must declare and populate a sudoers_group_plugin struct in the global scope. This structure contains pointers to the functions that implement plugin initialization, cleanup and group lookup. 1.8.0rc1 February 21, 2011 17 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) struct sudoers_group_plugin { unsigned int version; int (*init)(int version, sudo_printf_t sudo_printf, char *const argv[]); void (*cleanup)(void); int (*query)(const char *user, const char *group, const struct passwd *pwd); }; The sudoers_group_plugin struct has the following fields: version The version field should be set to GROUP_API_VERSION. This allows _s_u_d_o_e_r_s to determine the API version the group plugin was built against. init int (*init)(int version, sudo_printf_t plugin_printf, char *const argv[]); The _i_n_i_t function is called after _s_u_d_o_e_r_s has been parsed but before any policy checks. It returns 1 on success, 0 on failure (or if the plugin is not configured), and -1 if a error occurred. If an error occurs, the plugin may call the plugin_printf function with SUDO_CONF_ERROR_MSG to present additional error information to the user. The function arguments are as follows: version The version passed in by _s_u_d_o_e_r_s allows the plugin to determine the major and minor version number of the group plugin API supported by _s_u_d_o_e_r_s. plugin_printf A pointer to a printf-style function that may be used to display informational or error message to the user. Returns the number of characters printed on success and -1 on failure. argv A NULL-terminated array of arguments generated from the _g_r_o_u_p___p_l_u_g_i_n option in _s_u_d_o_e_r_s. If no arguments were given, _a_r_g_v will be NULL. cleanup void (*cleanup)(); The _c_l_e_a_n_u_p function is called when _s_u_d_o_e_r_s has finished its group checks. The plugin should free any memory it has allocated and close open file handles. query 1.8.0rc1 February 21, 2011 18 SUDO_PLUGIN(1m) MAINTENANCE COMMANDS SUDO_PLUGIN(1m) int (*query)(const char *user, const char *group, const struct passwd *pwd); The _q_u_e_r_y function is used to ask the group plugin whether _u_s_e_r is a member of _g_r_o_u_p. The function arguments are as follows: user The name of the user being looked up in the external group database. group The name of the group being queried. pwd The password database entry for _u_s_e_r, if any. If _u_s_e_r is not present in the password database, _p_w_d will be NULL. _V_e_r_s_i_o_n _M_a_c_r_o_s /* Sudoers group plugin version major/minor */ #define GROUP_API_VERSION_MAJOR 1 #define GROUP_API_VERSION_MINOR 0 #define GROUP_API_VERSION ((GROUP_API_VERSION_MAJOR << 16) | \ GROUP_API_VERSION_MINOR) /* Getters and setters for group version */ #define GROUP_API_VERSION_GET_MAJOR(v) ((v) >> 16) #define GROUP_API_VERSION_GET_MINOR(v) ((v) & 0xffff) #define GROUP_API_VERSION_SET_MAJOR(vp, n) do { \ *(vp) = (*(vp) & 0x0000ffff) | ((n) << 16); \ } while(0) #define GROUP_API_VERSION_SET_MINOR(vp, n) do { \ *(vp) = (*(vp) & 0xffff0000) | (n); \ } while(0) SSEEEE AALLSSOO _s_u_d_o_e_r_s(4), _s_u_d_o(1m) BBUUGGSS If you feel you have found a bug in ssuuddoo, please submit a bug report at http://www.sudo.ws/sudo/bugs/ SSUUPPPPOORRTT Limited free support is available via the sudo-workers mailing list, see http://www.sudo.ws/mailman/listinfo/sudo-workers to subscribe or search the archives. DDIISSCCLLAAIIMMEERR ssuuddoo is provided ``AS IS'' and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. See the LICENSE file distributed with ssuuddoo or http://www.sudo.ws/sudo/license.html for complete details. 1.8.0rc1 February 21, 2011 19