text
stringlengths
184
4.48M
% % Valve network planning for Advent of Code 2022 Day 16. % % From https://github.com/zayenz/advent-of-code-2022 % Instead of using differnet networks for varying hardness, this model % uses different planning horizons for adjusting the hardness of the problem. % % Model by Mikael Zayenz Lagerkvist % include "globals.mzn"; % Input enum Nodes; Nodes: first_node; array[Nodes] of int: flow; array[Nodes] of set of Nodes: connections; int: horizon; set of int: Minutes = 1..horizon; set of int: Steps = Minutes diff {1}; % Data enum Action = {Move, Open}; enum Person = {Me, Elephant}; function Person: other(Person: person) = if person = Me then Elephant else Me endif; % Variables array[Nodes, Minutes] of var bool: open; array[Minutes, Person] of var Nodes: position; array[Steps, Person] of var Action: action; array[Minutes] of var int: current_flow = array1d(Minutes, [ sum(node in Nodes) ( open[node, minute] * flow[node] ) | minute in Minutes ]); % Constraints % Initial state constraint position[1, Me] = first_node /\ position[1, Elephant] = first_node /\ forall (node in Nodes) ( open[node, 1] = false ); % Steps constraint forall (step in Steps, person in Person) ( if action[step, person] = Open then open[position[step, person], step] = true /\ forall (node in Nodes where (node != position[step, Me] /\ node != position[step, Elephant])) ( open[node, step] = open[node, step-1] ) /\ position[step, person] = position[step-1, person] else forall (node in Nodes where node != position[step, other(person)]) ( open[node, step] = open[node, step-1] ) /\ position[step, person] in connections[position[step-1, person]] endif ) /\ forall (step in Steps, node in Nodes) ( if (action[step, Me] = Open /\ position[step, Me] = node) \/ (action[step, Elephant] = Open /\ position[step, Elephant] = node) then open[node, step] = true else open[node, step] = open[node, step-1] endif ); var int: checksum = sum(current_flow); % Solve and output solve :: int_search([ [action[s, p], position[s, p]][i] | s in Steps, p in Person, i in 1..2 ], input_order, indomain_max) maximize checksum; output [ "Minute \(m): Position me=\(position[m, Me]), elephant=\(position[m, Elephant]), Open valves: \({n | n in Nodes where open[n, m]})\n" | m in Minutes ] ++ [ "checksum: ", show(checksum), "\n", ]; % % Definition of network. % % This is one possible input for the problem in https://adventofcode.com/2022/day/16 % % Multiple networks are possible to vary hardness, but planning length is used instead % for simplicity. Normally the below would be in a dzn file instead. % Nodes = { GJ, HE, ET, SG, LC, EE, AA, TF, GO, QE, MI, BR, UV, EH, WK, NT, KI, AH, EL, GP, GM, LU, LB, QC, JJ, MM, VI, NV, VT, RE, FO, DV, SQ, OQ, FF, IV, HY, ML, JS, KU, QA, EU, SV, JG, DW, UD, QJ, HU, ZR, YA, JH, OS, LG, SB, UU, VL, AO, EM}; first_node = AA; flow = [14, 0, 0, 0, 0, 13, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 22, 0, 0, 0, 9, 0, 0, 0, 0, 18, 0, 0, 0, 0, 10, 12, 23, 3, 0, 8, 0, 0, 5, 0, 0, 0, 0, 0, 0, 17, 0, 0, 0, 0, 15, 0, 4, 0, 0, 0, 0]; connections = [ {UV, AO, MM, UD, GM}, {QE, SV}, {LU, SB}, {FF, SB}, {QJ, GM}, {RE, BR}, {QC, ZR, NT, JG, FO}, {LU, MM}, {LB, AH}, {LG, HE}, {KU, FF}, {HY, EE}, {GP, GJ}, {UU, FF}, {HY, EL}, {FF, AA}, {OQ, AO}, {GO, RE}, {WK, SQ}, {SB, UV}, {LC, GJ}, {UU, DW, TF, ET, ML}, {GO, VI}, {ML, AA}, {QJ, DV}, {TF, GJ}, {LB}, {SB, KU}, {HY, JG}, {AH, EE}, {SB, AA}, {JH, UD, JJ}, {EL, QA}, {KI, IV, JS}, {EU, NT, SG, MI, EH}, {LG, OQ}, {VT, BR, WK}, {LU, QC}, {EM, OQ}, {MI, VL, NV, HU, DW}, {OS, SQ}, {FF, OS}, {QJ, HE}, {AA, VT}, {LU, KU}, {DV, GJ}, {JJ, SV, LC, EM, YA}, {JH, KU}, {AA, VL}, {QJ, OS}, {HU, DV}, {EU, YA, QA}, {QE, IV}, {FO, SG, NV, GP, ET}, {EH, LU}, {ZR, KU}, {GJ, KI}, {QJ, JS} ];
(* DO NOT EDIT THIS FILE CASUALLY !!! *) foo (* line 1 *) """ this is a triple quote confined to a single line """ (* line 2 *) # Ocaml doesn't recognize this as a comment (* line 3 *) (* This line starts a multi-line nested comment bar (* (* nested comment *) this might be a bit tricky *) *) hi (* line 4 *) (* as might this """ ;-) """ *) 'an isolated string should count as python' (* line 5 *) "even if it's DQUOTEd" (* line 6 *) """ a """ """ b ... (* line 7 *) ... (* line 8 *) and still more b """ (* line 9 *) (* That's 9 lines before the Ocaml interpreter gets involved *) (*(* doubly nested *)*) (*(*(* triply nested *)*)*) (*(* doubly nested *)*) a b c (* line 10 *) (*(*(* triply nested *)*)*) d e f (* line 11 *) (*(* doubly nested *)*) a b c (**) (* line 12 *) (*(*(* triply nested *)*)*) d e f (*(**)*) (* line 13 *) (************************************************************************* * WHAT FOLLOWS IS AN AUGEAS PROJECT LENSE AND IS COVED BY THE LGPL, * www.gnu.org/licenses/lgpl.html *************************************************************************) (* Parsing yum's config files *) module Yum = autoload xfm (************************************************************************ * INI File settings *************************************************************************) let comment = IniFile.comment "#" "#" let sep = IniFile.sep "=" "=" let empty = Util.empty let eol = IniFile.eol (************************************************************************ * ENTRY *************************************************************************) let list_entry (list_key:string) = let list_value = store /[^# \t\r\n,][^ \t\r\n,]*[^# \t\r\n,]|[^# \t\r\n,]/ in let list_sep = del /([ \t]*(,[ \t]*|\r?\n[ \t]+))|[ \t]+/ "\n\t" in [ key list_key . sep . Sep.opt_space . list_value ] . (list_sep . Build.opt_list [ label list_key . list_value ] list_sep)? . eol let entry_re = IniFile.entry_re - ("baseurl" | "gpgkey" | "exclude") let entry = IniFile.entry entry_re sep comment | empty let entries = let list_entry_elem (k:string) = list_entry k . entry* in entry* | entry* . Build.combine_three_opt (list_entry_elem "baseurl") (list_entry_elem "gpgkey") (list_entry_elem "exclude") (***********************************************************************a * TITLE *************************************************************************) let title = IniFile.title IniFile.record_re let record = [ title . entries ] (************************************************************************ * LENS & FILTER *************************************************************************) let lns = (empty | comment)* . record* let filter = (incl "/etc/yum.conf") . (incl "/etc/yum.repos.d/*.repo") . (incl "/etc/yum/yum-cron*.conf") . (incl "/etc/yum/pluginconf.d/*") . (excl "/etc/yum/pluginconf.d/versionlock.list") . Util.stdexcl let xfm = transform lns filter (* Local Variables: *) (* mode: caml *) (* End: *)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> //The cells contain 0 or 1 but the font is so small it effectively //renders them invisible const stopStartText = ["Start", "Stop"] const startTextIndex = 0 const stopTextIndex = 1 const classes = ["grid-item set-green", "grid-item set-red"] const delay = 750 const rows = 30 const cols = 30 //need to change css as well #grid var intervalHandle = null var clearId = null var count = 0 var promiseService var counterId = null var gridId = null const emptyGrid = Array(rows).fill().map(() => Array(cols).fill(0)) var startStopId = null const incCount = (value) => { count = count + value counterId.value = count.toString() } const clearCount = () => { count = 0 counterId.value = count.toString() } const nextActionsForStartPress = () => currentActions = startDisplayedActions const nextActionsForStopPress = () => currentActions = stopDisplayedActions let currentActions = null const setStopStartStop = () => { startStopId.innerText = stopStartText[stopTextIndex] startStopId.className = "set-red" } const setStopStartStart = () => { startStopId.innerText = stopStartText[startTextIndex] startStopId.className = "set-green" } const startIterations = () => { game() } const stopIterations = () => { clearInterval(intervalHandle) } const hideClearButton = () => { clearId.style.display ="none" } const showClearButton = () => { clearId.style.display ="inline" } const addGridClickHandler = () => { gridId.addEventListener('click', gridClickHandler, false); } const removeGridClickHandler = () => { gridId.removeEventListener('click', gridClickHandler, false); } //initActions on runs once on program loading //The other action lists run alternatively //Tooken xstate out. const initActions = { setStopStartStart, addGridClickHandler, nextActionsForStartPress } const startDisplayedActions = {hideClearButton, clearCount, setStopStartStop, startIterations, removeGridClickHandler, nextActionsForStopPress } const stopDisplayedActions = {stopIterations, showClearButton, setStopStartStart, addGridClickHandler, nextActionsForStartPress } const game = () => { grid = readContents() intervalHandle = setInterval(() => { grid = life(grid) writeContents(grid) incCount(1) }, delay) } const setRed = (element, aString) => { element.innerHTML = aString element.className = "grid-item set-red" } const setGreen = (element, aString) => { element.innerHTML = aString element.className = "grid-item set-green" } const gridClickHandler = (e) => { //Placing mouse in cell. Click and hold mouse down and try drag cell //results in the grid collapsing. This if statement is to fix this problem if (e.target.innerHTML.length === 1) { (e.target.innerHTML === "0") ? setRed(e.target,"1") : setGreen(e.target,"0"); readContents(); } } const executeActions = () => { Object.keys(currentActions).forEach(function(k, i) { currentActions[k]()} ) } const sendStopStart = () => { executeActions() } clearHandler = () => { clearCount() writeContents(emptyGrid) } const readContents = () => { var containerDiv = document.getElementById("grid"); var items = Array.from(containerDiv.children) // older version of the above [].slice.call(containerDiv.children) var contents = [] var index = 0 for (let i = 0; i < rows; i++) { var row = [] for (let j = 0; j < cols; j++) { row.push(parseInt(items[index].innerHTML)) index = index + 1 } contents.push(row) } //So we start with large array and return // [ [first row's cols], [second row's cols], .... ] return contents } const writeContents = (contents) => { //So we start with // [ [first row's cols], [second row's cols], .... ] //and update a large flat array var containerDiv = document.getElementById("grid"); index = 0 contents.map((aRow) => aRow.map((aCol) => { containerDiv.children[index].innerHTML = aCol.toString() containerDiv.children[index].className = (aCol === 0) ? "grid-item set-green" : "grid-item set-red" index = index + 1 })) } const boxLayOut = (rows, cols) => { var theRet = [] var index = 0 //for key for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { theRet.push( `<div class="grid-item set-green">0</div>` ) index = index + 1 } } return theRet.join(" ") } window.onload = function() { clearId = document.getElementById("clearButton") counterId = document.getElementById("counter") gridId = document.getElementById("grid"); startStopId = document.getElementById("startButton"); clearId.addEventListener('click', clearHandler, false); startStopId.addEventListener('click', sendStopStart, false); gridId.insertAdjacentHTML("beforeend", boxLayOut(rows, cols)); currentActions = initActions executeActions() } //Life code const sumValueOfSurroundingCells = (theCellRow, theCellCol, dataGrid) => { const rows = dataGrid.length const cols = dataGrid[0].length const offset = [[-1,-1],[-1,0],[-1,1], //row above cell [ 0,-1],[ 0,1], //same row as cell. Removed [0,0] [ 1,-1],[ 1,0],[ 1,1] ] //row below cell return offset.reduce((accum, valueFromOffset) => { //alert(valueFromOffset) const [row, col] = valueFromOffset const newRow = row+theCellRow const newCol = col+theCellCol //Need to check that we are not accessing values outside our grid if (newRow < 0 || newCol < 0 || newRow >= rows || newCol >= cols) { return accum } else { return accum + dataGrid[row+theCellRow][col+theCellCol] } },0) } const processCellsInRow = (aRow, rowNum, theGrid) => { return aRow.map((aCell, colNum) => { const livingCellsAround = sumValueOfSurroundingCells(rowNum, colNum, theGrid) if (aCell === 0) { //Cell is dead. If it has three living cells around it then //bring it back to life return (livingCellsAround === 3) ? 1 : 0 } else { //Cell is alive. It dies if living cells around it is //less than 2 or more than 3 return (livingCellsAround < 2 || livingCellsAround > 3) ? 0 : 1 } }) //map end } const life = (gridFull) => { //Iterate old grid gridFull values to build newGrid //console.log(gridFull) let newGrid = gridFull.map((aRow, rowNum, theGrid) => processCellsInRow(aRow, rowNum, theGrid)) //console.log(newGrid) return newGrid } </script> <title></title> <style> #startButton { margin-left: 10px; font-size: 20px; } #counter { margin-left: 10px; font-size: 20px; } #clearButton { margin-left: 10px; font-size: 20px; } .centrelock { display: grid; grid-template-columns: 1fr 1fr 1fr; } #grid { margin-top: 10px; display: grid; grid-template-columns: repeat(30, 20px); } .grid-item { border: 1px solid rgba(0, 0, 0, 0.8); font-size: 1px; height: 20px; } .set-red { background-color: red; } .set-green { background-color: green; } </style> </head> <body> <div> <h1>Conway's Game of Life</h1> <button id="startButton">Will be replaced</button> <input id="counter"/> <button id="clearButton">Clear</button> </div> <div id="grid"></div> </body> </html>
"""Removes duplicate entries from a JSONL file.""" import warnings import click import json from pathlib import Path import logging from huggingface_hub import HfApi from huggingface_hub.hf_api import RepositoryNotFoundError import re from tqdm.auto import tqdm logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s" ) logger = logging.getLogger(__name__) MERGE_CACHE: dict[str, bool] = dict() COMMERCIALLY_LICENSED_CACHE: dict[str, bool] = dict() @click.command() @click.argument('filename') def main(filename: str) -> None: """Removes duplicate entries from a JSONL file. Args: filename: The path to the JSONL file. """ records = list() with Path(filename).open(mode="r") as f: for line_idx, line in enumerate(f): if not line.strip(): continue for record in line.replace("}{", "}\n{").split("\n"): if not record.strip(): continue try: records.append(json.loads(record)) except json.JSONDecodeError: logger.error(f"Invalid JSON on line {line_idx:,}: {record}.") return num_raw_records = len(records) # Build caches global MERGE_CACHE global COMMERCIALLY_LICENSED_CACHE for record in tqdm(records, desc="Building caches"): model_id = record["model"].split("@")[0] if "merge" in record: MERGE_CACHE[model_id] = record["merge"] if "commercially_licensed" in record: COMMERCIALLY_LICENSED_CACHE[model_id] = record["commercially_licensed"] records = [ add_missing_entries(record=record) for record in tqdm(records, desc="Adding missing entries") ] # Remove invalid evaluation records records = [record for record in records if record_is_valid(record=record)] num_invalid_records = num_raw_records - len(records) if num_invalid_records > 0: logger.info(f"Removed {num_invalid_records:,} invalid records from {filename}.") # Filter records all_hash_values = [get_hash(dct) for dct in records] unique_hash_values = sorted(set(all_hash_values)) new_records = list() for unique_hash_value in tqdm(unique_hash_values, desc="Processing records"): matches = [ record for record, hash_value in zip(records, all_hash_values) if hash_value == unique_hash_value ] versions = [ list(map(int, match.get("scandeval_version", "0.0.0").split("."))) for match in matches ] newest_version = max(versions) matches_with_newest_version = [ match for match, version in zip(matches, versions) if version == newest_version ] newest_match = matches_with_newest_version[-1] new_records.append(newest_match) records = new_records num_duplicates = num_raw_records - num_invalid_records - len(records) if num_duplicates: logger.info(f"Removed {num_duplicates:,} duplicates from {filename}.") with Path(filename).open(mode="w") as f: for record in records: f.write(json.dumps(record) + "\n") records_without_extras = list() for record in records: record.pop("merge") record.pop("commercially_licensed") records_without_extras.append(record) with Path(filename).with_suffix(".no_extras.jsonl").open(mode="w") as f: for record in records_without_extras: f.write(json.dumps(record) + "\n") def add_missing_entries(record: dict) -> dict: """Adds missing entries to a record. Args: record: A record from the JSONL file. Returns: The record with missing entries added. """ if "validation_split" not in record: record["validation_split"] = False if "few_shot" not in record: record["few_shot"] = True if "generative" not in record: record["generative"] = False record["merge"] = is_merge(record=record) record["commercially_licensed"] = is_commercially_licensed(record=record) return record def is_commercially_licensed(record: dict) -> bool: """Asks if a model is commercially licensed. Args: record: A record from the JSONL file. Returns: Whether the model is commercially licensed. """ global COMMERCIALLY_LICENSED_CACHE # Remove revisions from model ID model_id = record["model"].split("@")[0] # Assume that non-generative models are always commercially licensed if not record.get("generative", True): COMMERCIALLY_LICENSED_CACHE[model_id] = True while True: if model_id in COMMERCIALLY_LICENSED_CACHE: return COMMERCIALLY_LICENSED_CACHE[model_id] msg = f"Is {model_id!r} commercially licensed?" if "/" in model_id: msg += f" (https://huggingface.co/{model_id})" msg += " [y/n] " user_input = input(msg) if user_input.lower() in {"y", "yes"}: COMMERCIALLY_LICENSED_CACHE[model_id] = True elif user_input.lower() in {"n", "no"}: COMMERCIALLY_LICENSED_CACHE[model_id] = False else: print("Invalid input. Please try again.") continue def get_hash(record: dict) -> str: """Returns a hash value for a record. Args: record: A record from the JSONL file. Returns: A hash value for the record. """ model = record["model"] dataset = record["dataset"] validation_split = int(record.get("validation_split", False)) few_shot = int(record.get("few_shot", True)) generative = int(record.get("generative", False)) return f"{model}{dataset}{validation_split}{few_shot * generative}" def is_merge(record: dict) -> bool: """Determines if a model is a merged model. Args: record: A record from the JSONL file. Returns: Whether the model is a merged model. """ # Remove revisions from model ID model_id = record["model"].split("@")[0] # Return cached value if available global MERGE_CACHE if model_id in MERGE_CACHE: return MERGE_CACHE[model_id] # Fresh models do not appear on the model hub, so we assume they are not merge # models if model_id.startswith("fresh"): MERGE_CACHE[model_id] = False return False # Fetch model info from the model hub, and assume that it is not a merged model if # the model is not found api = HfApi() try: with warnings.catch_warnings(): warnings.simplefilter("ignore", category=UserWarning) model_info = api.model_info(repo_id=model_id) except RepositoryNotFoundError: MERGE_CACHE[model_id] = False return False # A model is a merge model if it has merge-related tags merge_tags = ["merge", "mergekit"] has_merge_tag = any(tag in model_info.tags for tag in merge_tags) MERGE_CACHE[model_id] = has_merge_tag return has_merge_tag def record_is_valid(record: dict) -> bool: """Determine if a record is valid. Args: record: The record to validate. Returns: True if the record is valid, False otherwise. """ BANNED_VERSIONS: list[str] = ["9.3.0", "10.0.0"] if record.get("version") in BANNED_VERSIONS: return False merged_model = record.get("merge", False) evaluated_on_validation_split = record.get("validation_split", False) openai_model = re.search(r"gpt-[34][-.0-9a-z]+", record.get("model", "")) large_model = record["num_model_parameters"] > 60_000_000_000 if ( (merged_model and not evaluated_on_validation_split) or ( not merged_model and evaluated_on_validation_split and not openai_model and not large_model ) ): return False return True if __name__ == "__main__": main()
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.17; import {SafeERC20} from "openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IERC20Metadata} from "openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {TypeCasts} from "../../../shared/libraries/TypeCasts.sol"; import {IStableSwap} from "../interfaces/IStableSwap.sol"; import {LibConnextStorage, AppStorage, TokenConfig} from "./LibConnextStorage.sol"; import {SwapUtils} from "./SwapUtils.sol"; import {Constants} from "./Constants.sol"; import {TokenId} from "./TokenId.sol"; library AssetLogic { using SwapUtils for SwapUtils.Swap; using SafeERC20 for IERC20Metadata; error AssetLogic__handleIncomingAsset_nativeAssetNotSupported(); error AssetLogic__handleIncomingAsset_feeOnTransferNotSupported(); error AssetLogic__handleOutgoingAsset_notNative(); error AssetLogic__getTokenIndexFromStableSwapPool_notExist(); error AssetLogic__getConfig_notRegistered(); error AssetLogic__swapAsset_externalStableSwapPoolDoesNotExist(); function getConfig(bytes32 _key) internal view returns (TokenConfig storage) { AppStorage storage s = LibConnextStorage.connextStorage(); TokenConfig storage config = s.tokenConfigs[_key]; // Sanity check: not empty // NOTE: adopted decimals will *always* be nonzero (or reflect what is onchain // for the asset). The same is not true for the representation assets, which // will always have 0 decimals on the canonical domain if (config.adoptedDecimals < 1) { revert AssetLogic__getConfig_notRegistered(); } return config; } /** * notice Handles transferring funds from msg.sender to the Connext contract. * dev Does NOT work with fee-on-transfer tokens: will revert. * * param _asset - The address of the ERC20 token to transfer. * param _amount - The specified amount to transfer. */ function handleIncomingAsset(address _asset, uint256 _amount) internal { // Sanity check: if amount is 0, do nothing. if (_amount == 0) { return; } // Sanity check: asset address is not zero. if (_asset == address(0)) { revert AssetLogic__handleIncomingAsset_nativeAssetNotSupported(); } IERC20Metadata asset = IERC20Metadata(_asset); // Record starting amount to validate correct amount is transferred. uint256 starting = asset.balanceOf(address(this)); // Transfer asset to contract. asset.safeTransferFrom(msg.sender, address(this), _amount); // Ensure correct amount was transferred (i.e. this was not a fee-on-transfer token). if (asset.balanceOf(address(this)) - starting != _amount) { revert AssetLogic__handleIncomingAsset_feeOnTransferNotSupported(); } } /** * notice Handles transferring funds from the Connext contract to a specified address * param _asset - The address of the ERC20 token to transfer. * param _to - The recipient address that will receive the funds. * param _amount - The amount to withdraw from contract. */ function handleOutgoingAsset( address _asset, address _to, uint256 _amount ) internal { // Sanity check: if amount is 0, do nothing. if (_amount == 0) { return; } // Sanity check: asset address is not zero. if (_asset == address(0)) revert AssetLogic__handleOutgoingAsset_notNative(); // Transfer ERC20 asset to target recipient. SafeERC20.safeTransfer(IERC20Metadata(_asset), _to, _amount); } /** * notice Return the index of the given token address. Reverts if no matching * token is found. * param key the hash of the canonical id and domain * param tokenAddress address of the token * return the index of the given token address */ function getTokenIndexFromStableSwapPool(bytes32 key, address tokenAddress) internal view returns (uint8) { AppStorage storage s = LibConnextStorage.connextStorage(); uint8 index = s.tokenIndexes[key][tokenAddress]; if (address(s.swapStorages[key].pooledTokens[index]) != tokenAddress) revert AssetLogic__getTokenIndexFromStableSwapPool_notExist(); return index; } /** * notice Swaps an adopted asset to the local (representation or canonical) asset. * dev Will not swap if the asset passed in is the local asset. * param _key - The hash of canonical id and domain. * param _asset - The address of the adopted asset to swap into the local asset. * param _amount - The amount of the adopted asset to swap. * param _slippage - The maximum amount of slippage user will take on from _amount in BPS. * return uint256 The amount of local asset received from swap. */ function swapToLocalAssetIfNeeded( bytes32 _key, address _asset, address _local, uint256 _amount, uint256 _slippage ) internal returns (uint256) { // If there's no amount, no need to swap. if (_amount == 0) { return 0; } // Check the case where the adopted asset *is* the local asset. If so, no need to swap. if (_local == _asset) { return _amount; } // Get the configs. TokenConfig storage config = getConfig(_key); // Swap the asset to the proper local asset. (uint256 out, ) = _swapAsset( _key, _asset, _local, _amount, calculateSlippageBoundary(config.adoptedDecimals, config.representationDecimals, _amount, _slippage) ); return out; } /** * notice Swaps a local bridge asset for the adopted asset using the stored stable swap * dev Will not swap if the asset passed in is the adopted asset * param _key the hash of the canonical id and domain * param _asset - The address of the local asset to swap into the adopted asset * param _amount - The amount of the local asset to swap * param _slippage - The minimum amount of slippage user will take on from _amount in BPS * param _normalizedIn - The amount sent in on xcall to take the slippage from, in 18 decimals * by convention * return The amount of adopted asset received from swap * return The address of asset received post-swap */ function swapFromLocalAssetIfNeeded( bytes32 _key, address _asset, uint256 _amount, uint256 _slippage, uint256 _normalizedIn ) internal returns (uint256, address) { // Get the token config. TokenConfig storage config = getConfig(_key); address adopted = config.adopted; // If the adopted asset is the local asset, no need to swap. if (adopted == _asset) { return (_amount, adopted); } // If there's no amount, no need to swap. if (_amount == 0) { return (_amount, adopted); } // Swap the asset to the proper local asset return _swapAsset( _key, _asset, adopted, _amount, // NOTE: To get the slippage boundary here, you must take the slippage % off of the // normalized amount in (at 18 decimals by convention), then convert that amount // to the proper decimals of adopted. calculateSlippageBoundary( Constants.DEFAULT_NORMALIZED_DECIMALS, config.adoptedDecimals, _normalizedIn, _slippage ) ); } /** * notice Swaps a local bridge asset for the adopted asset using the stored stable swap * dev Will not swap if the asset passed in is the adopted asset * param _key the hash of the canonical id and domain * param _asset - The address of the local asset to swap into the adopted asset * param _amount - The exact amount to receive out of the swap * param _maxIn - The most you will supply to the swap * return The amount of local asset put into swap * return The address of asset received post-swap */ function swapFromLocalAssetIfNeededForExactOut( bytes32 _key, address _asset, uint256 _amount, uint256 _maxIn ) internal returns (uint256, address) { TokenConfig storage config = getConfig(_key); // If the adopted asset is the local asset, no need to swap. address adopted = config.adopted; if (adopted == _asset) { return (_amount, adopted); } return _swapAssetOut(_key, _asset, adopted, _amount, _maxIn); } /** * notice Swaps assetIn to assetOut using the stored stable swap or internal swap pool. * dev Will not swap if the asset passed in is the adopted asset * param _key - The hash of canonical id and domain. * param _assetIn - The address of the from asset * param _assetOut - The address of the to asset * param _amount - The amount of the local asset to swap * param _minOut - The minimum amount of `_assetOut` the user will accept * return The amount of asset received * return The address of asset received */ function _swapAsset( bytes32 _key, address _assetIn, address _assetOut, uint256 _amount, uint256 _minOut ) internal returns (uint256, address) { AppStorage storage s = LibConnextStorage.connextStorage(); // Retrieve internal swap pool reference. SwapUtils.Swap storage ipool = s.swapStorages[_key]; if (ipool.exists()) { // Swap via the internal pool. return ( ipool.swapInternal( getTokenIndexFromStableSwapPool(_key, _assetIn), getTokenIndexFromStableSwapPool(_key, _assetOut), _amount, _minOut ), _assetOut ); } else { // Otherwise, swap via external stableswap pool. IStableSwap pool = IStableSwap(getConfig(_key).adoptedToLocalExternalPools); IERC20Metadata assetIn = IERC20Metadata(_assetIn); assetIn.safeApprove(address(pool), 0); assetIn.safeIncreaseAllowance(address(pool), _amount); // NOTE: If pool is not registered here, then this call will revert. return ( pool.swapExact(_amount, _assetIn, _assetOut, _minOut, block.timestamp + Constants.DEFAULT_DEADLINE_EXTENSION), _assetOut ); } } /** * notice Swaps assetIn to assetOut using the stored stable swap or internal swap pool. * param _key - The hash of the canonical id and domain. * param _assetIn - The address of the from asset. * param _assetOut - The address of the to asset. * param _amountOut - The amount of the _assetOut to swap. * param _maxIn - The most you will supply to the swap. * return amountIn The amount of assetIn. Will be 0 if the swap was unsuccessful (slippage * too high). * return assetOut The address of asset received. */ function _swapAssetOut( bytes32 _key, address _assetIn, address _assetOut, uint256 _amountOut, uint256 _maxIn ) internal returns (uint256, address) { AppStorage storage s = LibConnextStorage.connextStorage(); // Retrieve internal swap pool reference. If it doesn't exist, we'll resort to using an // external stableswap below. SwapUtils.Swap storage ipool = s.swapStorages[_key]; // Swap the asset to the proper local asset. // NOTE: IFF slippage was too high to perform swap in either case: success = false, amountIn = 0 if (ipool.exists()) { // Swap via the internal pool. return ( ipool.swapInternalOut( getTokenIndexFromStableSwapPool(_key, _assetIn), getTokenIndexFromStableSwapPool(_key, _assetOut), _amountOut, _maxIn ), _assetOut ); } else { // Otherwise, swap via external stableswap pool. // NOTE: This call will revert if the external stableswap pool doesn't exist. IStableSwap pool = IStableSwap(getConfig(_key).adoptedToLocalExternalPools); address poolAddress = address(pool); // Perform the swap. // Edge case with some tokens: Example USDT in ETH Mainnet, after the backUnbacked call // there could be a remaining allowance if not the whole amount is pulled by aave. // Later, if we try to increase the allowance it will fail. USDT demands if allowance // is not 0, it has to be set to 0 first. // Example: https://github.com/aave/aave-v3-periphery/blob/ca184e5278bcbc10d28c3dbbc604041d7cfac50b/contracts/adapters/paraswap/ParaSwapRepayAdapter.sol#L138-L140 IERC20Metadata assetIn = IERC20Metadata(_assetIn); assetIn.safeApprove(poolAddress, 0); assetIn.safeIncreaseAllowance(poolAddress, _maxIn); uint256 out = pool.swapExactOut( _amountOut, _assetIn, _assetOut, _maxIn, block.timestamp + Constants.DEFAULT_DEADLINE_EXTENSION ); // Reset allowance assetIn.safeApprove(poolAddress, 0); return (out, _assetOut); } } /** * notice Calculate amount of tokens you receive on a local bridge asset for the adopted asset * using the stored stable swap * dev Will not use the stored stable swap if the asset passed in is the local asset * param _key - The hash of the canonical id and domain * param _asset - The address of the local asset to swap into the local asset * param _amount - The amount of the local asset to swap * return The amount of local asset received from swap * return The address of asset received post-swap */ function calculateSwapFromLocalAssetIfNeeded( bytes32 _key, address _asset, uint256 _amount ) internal view returns (uint256, address) { AppStorage storage s = LibConnextStorage.connextStorage(); // If the adopted asset is the local asset, no need to swap. TokenConfig storage config = getConfig(_key); address adopted = config.adopted; if (adopted == _asset) { return (_amount, adopted); } SwapUtils.Swap storage ipool = s.swapStorages[_key]; // Calculate the swap using the appropriate pool. if (ipool.exists()) { // Calculate with internal swap pool. uint8 tokenIndexIn = getTokenIndexFromStableSwapPool(_key, _asset); uint8 tokenIndexOut = getTokenIndexFromStableSwapPool(_key, adopted); return (ipool.calculateSwap(tokenIndexIn, tokenIndexOut, _amount), adopted); } else { // Otherwise, try to calculate with external pool. IStableSwap pool = IStableSwap(config.adoptedToLocalExternalPools); // NOTE: This call will revert if no external pool exists. return (pool.calculateSwapFromAddress(_asset, adopted, _amount), adopted); } } /** * notice Calculate amount of tokens you receive of a local bridge asset for the adopted asset * using the stored stable swap * dev Will not use the stored stable swap if the asset passed in is the local asset * param _asset - The address of the asset to swap into the local asset * param _amount - The amount of the asset to swap * return The amount of local asset received from swap * return The address of asset received post-swap */ function calculateSwapToLocalAssetIfNeeded( bytes32 _key, address _asset, address _local, uint256 _amount ) internal view returns (uint256, address) { AppStorage storage s = LibConnextStorage.connextStorage(); // If the asset is the local asset, no swap needed if (_asset == _local) { return (_amount, _local); } SwapUtils.Swap storage ipool = s.swapStorages[_key]; // Calculate the swap using the appropriate pool. if (ipool.exists()) { // if internal swap pool exists uint8 tokenIndexIn = getTokenIndexFromStableSwapPool(_key, _asset); uint8 tokenIndexOut = getTokenIndexFromStableSwapPool(_key, _local); return (ipool.calculateSwap(tokenIndexIn, tokenIndexOut, _amount), _local); } else { IStableSwap pool = IStableSwap(getConfig(_key).adoptedToLocalExternalPools); return (pool.calculateSwapFromAddress(_asset, _local, _amount), _local); } } /** * notice Gets the canonical information for a given candidate. * dev First checks the `address(0)` convention, then checks if the asset given is the * adopted asset, then calculates the local address. * return TokenId The canonical token ID information for the given candidate. */ function getCanonicalTokenId(address _candidate, AppStorage storage s) internal view returns (TokenId memory) { TokenId memory _canonical; // If candidate is address(0), return an empty `_canonical`. if (_candidate == address(0)) { return _canonical; } // Check to see if candidate is an adopted asset. _canonical = s.adoptedToCanonical[_candidate]; if (_canonical.domain != 0) { // Candidate is an adopted asset, return canonical info. return _canonical; } // Candidate was not adopted; it could be the local address. // IFF this domain is the canonical domain, then the local == canonical. // Otherwise, it will be the representation asset. if (isLocalOrigin(_candidate, s)) { // The token originates on this domain, canonical information is the information // of the candidate _canonical.domain = s.domain; _canonical.id = TypeCasts.addressToBytes32(_candidate); } else { // on a remote domain, return the representation _canonical = s.representationToCanonical[_candidate]; } return _canonical; } /** * notice Determine if token is of local origin (i.e. it is a locally originating contract, * and NOT a token deployed by the bridge). * param s AppStorage instance. * return bool true if token is locally originating, false otherwise. */ function isLocalOrigin(address _token, AppStorage storage s) internal view returns (bool) { // If the token contract WAS deployed by the bridge, it will be stored in this mapping. // If so, the token is NOT of local origin. if (s.representationToCanonical[_token].domain != 0) { return false; } // If the contract was NOT deployed by the bridge, but the contract does exist, then it // IS of local origin. Returns true if code exists at `_addr`. return _token.code.length != 0; } /** * notice Get the local asset address for a given canonical key, id, and domain. * param _key - The hash of canonical id and domain. * param _id Canonical ID. * param _domain Canonical domain. * param s AppStorage instance. * return address of the the local asset. */ function getLocalAsset( bytes32 _key, bytes32 _id, uint32 _domain, AppStorage storage s ) internal view returns (address) { if (_domain == s.domain) { // Token is of local origin return TypeCasts.bytes32ToAddress(_id); } else { // Token is a representation of a token of remote origin return getConfig(_key).representation; } } /** * notice Calculates the hash of canonical ID and domain. * dev This hash is used as the key for many asset-related mappings. * param _id Canonical ID. * param _domain Canonical domain. * return bytes32 Canonical hash, used as key for accessing token info from mappings. */ function calculateCanonicalHash(bytes32 _id, uint32 _domain) internal pure returns (bytes32) { return keccak256(abi.encode(_id, _domain)); } /** * notice This function calculates slippage as a %age of the amount in, and normalizes * That to the `_out` decimals. * * dev This *ONLY* works for 1:1 assets * * param _in The decimals of the asset in / amount in * param _out The decimals of the target asset * param _amountIn The starting amount for the swap * param _slippage The slippage allowed for the swap, in BPS * return uint256 The minimum amount out for the swap */ function calculateSlippageBoundary( uint8 _in, uint8 _out, uint256 _amountIn, uint256 _slippage ) internal pure returns (uint256) { if (_amountIn == 0) { return 0; } // Get the min recieved (in same decimals as _amountIn) uint256 min = (_amountIn * (Constants.BPS_FEE_DENOMINATOR - _slippage)) / Constants.BPS_FEE_DENOMINATOR; return normalizeDecimals(_in, _out, min); } /** * notice This function translates the _amount in _in decimals * to _out decimals * * param _in The decimals of the asset in / amount in * param _out The decimals of the target asset * param _amount The value to normalize to the `_out` decimals * return uint256 Normalized decimals. */ function normalizeDecimals( uint8 _in, uint8 _out, uint256 _amount ) internal pure returns (uint256) { if (_in == _out) { return _amount; } // Convert this value to the same decimals as _out uint256 normalized; if (_in < _out) { normalized = _amount * (10**(_out - _in)); } else { normalized = _amount / (10**(_in - _out)); } return normalized; } }
import { ICard, ICardImage, BanlistInfo } from './card.interface'; enum Category { MONSTER, SPELL, TRAP, } const trapCardId = 'Trap Card'; const spellCardId = 'Spell Card'; export class Card { id: number; name: string; type: string; race: string; desc: string; card_images: ICardImage[]; archetype?: string; banlist_info?: BanlistInfo; atk?: number; def?: number; level?: number; attribute?: string; linkval?: number; linkmarkers?: string[]; get isMonster() { return this.category === Category.MONSTER; } get isSpell() { return this.category === Category.SPELL; } get isTrap() { return this.category === Category.TRAP; } private get category(): Category { if (this.type === spellCardId) return Category.SPELL; if (this.type === trapCardId) return Category.TRAP; return Category.MONSTER; } constructor(private readonly card: ICard) { this.id = card.id; this.name = card.name; this.type = card.type; this.race = card.race; this.desc = card.desc; this.card_images = card.card_images; this.archetype = card.archetype; this.banlist_info = card.banlist_info; this.atk = card.atk; this.def = card.def; this.level = card.level; this.attribute = card.attribute; this.linkval = card.linkval; this.linkmarkers = card.linkmarkers; } }
import { HttpClient } from '@angular/common/http'; import { EventEmitter, Injectable } from '@angular/core'; import { Observable, catchError, map, throwError } from 'rxjs'; import { Producto } from '../models/producto'; const API_URL = 'https://static.compragamer.com/test/productos.json'; @Injectable({ providedIn: 'root' }) export class ProductoService { public eventoAgregarAlCarrito = new EventEmitter(); private productosAgregadosAlCarrito: number[] = []; constructor(private http: HttpClient) { } public obtenerDestacados(): Observable<Producto[]> { return this.http.get<Producto[]>(API_URL) .pipe( map(response => response.filter(producto => producto.destacado == 1)), catchError(ex => throwError(() => ex)) ); } public obtenerPorSubcategoria(idSubcategoria: number): Observable<Producto[]> { return this.http.get<Producto[]>(API_URL).pipe( map(response => response.filter(producto => producto.id_subcategoria == idSubcategoria)), catchError(ex => throwError(() => ex)) ); } public obtenerPorNombre(nombre: string): Observable<Producto[]> { return this.http.get<Producto[]>(API_URL).pipe( map(response => response.filter(producto => producto.nombre.toLowerCase().includes(nombre.toLowerCase()))), catchError(ex => throwError(() => ex)) ); } public agregarAlCarrito(producto: Producto): void { if (!this.estaEnElCarrito(producto)) { this.productosAgregadosAlCarrito.push(producto.id_producto); } } public estaEnElCarrito(producto: Producto): boolean { return this.productosAgregadosAlCarrito.find(id => id == producto.id_producto) !== undefined; } }
// // FailViewModel.swift // CombineLearning // // Created by Artem Vinogradov on 14.06.2022. // import Foundation import Combine enum InvalidNumError: Error { case lessThanZero case moreThanTen } class FailViewModel: ObservableObject { @Published var num = 0 @Published var error: InvalidNumError? func save(num: Int) { _ = Validator.validValue(num: num) // we alredy has a logic in this publisher from Validator .sink(receiveCompletion: { [unowned self] completion in if case .failure(let error) = completion { self.error = error } }, receiveValue: { [unowned self] num in self.num = num }) } } class Validator: Identifiable, ObservableObject { static func validValue(num: Int) -> AnyPublisher<Int, InvalidNumError> { // Able to return different publisher if num < 0 { return Fail(error: InvalidNumError.lessThanZero) .eraseToAnyPublisher() // We use it to make all a common type of publisher that returns an Int or InvalidNumError } else if num > 10 { return Fail(error: InvalidNumError.moreThanTen) .eraseToAnyPublisher() } return Just(num) .setFailureType(to: InvalidNumError.self) // In coomon way Just publisher doesn't throw an error. We use it to match up the failure types .eraseToAnyPublisher() } } extension InvalidNumError: CustomStringConvertible { public var description: String { switch self { case .lessThanZero: return "Less Than Zero" case .moreThanTen: return "More Than Ten" } } }
<template> <div> <!-- 검색어 입력 input --> <div class="searchfield-wrap"> <input id="searchfield" type="text" :placeholder="placeholder" @touchstart="recentKeyword = true, dimmed = true" @keyup="relatedKeyword = true, recentKeyword = false" > <img class="img-search" inline src="@/assets/images/icon_24/appbar_search.svg" aria-hidden="true"> </div> <!-- 최근 검색어 리스트 --> <div v-if="showRecentKeyword" class="recent-list"> <p class="tit">최근검색어</p> <ul> <li v-for="item in recentKeywordData" :key="item"> <button class="recent-keyword"> {{ item.name }} </button> <button class="btn-close"> <span class="sr-only">닫기</span> </button> </li> </ul> </div> <!-- 연관 검색어 리스트 --> <div v-if="relatedKeyword" class="related-list"> <ul> <li v-for="item in relatedKeywordData" :key="item"> <button class="related-keyword"> {{ item.name }} </button> </li> </ul> </div> <!-- dimm --> <div v-if="dimmed" class="dimm" aria-hidden="true" @touchstart=" (recentKeyword = false), (relatedKeyword = false), (dimmed = false) " /> </div> </template> <script> export default { props: { placeholder: { type: String, default: "placeholder", }, recentKeywordData: [], relatedKeywordData: [], }, data() { return { recentKeyword: false, relatedKeyword: false, dimmed: false, }; }, computed: { showRecentKeyword() { return this.recentKeyword == true && this.relatedKeyword == false; }, }, }; </script> <style lang="scss" scoped> .searchfield-wrap { position: relative; } #searchfield { display: flex; align-items: center; padding: 0 56px 0 16px; width: 100%; height: 46px; margin-top: 16px; border: 1px solid var(--gray-5); border-radius: 8px; } .img-search { position: absolute; top: 10px; right: 16px; width: 24px; height: 24px; } .recent-list { position: sticky; margin-left: -22px; width: calc(100% + 44px); height: auto; padding: 30px 22px 38px; background-color: var(--white); z-index: 20; &.top { top: 90px; } .tit { font-weight: 700; } > ul { margin-top: 20px; > li { display: flex; align-items: center; position: relative; margin-left: 30px; &::before { content: ''; position: absolute; left: -30px; width: 16px; height: 16px; background: url('@/assets/images/icon_16/time.png') center no-repeat; background-size: 100%; } .recent-keyword { width: calc(100% - 28px); padding: 8px 0; margin-right: 14px; text-align: left; overflow: hidden; text-overflow: ellipsis; } .btn-close { width: 14px; height: 14px; background: url('@/assets/images/icon_14/close.png') center no-repeat; background-size: 100%; } } } } .related-list { position: sticky; margin-left: -22px; width: calc(100% + 44px); height: auto; padding: 10px 22px 38px; background-color: var(--white); z-index: 20; > ul { > li { display: flex; position: relative; align-items: center; margin-left: 28px; .related-keyword { padding: 8px 0; width: 100%; overflow: hidden; text-overflow: ellipsis; text-align: left; } &::before { content: ''; position: absolute; left: -28px; width: 12px; height: 12px; background: url('@/assets/images/icon_24/link.png') center no-repeat; background-size: 100%; } } } } .dimm { position: absolute; top: 124px; left: 0; width: 100%; height: calc(100vh - 124px); background-color: rgba(22, 22, 22, 0.4); z-index: 10; } </style>
<!DOCTYPE html> <html> <head> <title>Home</title> <style> /* Add some styling to the page */ body { margin: 0; padding: 0; font-family: sans-serif; } .container { display: flex; justify-content: center; align-items: center; height: 100vh; } .welcome-message { text-align: center; } .welcome-message h1 { margin-bottom: 20px; } .welcome-message p { margin-bottom: 20px; } .welcome-message button { height: 30px; width: 100px; background-color: #4caf50; border: none; color: white; font-size: 16px; cursor: pointer; } </style> </head> <body> <div class="container"> <div class="welcome-message"> <h1>Welcome to the Ticket Tracker!</h1> <p>Use the navigation menu to log in and create tickets.</p> <a href="{{ url_for('login') }}"><button>Log in</button></a> </div> </div> <div class="container"> <form onsubmit="searchForTicket(); return false;"> <label for="identifier">Ticket Search (by Identifier):</label><br> <input type="text" id="identifier"><br> <input type="submit" value="Search"> </form> <div id="search-results-container"></div> </div> <script> function searchForTicket() { // Get the identifier from the input field var identifier = document.getElementById('identifier').value; // Send a request to the server to search for the ticket var xhr = new XMLHttpRequest(); xhr.open('POST', '/search_ticket'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status === 200) { // Redirect to the ticket details page var result = JSON.parse(xhr.responseText); if (result.length > 0) { // A result was found, so redirect to the ticket details page window.location.href = '/ticket_details?identifier=' + identifier; } else { // No result was found, so display a message displaySearchResults(result); } } }; xhr.send(JSON.stringify({ 'identifier': identifier })); } function displaySearchResults(results) { // Clear any existing search results var searchResultsContainer = document.getElementById('search-results-container'); searchResultsContainer.innerHTML = ''; // Check if there are any results to display if (results.length === 0) { // No results were found searchResultsContainer.innerHTML = '<p>No results found</p>'; } else { // Results were found, so display them in a table // Create a table to hold the results var resultsTable = document.createElement('table'); // Add a table row for each result results.forEach(function(result) { var row = document.createElement('tr'); var identifierCell = document.createElement('td'); identifierCell.textContent = result.identifier; row.appendChild(identifierCell); // Add cells for the other data fields var requestedItemCell = document.createElement('td'); requestedItemCell.textContent = result.requested_item; row.appendChild(requestedItemCell); var departmentCell = document.createElement('td'); departmentCell.textContent = result.department; row.appendChild(departmentCell); var projectCell = document.createElement('td'); projectCell.textContent = result.project; row.appendChild(projectCell); var statusCell = document.createElement('td'); statusCell.textContent = result.status; row.appendChild(statusCell); // Append the row to the table resultsTable.appendChild(row); }); // Append the table to the searchResultsContainer element searchResultsContainer.appendChild(resultsTable); } } </script> </body> </html>
from flask import Flask, render_template, request, redirect, url_for, flash from flask_sqlalchemy import SQLAlchemy from sqlalchemy.exc import IntegrityError from sqlalchemy import func from flask_bootstrap import Bootstrap # Flask WTF from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField from wtforms.validators import DataRequired, Email class GuestbookForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) name = StringField('Name', validators=[DataRequired()]) message = TextAreaField('Message', validators=[DataRequired()]) app = Flask(__name__) # Configure the SQLite database URI # SQLite database file app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///guestbook.db' app.secret_key = '8abb191586453f50cd47b9f13caa2ae8' db = SQLAlchemy(app) # Initialize Flask-Bootstrap bootstrap = Bootstrap(app) # Define the model for your guestbook entries class GuestEntry(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(120), nullable=False) name = db.Column(db.String(120), nullable=False) message = db.Column(db.Text, nullable=False) @app.route('/', methods=['GET', 'POST']) def guestbook_form(): form = GuestbookForm() if request.method == 'POST': email = request.form['email'] name = request.form['name'] message = request.form['message'] # Perform server-side validation here if not email or not name or not message: flash('All fields are required', 'error') else: # Data is valid, insert it into the database try: entry = GuestEntry(email=email, name=name, message=message) db.session.add(entry) db.session.commit() flash('Entry added to the guestbook', 'success') except IntegrityError: db.session.rollback() flash('An error occurred while adding the entry', 'error') return redirect(url_for('guestbook_form')) return render_template('guestbook_form.html', form=form) @app.route('/view_guestbook', methods=['GET']) def view_guestbook(): filter_name = request.args.get('filter') sort_option = request.args.get('sort') entries_query = GuestEntry.query if filter_name: entries_query = entries_query.filter(func.lower( GuestEntry.name).contains(filter_name.lower())) if sort_option == 'name_asc': entries_query = entries_query.order_by(GuestEntry.name) elif sort_option == 'name_desc': entries_query = entries_query.order_by(GuestEntry.name.desc()) elif sort_option == 'date_asc': entries_query = entries_query.order_by(GuestEntry.id) elif sort_option == 'date_desc': entries_query = entries_query.order_by(GuestEntry.id.desc()) entries = entries_query.all() return render_template('view_guestbook.html', entries=entries) if __name__ == '__main__': app.run(debug=True)
# Glaze calculator import numpy as np import re class Element: def __init__(self, symbol, name, atWt): self.symbol = symbol self.name = name self.atWt = atWt element_data = [ \ ('Aluminum', 'Al', 26.97), \ ('Barium', 'Ba', 137.36), \ ('Bismuth', 'Bi', 209.00), \ ('Boron', 'B', 10.82), \ ('Cadmium', 'Cd', 112.42), \ ('Calcium', 'Ca', 40.08),\ ('Carbon', 'C', 12.01),\ ('Chlorine', 'Cl', 35.457),\ ('Chromium', 'Cr', 52.01),\ ('Cobalt', 'Co', 58.94),\ ('Copper', 'Cu', 63.54),\ ('Flourine', 'F', 19.00),\ ('Gold', 'Au', 197.20),\ ('Hydrogen', 'H', 1.008),\ ('Iron', 'Fe', 55.84),\ ('Lead', 'Pb', 207.21),\ ('Lithium', 'Li', 6.94),\ ('Magnesium', 'Mg', 24.32),\ ('Manganese', 'Mn', 54.93),\ ('Molybdenum', 'Mo', 95.98),\ ('Nickel', 'Ni', 58.69),\ ('Nitrogen', 'N', 14.008),\ ('Oxygen', 'O', 16.00),\ ('Phosphorus', 'P', 30.98),\ ('Potassium', 'K', 39.096),\ ('Silicon', 'Si', 28.06),\ ('Silver', 'Ag', 107.88),\ ('Sodium', 'Na', 22.997),\ ('Sulphur', 'S', 36.006),\ ('Tin', 'Sn', 118.70),\ ('Titanium', 'Ti', 47.90),\ ('Vanadium', 'V', 50.95),\ ('Zinc', 'Zn', 65.38),\ ('Zirconium', 'Zr', 91.22) ] mpSymElem = {} for name, symbol, atwt in element_data: elem = Element(symbol, name, atwt) mpSymElem[symbol] = elem # print mpSymElem['Al'].name class StringTokens: "Tokenizer" def __init__(self, s): self.s = s self.iCh = 0 def is_empty(self): return self.iCh >= len(self.s) def peek(self): ch = '\a' # something safe to dereference but not valid if not(self.is_empty()): ch = self.s[self.iCh] #print 'peek =', ch return ch def pop(self): ch = self.peek() if not(self.is_empty()): self.iCh += 1 #print 'pop =', ch return ch class Molecule: "A single oxide, Eg. 'Fe2O3'" mpNameMol = {} nSort = 0 def __init__(self, name, molWt, nSort): self.name = name self.molWt = molWt self.nSort = nSort @classmethod def ensure(cls, name): if name in Molecule.mpNameMol: return Molecule.mpNameMol[name] # mpElemC = mols of elem / mol of material # mpElemC / molWt = mols of elem / gram material mpElemC = {} global mpSymElem toks = StringTokens(name) while not(toks.is_empty()): ch = toks.pop() if ch.isupper(): sym = ch if toks.peek().islower(): sym += toks.pop() elem = mpSymElem[sym] c = 1 if toks.peek().isdigit(): c = int(toks.pop()) # print mul * c, " ", elem.name mpElemC[elem] = mpElemC.get(elem, 0) + c else: raise Exception('unrecognized character in formula') # Calculate molecular weight as sum of atomic weights molWt = 0 for elem, c in mpElemC.items(): molWt += c * elem.atWt mol = cls(name, molWt, Molecule.nSort) Molecule.nSort += 1 Molecule.mpNameMol[name] = mol return mol ## Python 2? ## def __cmp__(self, other): ## return self.nSort - other.nSort def __lt__(self, other): return self.nSort < other.nSort def __hash__(self): return hash(self.nSort) for name in ['SiO2', 'Al2O3', 'Na2O', 'K2O', 'MgO', 'CaO', 'TiO2', 'Fe2O3']: Molecule.ensure(name) class Formula: "A mixture of oxides, Eg. 'Al2O3 2SiO2'" def __init__(self, stForm): self.name = stForm # mpMolC = mols of oxide / mol of material # mpMolC / molWt = mols of oxide / gram material self.mpMolC = {} global mpSymElem toks = StringTokens(stForm) mul = 1 while not(toks.is_empty()): ch = toks.pop() if ch.isdigit(): mul = float(ch) while toks.peek().isdigit(): mul = 10 * mul + float(toks.pop()) if toks.peek() == '.': toks.pop() digit_value = 0.1 while toks.peek().isdigit(): mul += float(toks.pop()) * digit_value digit_value /= 10 elif ch == ' ' or ch == '.': mul = 1 elif ch.isupper(): sym = ch while toks.peek().isalnum(): sym += toks.pop() mol = Molecule.ensure(sym) # print mul " ", mol.name self.mpMolC[mol] = self.mpMolC.get(mol, 0) + mul else: raise Exception('unrecognized character in formula') # Calculate molecular weight as sum of atomic weights molWt = 0 for mol, c in self.mpMolC.items(): molWt += c * mol.molWt self.molWt = molWt class Material: "A raw material for a glaze" def __init__(self, names, stRaw, stFired): if type(names) == str: self.names = [names] else: self.names = names self.fAdd = (self.names[0][0] == '+') # strip +'s for i,name in enumerate(self.names): if name[0] == '+': self.names[i] = name[1:] self.name = self.names[0] self.mpMolFrac = {} if not stFired: return formRaw = Formula(stRaw) formFired = Formula(stFired) for mol, c in formFired.mpMolC.items(): # How many mols of this oxide per gram of material self.mpMolFrac[mol] = float(c) * mol.molWt / formRaw.molWt self.calcLoi() @classmethod def fromPercents(cls, names, percents): "Initialize Material from an array of formula/percentage pairs" # BB can I do this constructor via optional param and avoid calling regular init? material = cls(names, '', '') for sForm, percent in percents: if sForm == "LOI": continue form = Formula(sForm) frac = float(percent) / 100.0 for mol, c in form.mpMolC.items(): assert(c == 1) # How many mols of this oxide per gram of material material.mpMolFrac[mol] = frac # handle dups? material.calcLoi() return material def calcLoi(self): fracFired = 0.0 for frac in self.mpMolFrac.values(): fracFired += frac self.loi = 1.0 - fracFired self.mpMolFracFired = {} for mol,frac in self.mpMolFrac.items(): self.mpMolFracFired[mol] = frac / fracFired #print name, self.mpMolFrac, "loi =", self.loi material_data = [ ('Whiting', "CaCO3", "CaO"), # ('Kaolin', 'Al2O3 2SiO2 2H2O', 'Al2O3 2SiO2'), ('Talc', '3MgO 4SiO2 H2O', '3MgO 4SiO2'), (['Silica', "Flint"], 'SiO2', 'SiO2'), ('Zinc Oxide', 'ZnO', 'ZnO'), ('+RIO', 'Fe2O3', 'Fe2O3'), ('+Copper Carbonate', 'CuCO3', 'CuO'), ('+Titanium Dioxide', 'TiO2', 'TiO2'), (['CuO', 'Black Copper Oxide'], 'CuO', 'CuO'), ] Materials = {} def addMat(mat): for name in mat.names: Materials[name] = mat Materials["+" + name]= mat for names, stRaw, stFired in material_data: addMat(Material(names, stRaw, stFired)) #print "mol wt of", material.name, "is", material.formRaw.molWt addMat(Material.fromPercents('Barnard Clay',\ [('SiO2', 46.99),\ ('Al2O3', 7.60),\ ('MgO', 0.70), ('CaO', 0.60), ('K2O', 1.10), ('Na2O', 0.6), ('Fe2O3', 33.9), ('TiO2', 0.2)])) addMat(Material.fromPercents(['Custer Feldspar', "Custer", "Potash Feldspar"],\ [('SiO2', 68.5),\ ('Al2O3', 17.0),\ ('CaO', 0.30), ('K2O', 10.0), ('Na2O', 3.00), ('Fe2O3', 0.1)])) addMat(Material.fromPercents(['EPK', "EP Kaolin", "Kaolin"],\ [('SiO2', 45.73),\ ('Al2O3', 37.36),\ ('MgO', 0.10), ('CaO', 0.18), ('K2O', 0.35), ('Na2O', 0.07), ('P2O5', 0.26), ('Fe2O3', 0.76), ('TiO2', 0.38)])) addMat(Material.fromPercents(['Cornwall Stone', 'Cornish Stone'],\ [('SiO2', 73.78), ('Al2O3', 16.33), ('MgO', 0.14), ('CaO', 1.81), ('K2O', 4.30), ('Na2O', 3.30), ('Fe2O3', 0.19), ('TiO2', 0.15)])) addMat(Material.fromPercents('Dolomite',\ [('CaO', 30.48), ('MgO', 21.91)])) addMat(Material.fromPercents(['+Rutile'],\ [('Fe2O3', 9.90), ('TiO2', 90.0)])) addMat(Material.fromPercents('Nepheline Syenite',\ [('SiO2', 60.70),\ ('Al2O3', 23.30),\ ('MgO', 0.10), ('CaO', 0.70), ('K2O', 4.60), ('Na2O', 9.80), ('Fe2O3', 0.10)])) addMat(Material.fromPercents('+Bentonite',\ [('SiO2', 59.33),\ ('Al2O3', 20.12),\ ('MgO', 2.01), ('CaO', 1.01), ('K2O', 1.01), ('Na2O', 3.02), ('Fe2O3', 3.51)])) addMat(Material.fromPercents("Gerstley Borate",\ [('SiO2', 14.80),\ ('Al2O3', 1.00),\ ('B2O3', 26.80), ('MgO', 3.50), ('CaO', 19.40), ('K2O', 0.40), ('Na2O', 4.00), ('P2O5', 0.10), ('Fe2O3', 0.40), ('TiO2', 0.10)])) addMat(Material.fromPercents(["Kona F-4", "Kona", "Soda Spar"],\ [('SiO2', 66.74),\ ('Al2O3', 19.58),\ ('MgO', 0.05), ('CaO', 1.70), ('K2O', 4.80), ('Na2O', 6.89), ('Fe2O3', 0.04)])) addMat(Material.fromPercents(["OM-4 Ball Clay", "OM4", "Ball Clay", "OM-4"],\ [('CaO', 0.20),\ ('K2O', 1.10),\ ('MgO', 0.50),\ ('Na2O', 0.20),\ ('TiO2', 2.00),\ ('Al2O3', 26.30),\ ('SiO2', 59.70),\ ('Fe2O3', 1.30)])) addMat(Material.fromPercents("Petalite",\ [('Li2O', 4.87),\ ('Al2O3', 16.65),\ ('SiO2', 78.49)])) addMat(Material.fromPercents(["Zircopax", "Zirconium Silicate"], [('ZrO2', 67.21), ('SiO2', 32.79)])) addMat(Material.fromPercents(["Wood Ash", "Ash"], [('CaO', 37), ('MgO', 11), ('K2O', 16), ('Na2O', 1), ('P2O5', 9), ('SiO2', 7), ('Fe2O3', 1), ('MnO', 2), ('LOI', 16)])) addMat(Material.fromPercents(["Yellow Ochre", "Ochre"], [("CaO", 0.23), ("MgO", 0.06), ("Al2O3", 19.92), ("SiO2", 57.78), ("Fe2O3", 22.01)])) #print Molecule.mpNameMolWt ##for mat in Materials: ## print mat, Materials[mat].mpMolFrac def mulOxide(mpMolWt, sMol, gMul): mol = Molecule.ensure(sMol) if mol in mpMolWt: mpMolWt[mol] *= gMul else: raise("mulOxide on missing oxide") def replaceOxide(mpMolWt, sMolOld, frac, sMolNew): molOld = Molecule.ensure(sMolOld) molNew = Molecule.ensure(sMolNew) if molOld in mpMolWt: wtOld = mpMolWt[molOld] if frac < 1.0: mpMolWt[molOld] = wtOld * (1 - frac) else: del mpMolWt[molOld] nOld = wtOld / molOld.molWt nNew = nOld * frac wtNew = nNew * molNew.molWt mpMolWt[molNew] = mpMolWt.get(molNew, 0) + wtNew class Glaze: def __init__(self, ingreds, name = None): self.name = name self.mats = [] # ingredients in recipe order self.mpMatWt = {} # how much of each raw ingredient in 100g raw glaze self.mpMatFAdd = {} self.wtTotal = 0.0 # total weight of 100g batch, including additives # BB should this just be a Formula? Rationalize percent vs. frac self.mpMolWt = {} # grams fired oxide/100g raw glaze self.mpMolWtFired = {} # grams fired oxide/100g fired glaze if not ingreds: return sum = 0.0 sumAdditives = 0.0 for sMat, wt in ingreds: fAdd = False if sMat[0] == "+": fAdd = True sMat = sMat[1:] else: sum += wt sumAdditives += wt self.wtTotal += wt mat = Materials[sMat] self.mats.append(mat) self.mpMatWt[mat] = wt self.mpMatFAdd[mat] = fAdd # normalize to 100 if sum == 0.0: sum = sumAdditives for mat in self.mpMatWt: self.mpMatWt[mat] *= 100.0 / sum self.wtTotal *= 100.0 / sum for mat,wt in self.mpMatWt.items(): for mol, frac in mat.mpMolFrac.items(): self.mpMolWt[mol] = self.mpMolWt.get(mol, 0) + frac * wt self.calcLoi() def calcLoi(self): wtFired = 0.0 for wt in self.mpMolWt.values(): wtFired += wt self.loi = self.wtTotal - wtFired for mol,wt in self.mpMolWt.items(): self.mpMolWtFired[mol] = (wt / wtFired) * 100.0 ## def copy(self): ## glaze = Glaze([]) ## glaze.mats = self.mats[:] ## glaze.mpMatWt = self.mpMatWt.copy() ## glaze.wtTotal = self.wtTotal ## glaze.mpMolWt = self.mpMolWt.copy() ## glaze.loi = self.loi ## glaze.mpMolWtFired = self.mpMolWtFired.copy() ## return glaze ## def oxides(self): "Returns dict of oxide=>wt" # BB better name for this? return self.mpMolWt.copy() def materials(self): mats = [] for mat in self.mats: sMat = mat.name if self.mpMatFAdd[mat]: sMat = "+" + sMat mats.append(sMat) return mats def ingreds(self): ingreds = [] for mat in self.mats: name = mat.name if self.mpMatFAdd[mat]: name = "+" + name ingreds.append((name, self.mpMatWt[mat])) return ingreds def grams(self, mol): return self.mpMolWt[mol] def moles(self, mol): return self.grams(mol) / mol.molWt @classmethod def fromBlend(cls, glazeA, fracA, glazeB, fracB, name): mpNameWt = {} for (sMat,wt) in glazeA.ingreds(): mpNameWt[sMat] = wt * fracA for (sMat,wt) in glazeB.ingreds(): wt *= fracB if sMat in mpNameWt: wt += mpNameWt[sMat] mpNameWt[sMat] = wt ingreds=[] for (sMat,wt) in sorted(mpNameWt.items(), key=lambda item : item[1], reverse=True): ingreds.append((sMat,wt)) return Glaze(ingreds, name) @classmethod def fromGlazeChemFile(cls, filename): f = open(filename, "r") ingreds = [] name = None for line in f.read().split('\n'): if len(line) == 0: continue match = re.match(r""" (?P<field>[a-z_ ]+[a-z_])\s+=\s+ (?P<val>.*)""", line, re.VERBOSE) if not match: print("can't parse", line) exit sField = match.group("field") sVal = match.group("val") if sField == "name": name = sVal elif sField == "component": sMat = sVal elif sField == "amount": ingreds.append((sMat, float(sVal))) elif sField == "addition": sMat = sVal elif sField == "addamount": ingreds.append(("+" + sMat, float(sVal))) return Glaze(ingreds, name) @classmethod def fromFile(cls, filename): if filename[-4:] == ".txt": return cls.fromGlazeChemFile(filename) else: print("unknown file type", filename[-4:]) exit @classmethod def fromFormula(cls, oxidesTarget, materials=None, limit=0.1, name=None): "Regenerate recipe from fired formula" mpMatFAdd = {} if materials is None: # by default, use full set in Materials # BB this duplicates things like CuO and CuCO3 setMat = set() for s in Materials.values(): s.add(s) materials = [mat.name for mat in setMat] oxides = {oxide:wt for oxide,wt in oxidesTarget.items() if wt>=limit} # Include oxides from unused materials--must penalize extra oxides! for sMat in materials: fAdd = (sMat[0] == '+') if fAdd: sMat = sMat[1:] mat = Materials[sMat] mpMatFAdd[mat] = fAdd for mol in mat.mpMolFrac.keys(): if mol not in oxides: oxides[mol] = 0.0 # BB add extra row for combined fluxes (by molarity), scaled high, # to ensure total flux equivalency? # BB score similarity by molarity instead of weight while True: a = np.zeros((len(oxides),len(materials))) b = np.zeros(len(oxides)) for iOx,mol in enumerate(oxides): for iMat,sMat in enumerate(materials): mat = Materials[sMat] a[iOx,iMat] = mat.mpMolFrac.get(mol, 0) b[iOx] = oxides[mol] wts = np.linalg.lstsq(a,b,rcond=None)[0] if min(wts) > 0.0: break prunedMaterials = [] for iMat,sMat in enumerate(materials): if wts[iMat] > 0.0: prunedMaterials.append(sMat) materials = prunedMaterials ingreds = [] for iMat,sMat in enumerate(materials): mat = Materials[sMat] sMat = mat.name if mpMatFAdd[mat]: sMat = "+" + sMat ingreds.append((sMat, wts[iMat])) ingreds.sort(key=lambda ingred : ingred[1], reverse=True) return cls(ingreds, name) def substitute(self, sMatOrig, *new): # BB always add +additives to end of list materials = self.materials() aMatNew = [] for sMat in new: mat = Materials[sMat] aMatNew.append(mat.name) matOrig = Materials[sMatOrig].name i = materials.index(matOrig) materials = materials[0:i] + aMatNew + materials[i+1:] oxides = self.oxides() return Glaze.fromFormula(materials, oxides) ## # BB How to do this? Forward optional arg list? ## def sub(self, orig, *new): ## return self.substitute(orig, new) def print(self, scale=1.0): print(self.name) for (sMat, wt) in self.ingreds(): line = "{:<20}{:>7.1f}".format(sMat, wt*scale) print(line) line = "{:<20}{:>7.1f}".format("Total", self.wtTotal * scale) print(line) def printAnalysis(self): print(self.name) mols = [] for mol in self.mpMolWt.keys(): mols.append(mol) mols.sort() print("Percentage Analysis") line = " "*27 for mol in mols: line += " {:>7}".format(mol.name) print(line + "{:>7}".format("LOI")) for mat in self.mats: wt = self.mpMatWt[mat] name = mat.name if self.mpMatFAdd[mat]: name = "+" + name line = "{:<20}{:>7.1f}".format(name, wt) for mol in mols: if mol in mat.mpMolFrac: line += " {:>7.2f}".format(mat.mpMolFrac[mol] * wt) else: line += " {:>7}".format("") print(line + "{:7.2f}".format(mat.loi * wt)) line = "{:<20}{:>7.1f}".format("Total", self.wtTotal) for mol in mols: line += " {:>7.2f}".format(self.mpMolWt[mol]) print(line + "{:7.2f}".format(self.loi)) line = "{:<20}{:>7}".format("Fired %", "") for mol in mols: line += " {:>7.2f}".format(self.mpMolWtFired[mol]) print(line) print() self.printSeger() def printSeger(self): # classify ingredients according to type fluxes = [] glasses = [] stabilizers = [] for mol in self.mpMolWt: if mol.name == "SiO2" or mol.name == "TiO2": glasses.append(mol) elif mol.name == "Al2O3" or mol.name == "B2O3": stabilizers.append(mol) elif (mol.name == "PbO" or mol.name == "Na2O" or mol.name == "K2O" or mol.name == "LiO" or mol.name == "SrO" or mol.name == "BaO" or mol.name == "ZnO" or mol.name == "CaO" or mol.name == "MgO"): fluxes.append(mol) else: None # colorants not included in Seger formula sumFlux = 0.0 for mol in fluxes: sumFlux += self.moles(mol) sumGlasses = 0.0 for mol in glasses: sumGlasses += self.moles(mol) sumStab = 0.0 for mol in stabilizers: sumStab += self.moles(mol) mpMolC = {} for mol,wt in self.mpMolWt.items(): mpMolC[mol] = wt / (mol.molWt * sumFlux) print("{:8}{:>6}{:8}{:>6}{:8}{:>6}".format("", "RO", "", "R2O3", "", "RO2")) for i in range(max(len(fluxes), len(glasses), len(stabilizers))): line = "" if i < len(fluxes): line += "{:>8.2f}{:>6}".format(mpMolC[fluxes[i]], fluxes[i].name) else: line += "{:>8}{:>6}".format("", "") if i < len(stabilizers): line += "{:>8.2f}{:>6}".format(mpMolC[stabilizers[i]], stabilizers[i].name) else: line += "{:>8}{:>6}".format("", "") if i < len(glasses): line += "{:>8.2f}{:>6}".format(mpMolC[glasses[i]], glasses[i].name) else: line += "{:>8}{:>6}".format("", "") print(line) print() # R2O : RO 0.14 : 0.86 # Silica:Alumina ratio predicts glossiness (higher is glossier) print("SiO2 : Al2O3 {:8.2f}".format(sumGlasses / sumStab)) print()
![screenshot](design/screenshot.png) Fancy RWKV client. [Preview](https://rwkv-web-01.surge.sh/) (may be out-of-date. Install this locally for best experience) This application requires [rwkv-flask](https://github.com/iacore/rwkv-flask) running as the server. Go to that repo for installation guide. ## Installation ``` pnpm i pnpm dev ``` ## Tips - Infer request is cached. - Refresh when the server is loaded with a different model. - The application is slightly janky. Refresh or Press "Reset" might solve some problems. ## Notes RWKV is easy to model as pure functions. Therefore, it's easy reconstruct the state from prompt. It's also possible to cache infer results in a radix tree/cactus stack. The tokens used so far is much smaller (in bytes) than model hidden state. For explanation of RWKV itself, see [How the RWKV language model works](https://johanwind.github.io/2023/03/23/rwkv_details.html) and [numpy implementation](https://github.com/iacore/rwkv-np) (used in server of this project). High level representation of RWKV API is presented below. ```lean -- pseudo-code for RWKV inference structure Shape where -- model shape n_vocab: Nat n_embed: Nat n_layer: Nat def Token (S: Shape) := Fin S.n_vocab -- np.zeros def zeros {S: Shape} : HiddenState S := ... def infer {S: Shape} : ModelWeights S -> HiddenState S -> Token S -> HiddenState S := ... def infer_batch : ModelWeights S -> HiddenState S -> List (Token S) -> HiddenState S | _ [] s => s | w (x::xs) s => infer_batch w (infer w s x) xs def infer_from_zero : ModelWeights S -> List Token -> HiddenState S | w tokens => infer_batch w zeros tokens ``` ## TODO - add loading indicator. when waiting for server response (inferFromZero) should be at rightmost of top/status bar - add saving animation ("stop inference to save") - add "retry request" button for all windows - show a list of cached prompts - cache invalidation good to have - use consistent wording - scroll wheel zoom - scroll wheel scroll canvas - dynamic canvas background - faster sampler - better touch support - improve code - Subclass of ExNode depend on state_nodes not changing identity (Javascript object are kept by reference). Change that.
/** * 加载远程css * 可根据 :root 变量判断 防止重复添加 * @param {string|string[]} url * @param {() => boolean} [checkFunc] * @param {string} prop */ export function loadRemoteCss(url: string | string[], checkFunc: Function, prop: string) { return new Promise(async (resolve, reject) => { if (typeof url === 'string') { fn(url).then(() => { resolve(true) }).catch(() => { reject('样式文件加载失败!,地址链接:' + url) }) } else { for (const item of url) { if (checkFunc && checkFunc()) { break; } await fn(item) } if (checkFunc && checkFunc()) { resolve(true) } else { reject('样式文件加载失败!,地址链接:' + url.join(',')) } } }) function fn(path: string) { return new Promise((resolve, reject) => { let link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.href = path; // @ts-ignore link.dataset[prop] = 1 document.head.appendChild(link); link.onload = function () { resolve(true) } link.onerror = function (e) { reject(e) } }) } } /** * 动态加载脚本 * @param url 脚本地址 * @param check 检验是否引入 * @param prop window属性 */ export function loadScript(url: string, check = false, prop: string) { return new Promise((resolve, reject) => { // @ts-ignore let document1 = window?.rawWindow?.document || window?.document try { // @ts-ignore if (check) resolve(true) let script = document1.createElement("script"); script.type = "text/javascript"; // @ts-ignore if (script.readyState) { // @ts-ignore script.onreadystatechange = function () { // @ts-ignore if (script.readyState == "loaded" || script.readyState == "complete") { // @ts-ignore script.onreadystatechange = null; resolve(true) } }; } else { script.onload = function () { // @ts-ignore if (prop && !window[prop] && window.rawWindow && window.rawWindow[prop]) { // @ts-ignore window[prop] = window.rawWindow[prop] } resolve(true) }; script.onerror = function (r: any) { reject(r) } } script.src = url; document1.head.appendChild(script); } catch (e) { reject(false) } }) } /** * * @param urls 数组 * @param check 检验是否引入 * @param prop window属性 */ export function loadScriptByUrls(urls: string[], prop: string, check: Function) { return new Promise((resolve, reject) => { fn() function fn(urlIndex = 0) { let url = urls[urlIndex] // @ts-ignore let bool1 = !!(window?.rawWindow?.[prop] || window?.[prop]) if (check) { bool1 = check() } loadScript(url, bool1, prop) .then(() => { // @ts-ignore let value = window.rawWindow?.[prop] || window?.[prop] resolve(value) }) .catch(() => { if (urlIndex + 1 > urls.length - 1) { reject(false) } else { fn(urlIndex + 1) } }) } }) } export function initDefaultProps<T extends object>(props: object, defaultProps: T): T { // @ts-ignore let obj: T = {...props} Object.keys(defaultProps).forEach(key => { // @ts-ignore if (props[key] === undefined && typeof defaultProps[key] !== "object") { // @ts-ignore obj[key] = defaultProps[key] //@ts-ignore } else if (Array.isArray(defaultProps[key]) && defaultProps[key].length > 0 && (!props[key] || props[key].length === 0)) { // @ts-ignore obj[key] = [...defaultProps[key]] // @ts-ignore } else if (Array.isArray(props[key])) { // @ts-ignore obj[key] = [...props[key]] // @ts-ignore } else if (typeof defaultProps[key] === "object" && defaultProps[key] !== null) { // @ts-ignore obj[key] = initDefaultProps(obj[key] || {}, defaultProps[key]) } }) return obj }
import Knex from 'knex' import { GraphDBModel } from '../core/models/graphModel' import { SchemaDBModel } from '../core/models/schemaModel' import { SchemaTagDBModel } from '../core/models/schemaTagModel' import { ServiceDBModel } from '../core/models/serviceModel' export async function up(knex: Knex): Promise<void> { return knex.schema .createTable(GraphDBModel.table, (table) => { table.increments(GraphDBModel.field('id')).primary().notNullable() table.string(GraphDBModel.field('name')).unique().notNullable() table.boolean(GraphDBModel.field('isActive')).notNullable().defaultTo(true) table .timestamp(GraphDBModel.field('createdAt'), { useTz: true }) .notNullable() .defaultTo(knex.fn.now()) table .timestamp(GraphDBModel.field('updatedAt'), { useTz: true }) .notNullable() .defaultTo(knex.fn.now()) table.index([GraphDBModel.field('isActive'), GraphDBModel.field('name')]) }) .createTable(ServiceDBModel.table, (table) => { table.increments(ServiceDBModel.field('id')).primary() table.string(ServiceDBModel.field('name')).notNullable() table.boolean(ServiceDBModel.field('isActive')).notNullable().defaultTo(true) table.string(ServiceDBModel.field('routingUrl')).notNullable() table .timestamp(ServiceDBModel.field('createdAt'), { useTz: true }) .notNullable() .defaultTo(knex.fn.now()) table .timestamp(ServiceDBModel.field('updatedAt'), { useTz: true }) .notNullable() .defaultTo(knex.fn.now()) table .integer(ServiceDBModel.field('graphId')) .unsigned() .references(GraphDBModel.field('id')) .inTable(GraphDBModel.table) .onDelete('CASCADE') .index() table.index([ServiceDBModel.field('isActive'), ServiceDBModel.field('name')]) table.unique([ServiceDBModel.field('graphId'), ServiceDBModel.field('name')]) table.unique([ServiceDBModel.field('graphId'), ServiceDBModel.field('routingUrl')]) }) .createTable(SchemaDBModel.table, (table) => { table.increments(SchemaDBModel.field('id')).primary() table.text(SchemaDBModel.field('typeDefs')) table.boolean(SchemaDBModel.field('isActive')).notNullable().defaultTo(true) table .timestamp(SchemaDBModel.field('createdAt'), { useTz: true }) .notNullable() .defaultTo(knex.fn.now()) table .timestamp(SchemaDBModel.field('updatedAt'), { useTz: true }) .notNullable() .defaultTo(knex.fn.now()) table .integer(SchemaDBModel.field('graphId')) .unsigned() .references(GraphDBModel.field('id')) .inTable(GraphDBModel.table) .index() table .integer(SchemaDBModel.field('serviceId')) .unsigned() .references(ServiceDBModel.field('id')) .inTable(ServiceDBModel.table) .index() table.index([SchemaDBModel.field('isActive')]) table.index([SchemaDBModel.field('typeDefs')]) }) .createTable(SchemaTagDBModel.table, (table) => { table.increments(SchemaTagDBModel.field('id')).primary() table.string(SchemaTagDBModel.field('version')) table.boolean(SchemaTagDBModel.field('isActive')).notNullable().defaultTo(true) table .timestamp(SchemaTagDBModel.field('createdAt'), { useTz: true }) .notNullable() .defaultTo(knex.fn.now()) table .integer(SchemaTagDBModel.field('schemaId')) .unsigned() .references(SchemaDBModel.field('id')) .inTable(SchemaDBModel.table) .index() table .integer(SchemaTagDBModel.field('serviceId')) .unsigned() .references(ServiceDBModel.field('id')) .inTable(ServiceDBModel.table) .index() table.index([SchemaTagDBModel.field('version')]) }) } export async function down(knex: Knex): Promise<void> { return knex.schema .raw(`DROP TABLE ${GraphDBModel.table} CASCADE`) .raw(`DROP TABLE ${SchemaDBModel.table} CASCADE`) .raw(`DROP TABLE ${SchemaTagDBModel.table} CASCADE`) .raw(`DROP TABLE ${ServiceDBModel.table} CASCADE`) }
import { FileOps } from './plugins/file-ops/file-ops'; import { ICallgraphEdge } from './interfaces/callgraph-edge.interface'; import { CallGraphTransformations } from './plugins/callgraph-transformations'; import { ASTTransformations } from './plugins/ast-transformations'; import { Node } from './models/node.model'; import { Store } from './plugins/store/store'; import { BabelGenerator } from './plugins/parsers-and-generators/babel-generator'; import * as babelTypes from '@babel/types'; import { ITransformationDetail } from './interfaces/transformation-detail.interface'; import { ExtractCallTrees } from './plugins/callgraph-transformations/extract-call-trees'; import { SuggestionUtils } from './utils/suggestion-utils'; import { Events } from './plugins/events/events'; export default class Asyncify { public static showTransformationsAndTransform = async (pathToCallgraphCSV: string): Promise<{[key: string]: Array<ITransformationDetail>}> => { const callgraph: Array<ICallgraphEdge> = await FileOps.readCSVFile(pathToCallgraphCSV, true); const callTree: Node = await CallGraphTransformations.transform(callgraph); Store.setData('callTree', callTree); const transformations: { statistics: any, suggestions: { [key: string]: Array<ITransformationDetail>} } = ASTTransformations.showTransformations(callTree); await SuggestionUtils.generateHtmlReport(transformations); await FileOps.writeFile('listOfTransformations.txt', JSON.stringify(transformations, null, 2)); await Asyncify.rebuildASTCache(pathToCallgraphCSV); const numberOfFuncsTransformed: number = ASTTransformations.transform(Store.getData('callTree')); await Asyncify.writeTransformedFiles(); console.log('Sync functions transformed: ', callTree.children.length); console.log('Related functions transformed: ', numberOfFuncsTransformed - callTree.children.length); return; } public static showTransformations = async (pathToCallgraphCSV: string): Promise<{[key: string]: Array<ITransformationDetail>}> => { const callgraph: Array<ICallgraphEdge> = await FileOps.readCSVFile(pathToCallgraphCSV, true); const callTree: Node = await CallGraphTransformations.transform(callgraph); Store.setData('callTree', callTree); const transformations: { statistics: any, suggestions: { [key: string]: Array<ITransformationDetail>} } = ASTTransformations.showTransformations(callTree); await SuggestionUtils.generateHtmlReport(transformations); await FileOps.writeFile('listOfTransformations.txt', JSON.stringify(transformations, null, 2)); return; } public static transform = async (pathToCallgraphCSV: string, nodesToTransform?: Array<string>): Promise<any> => { const start: number = new Date().getTime(); const callgraph: Array<ICallgraphEdge> = await FileOps.readCSVFile(pathToCallgraphCSV, true); const callTree: Node = await CallGraphTransformations.transform(callgraph); Store.setData('callTree', callTree); if(nodesToTransform) { callTree.childKeys .filter((key: string): boolean => !nodesToTransform.includes(key)) .forEach((key: string): void => { callTree.removeChild(parseInt(key, 10)); }); } const numberOfFuncsTransformed: number = ASTTransformations.transform(callTree); await Asyncify.writeTransformedFiles(); const end: number = new Date().getTime(); const timeTaken: number = end - start; const syncIdentified = Store.getData('syncIdentified'); const syncTransformed = callTree.children.length const relatedTransformed = numberOfFuncsTransformed - callTree.children.length console.log('Sync functions transformed: ', syncTransformed); console.log('Related functions transformed: ', relatedTransformed); return { syncIdentified, syncTransformed, relatedTransformed, timeTaken }; } public static resetData(): void { Store.reset(); ExtractCallTrees.resetData(); Events.reset(); } private static rebuildASTCache = async (pathToCallgraphCSV: string) => { Store.reset(); ExtractCallTrees.resetData(); const callgraph: Array<ICallgraphEdge> = await FileOps.readCSVFile(pathToCallgraphCSV, true); const callTree: Node = await CallGraphTransformations.transform(callgraph); Store.setData('callTree', callTree); } private static writeTransformedFiles = (): Promise<void> => { const promises: Array<Promise<any>> = []; Store.getFilesToWrite().forEach((fileName: string): void => { promises.push(Asyncify.generateCodeAndWrite(fileName)); }); return Promise.all(promises) .then((): void => { return; }); } private static generateCodeAndWrite = (fileName: string): Promise<any> => { const modifiedAST: babelTypes.File = Store.getAST(fileName); const contents: string = BabelGenerator.generateCode(modifiedAST, {}); return FileOps.writeFile(fileName, contents); } } module.exports = Asyncify;
import React from "react" import { useEffect } from "react" import { useState } from "react" function App() { const [todos, setTodos] = useState([]) useEffect(()=>{ setInterval(function() { fetch("https://sum-server.100xdevs.com/todos").then( // it's the backend server to get the todos list async function(res) { const json = await res.json() setTodos(json.todos); } )} , 3000) // get's new list of todos after every 3 seconds }, []) return ( <> {todos.map((todo)=>{ return <ToDo title={todo.title} description={todo.description} /> })} </> ) } function ToDo({title, description}) { return <div> <h1>{title}</h1> <h2>{description}</h2> </div> } export default App
/* * This file is part of the SYMPLER package. * https://github.com/kauzlari/sympler * * Copyright 2002-2013, * David Kauzlaric <[email protected]>, * and others authors stated in the AUTHORS file in the top-level * source directory. * * SYMPLER is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SYMPLER 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 SYMPLER. If not, see <http://www.gnu.org/licenses/>. * * Please cite the research papers on SYMPLER in your own publications. * Check out the PUBLICATIONS file in the top-level source directory. * * You are very welcome to contribute extensions to the code. Please do * so by making a pull request on https://github.com/kauzlari/sympler * */ #ifndef __F_WALL_REPULSION_H #define __F_WALL_REPULSION_H #include "f_particle.h" #include "simulation.h" #include "manager_cell.h" using namespace std; //---- FWallRepulsion ---- /*! * Simple repulsive wall force which drops linearly from \a m_force at the wall * to zero at the cut-off distance. */ class FWallRepulsion : public FParticle { protected: /*! * The cut-off distance from the wall */ double m_cutoff; /*! * The inverse of the cut-off distance from the wall */ double m_rcinv; /*! * Direction in where to find the walls */ int m_wall_dir; /*! * Position of the wall to the left in the wall direction */ double m_left_wall; /*! * Position of the wall to thr right in the wall direction */ double m_right_wall; /*! * Magnitude of the force directly at the wall */ double m_force; void init(); public: /*! * Constructor * @param simulation Pointer to the simulation object */ FWallRepulsion(Simulation *simulation); /*! * Destructor */ virtual ~FWallRepulsion(); #ifdef _OPENMP virtual void setForceSlots(Integrator* intr, int thread_no) {} #endif virtual void computeForces(int force_index); virtual void computeForces(Particle* part, int force_index); #ifndef _OPENMP virtual void computeForces(Pairdist* pair, int force_index); #else virtual void computeForces(Pairdist* pair, int force_index, int thread_no); // virtual void mergeCopies(Particle* p, size_t thread_no, int force_index) {} #endif virtual void setup(); }; #endif
import 'dart:io'; import 'package:path_provider/path_provider.dart'; import 'package:sqflite/sqflite.dart'; import 'note.dart'; class DatabaseHelper1 { static DatabaseHelper1 _databasseHelper; static Database _database; String noteTable = 'note_table'; String colId = 'id'; String colTitle = 'title'; String colPrice = 'price'; String colTotal = 'total'; DatabaseHelper1._createInstance(); factory DatabaseHelper1() { if (_databasseHelper == null) { _databasseHelper = DatabaseHelper1._createInstance(); } return _databasseHelper; } Future<Database> get database async { if (_database == null) { _database = await initalizeDatabase(); } return _database; } Future<Database> initalizeDatabase() async { Directory directory = await getApplicationDocumentsDirectory(); String path = directory.path + 'notese.db'; var notesDatabase = await openDatabase(path, version: 1, onCreate: _createDb); return notesDatabase; } void _createDb(Database db, int newVersion) async { await db.execute( 'CREATE TABLE $noteTable($colId INTEGER PRIMARY KEY AUTOINCREMENT, $colTitle TEXT, $colPrice TEXT, $colTotal TEXT)'); } Future<List<Map<String, dynamic>>> getNoteMapList() async { Database db = await this.database; // var result = await db.rawQuery('SELECT * FROM $noteTable order by $colPriority ASC'); var result = await db.query(noteTable, orderBy: '$colId ASC'); return result; } Future<int> insertNote(Note2 note) async { Database db = await this.database; var result = await db.insert(noteTable, note.toMap()); return result; } Future<int> updateNote(Note2 note) async { var db = await this.database; var result = await db.update(noteTable, note.toMap(), where: '$colId = ?', whereArgs: [note.id]); return result; } Future<int> deleteNote(int id) async { var db = await this.database; int result = await db.rawDelete('DELETE FROM $noteTable WHERE $colId = $id'); return result; } Future<int> deleteAll() async { var db = await this.database; int result = await db.rawDelete('DELETE FROM $noteTable'); return result; } Future<int> getCount() async { Database db = await this.database; List<Map<String, dynamic>> x = await db.rawQuery('SELECT COUNT (*) from $noteTable'); int result = Sqflite.firstIntValue(x); return result; } Future<List<Note2>> getNoteList() async { var noteMapList = await getNoteMapList(); int count = noteMapList.length; List<Note2> noteList = List<Note2>(); for (int i = 0; i < count; i++) { noteList.add(Note2.fromMapObject(noteMapList[i])); } return noteList; } Future<int> updateTotal(String id, String total) async { var db = await this.database; int result = await db.rawUpdate( 'UPDATE $noteTable SET $colTotal = $total WHERE $colId = $id'); print("update Total Successfully"); return result; } Future getAllTotal() async { var db = await this.database; var result = await db.rawQuery("SELECT SUM($colTotal) as AllTotal FROM $noteTable"); return result; } }
<?php namespace App\Http\Controllers; use App\Models\project; use Illuminate\Http\Request; class ProjectController extends Controller { /** * Display a listing of the resource. */ protected $project; public function __construct() { $this->project = new project(); } public function index() { $response['projects'] = $this->project->all(); return view('welcome')->with($response); } public function showProjects() { $projects = $this->project->all(); return view('/dashboard')->with('projects', $projects); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $request->validate([ 'name' => ['required', 'max:26'], // Maximum length of 26 characters 'description' => ['required', 'max:255'], // Maximum length of 255 characters 'project_url' => ['required', 'url'], // Must be a valid URL 'image_url' => ['required'] // No validation on image_url provided, you can add it as needed ]); $this->project->create($request->all()); return redirect()->back(); } /** * Display the specified resource. */ public function show(string $id) { return $this->project->find($id); } public function edit(Request $request, string $id) { $project = $this->project->find($id); if ($project) { $project->update($request->all()); return redirect()->back()->with('success', 'Project updated successfully!'); } else { // Handle the case where the project is not found return redirect()->back()->with('error', 'Project not found!'); } } /** * Remove the specified resource from storage. */ public function destroy(string $id) { $this->project->find($id)->delete(); return redirect()->back(); } }
import React from 'react' import { DndContext, closestCenter } from "@dnd-kit/core"; import { SortableContext, rectSortingStrategy, } from "@dnd-kit/sortable"; import { useState, useEffect } from "react"; import { SortableItem } from "../component/SortableItem"; import Header from "../component/Header"; import LoadingSkeleton from "../component/LoadingSkeleton"; import { toast } from "react-toastify"; import Navbar from '../component/NavBar'; const Home = () => { const [items, setItems] = useState([]); const [isLoading, setIsLoading] = useState(true); const [searchTerm, setSearchTerm] = useState(""); useEffect(() => { setIsLoading(true); try{ if(searchTerm !== "") { setItems(items.filter((item) => item.tags.toLowerCase().includes(searchTerm.toLowerCase()) )) setIsLoading(false) } else { fetch( "https://pixabay.com/api/?key=39531365-0f0f6711437439bd9bc7abac1&q=art+gallery&image_type=photo&pretty=true&per_page=30" ) .then((res) => res.json()) .then((data) => { setItems(data.hits); setIsLoading(false); }); }} catch(err) { toast.success("Items can't be fetched") } }, [searchTerm]); function handleDragEnd(event) { console.log("Drag end called"); const { active, over } = event; if (active && over) { if (active.id !== over.id) { setItems((items) => { const draggedItem = items.find((item) => item.id === active.id); const overItem = items.find((item) => item.id === over.id); const draggedIndex = items.indexOf(draggedItem); const overIndex = items.indexOf(overItem); const updatedItems = [...items]; updatedItems.splice(draggedIndex, 1); updatedItems.splice(overIndex, 0, draggedItem); return updatedItems; }); } } } return ( <div className="w-full"> <Navbar /> <Header text={searchTerm} textState={setSearchTerm} /> {!isLoading ? ( <DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd} > <div className="sm:p-3 my-4 w-[95%] mx-auto flex justify-center overflow-hidden"> <SortableContext items={items} strategy={rectSortingStrategy}> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-y-6 w-full mx-auto items-center"> {items.map((item, index) => ( <SortableItem key={item.id} id={item} /> ))} </div> </SortableContext> </div> </DndContext> ) : ( <div className="flex flex-wrap gap-5 my-8"> <LoadingSkeleton /> </div> )} </div> ) } export default Home
import { Button, CircularProgress, Container, Grid, Typography } from "@material-ui/core"; import axios from "axios"; import React, { lazy, Suspense, useEffect, useState } from "react"; import { useSelector } from "react-redux"; import { useParams } from "react-router"; import { toast } from "react-toastify"; import authorImg from "../../assets/author.png"; import heroBanner from "../../assets/banner/hero-banner.jpg"; import behanceIcon from "../../assets/icons/behance.svg"; import dribbbleIcon from "../../assets/icons/dribble.svg"; import facebookIcon from "../../assets/icons/facebook.svg"; import instagramIcon from "../../assets/icons/instagram.svg"; import linkedInIcon from "../../assets/icons/linkdin.svg"; import pinterestIcon from "../../assets/icons/pintarest.svg"; import shutterstockIcon from "../../assets/icons/shutterstock.svg"; import twitterIcon from "../../assets/icons/twitter.svg"; import Spacing from "../../components/Spacing"; import Header from "../../components/ui/Header"; import SocialShare from "../../components/ui/SocialShare"; import { getBaseURL, imageObjSchema } from "../../helpers"; import Layout from "../../Layout"; import SignUpModal from "../Authentication/SignUpModal"; import Loader from "./../../components/ui/Loader/index"; import useStyles from "./AuthorProfile.styles"; const AuthorItems = lazy(() => import("../../components/ui/AuthorItems")); const CallToAction = lazy(() => import("../../components/ui/CallToAction")); const Footer = lazy(() => import("../../components/ui/Footer")); const AuthorProfile = () => { const classes = useStyles(); const { username } = useParams(); const user = useSelector((state) => state.user); const [openAuthModal, setOpenAuthModal] = useState(false); const [imageSummery, setImageSummery] = useState([]); const [isFollowing, setFollowing] = useState(false); const [profileInfo, setProfileInfo] = useState({}); const [isLoading, setLoading] = useState(true); const [role, setRole] = useState(""); const [thumbnail, setThumbnail] = useState(""); useEffect(() => { const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios .get(`${process.env.REACT_APP_API_URL}/contributor/${username}/statistics`, { cancelToken: source.token }) .then(({ data }) => { if (data?.status) { setProfileInfo(data?.profile); setThumbnail(getBaseURL().bucket_base_url + "/" + data?.profile?.avatar); setImageSummery(data?.images_summary); setLoading(false); if (user && user?.isLoggedIn && user?.role === "user") { axios .get(`${process.env.REACT_APP_API_URL}/contributor/follow_status/${data.profile.id}`, { headers: { Authorization: user?.token } }) .then((response) => { if (response.data.status) { setFollowing(true); setLoading(false); } else { setFollowing(false); setLoading(false); } }); } } }) .catch((error) => { console.log("statistics", error); setLoading(false); }); return () => source.cancel(); }, [username, user]); const handleJoinUsButton = () => { if (!user.token) { setOpenAuthModal(true); } }; const handleFollower = (e) => { const CancelToken = axios.CancelToken; const source = CancelToken.source(); if (!user?.isLoggedIn) { setRole(e.target.closest("button").value); setOpenAuthModal(true); } else if (user?.isLoggedIn && user?.role === "user") { axios .post( `${process.env.REACT_APP_API_URL}/contributor/followers/${profileInfo?.id}`, {}, { cancelToken: source.token, headers: { Authorization: user?.token } } ) .then((response) => { if (response?.status === 200) { setFollowing(!isFollowing); } }) .catch((error) => console.log("Followers error: ", error)); } else { if (user?.isLoggedIn && user?.role === "contributor") { toast.error("Please, login as a user", { autoClose: 2200 }); setOpenAuthModal(true); } else { toast.error("You can't follow yourself", { autoClose: 2000 }); } } return () => source.cancel(); }; const socialMedia = [ { socialUrl: profileInfo?.facebook, socialIcon: facebookIcon, }, { socialUrl: profileInfo?.behance, socialIcon: behanceIcon, }, { socialUrl: profileInfo?.dribbble, socialIcon: dribbbleIcon, }, { socialUrl: profileInfo?.instagram, socialIcon: instagramIcon, }, { socialUrl: profileInfo?.linkedin, socialIcon: linkedInIcon, }, { socialUrl: profileInfo?.pinterest, socialIcon: pinterestIcon, }, { socialUrl: profileInfo?.shutterstock, socialIcon: shutterstockIcon, }, { socialUrl: profileInfo?.twitter, socialIcon: twitterIcon, }, ]; useEffect(() => { const schemaObj = { name: document.title, contentUrl: document.location.href, acquireLicensePage: document.location.href, thumbnailUrl: `${process.env.REACT_APP_API_URL}/media_images/company/piktak_logo.jpg`, }; imageObjSchema(schemaObj); }, []); return ( <Layout title={`${profileInfo?.username}`} description={`Discover millions of free Vectors, Photos &amp; PSD files from ${profileInfo?.username} - Free Graphic Resources for personal and commercial use`} canonical={document.URL} ogUrl={document.URL} ogImage={thumbnail} > <Header /> <div className={classes.authorHero} style={{ backgroundImage: `url(${heroBanner})` }}> <Container> {isLoading ? ( <div style={{ display: "flex", justifyContent: "center", alignItems: "center", margin: "0 auto", height: 300, }} > <CircularProgress color="primary" /> </div> ) : ( <> {profileInfo ? ( <Grid container className={classes.profileWrapper}> <div className={classes.authorImg}> {profileInfo?.avatar ? ( <img src={getBaseURL().bucket_base_url + "/" + profileInfo?.avatar} alt={profileInfo?.username} width="90px" height="90px" /> ) : ( <img src={authorImg} alt={profileInfo?.username} width="90px" height="90px" /> )} </div> <div className={classes.authorInfo}> <Typography className={classes.authorName} variant="h3"> {profileInfo?.username} </Typography> <div className={classes.resourceDetails}> <Typography className={classes.infoItem} variant="body2"> Resources <span>{profileInfo?.total_images}</span> </Typography> <Typography className={classes.infoItem} variant="body2"> Followers <span>{profileInfo?.total_followers}</span> </Typography> <Typography className={classes.infoItem} variant="body2"> Downloads <span>{profileInfo?.total_downloads}</span> </Typography> {user?.id !== profileInfo?.id && ( <div> <Button className={classes.followBtn} onClick={handleFollower} value="user"> {!isFollowing ? <>Follow</> : <>Following</>} </Button> </div> )} </div> <div className={classes.authorSocials}> {socialMedia?.length > 0 && <Typography>Follow me: </Typography>} <SocialShare title="Follow this author:" socials={socialMedia} /> </div> </div> </Grid> ) : ( <div style={{ display: "flex", justifyContent: "center", alignItems: "center", margin: "0 auto", height: 300, }} > <CircularProgress color="primary" /> </div> )} </> )} </Container> </div> <Suspense fallback={<Loader />}> <AuthorItems userId={profileInfo.id} imageSummery={imageSummery} /> </Suspense> <Spacing space={{ height: "4rem" }} /> <Suspense fallback={<Loader />}> {!user?.isLoggedIn ? ( <CallToAction title="Join Piktask team" subtitle="Upload your first copyrighted design. Get $5 designer coupon packs" buttonText="Join Us" buttonClicked={() => handleJoinUsButton()} /> ) : ( <CallToAction title="Go Premium" subtitle="Upload your first copyrighted design. Get $5 designer coupon packs" buttonLink="/subscription" buttonText="See Plans" /> )} </Suspense> {/* Sign up modal section*/} <SignUpModal openAuthModal={openAuthModal} setOpenAuthModal={setOpenAuthModal} role={role} /> <Suspense fallback={<Loader />}> <Footer /> </Suspense> </Layout> ); }; export default AuthorProfile;
import React from 'react' import { Col } from 'reactstrap'; import { Link } from 'react-router-dom'; import { motion } from 'framer-motion'; import '../../styles/product-card.css' const ProductCard = ({i}) => { return ( <Col lg='3' md='4' className='mb-2'> <div className="product__item"> <div className="product__img"> <motion.img whileHover={{scale:0.9}} src={i.imgUrl} alt="product_image" /> </div> <div className="p-2 product__info"> <h3 className="product__name"><Link to={`/shop/${i.id}`}>{i.productName}</Link></h3> <span>{i.category}</span> </div> <div className="product__card-bottom d-flex align-items-center justify-content-between p-2 "> <span className="price">{`$${i.price}`}</span> <motion.span whileTap={{scale: 1.2}}> <i className="ri-add-line"></i> </motion.span> </div> </div> </Col> ) } export default ProductCard
/**************************************************************************** * Copyright (c) 2023, CEA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ #include <Bords.h> Implemente_instanciable(Bords, "Bords", LIST(Bord)); Sortie& Bords::printOn(Sortie& os) const { return LIST(Bord)::printOn(os); } Entree& Bords::readOn(Entree& is) { return LIST(Bord)::readOn(is); } /*! @brief Associe un domaine a tous les bords de la liste. * * @param (Domaine& un_domaine) le domaine a associer aux bords de la liste */ void Bords::associer_domaine(const Domaine& un_domaine) { for (auto &itr : *this) itr.associer_domaine(un_domaine); } /*! @brief Renvoie le nombre total de faces de tous les bords de la liste * * @return (int) le nombre total de faces de tous les bords de la liste */ int Bords::nb_faces() const { int nombre = 0; for (const auto &itr : *this) nombre += itr.nb_faces(); return nombre; } /*! @brief Renvoie le nombre total de faces du type specifie, pour tous les bords de la liste. * * @param (Type_Face type) le type des faces a comptabiliser * @return (int) le nombre total de faces du type specifie, pour tous les bords de la liste */ int Bords::nb_faces(Type_Face type) const { int nombre = 0; for (const auto &itr : *this) if (type == itr.faces().type_face()) nombre += itr.nb_faces(); return nombre; }
package com.hemanth.junit5testing; import com.hemanth.junit5testing.model.Book; import com.hemanth.junit5testing.service.BookService; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.assertTrue; public class AssertTrueDemo { @Test public void assertTrueWithNoMessage() { BookService bookService = new BookService(); Book headFirstJavaBook = new Book("1", "Head First Java ", "Wrox"); bookService.addBook(headFirstJavaBook); List<Book> listOfBooks = bookService.books(); assertTrue(listOfBooks.isEmpty()); } @Test public void assertTrueWIthMessage() { BookService bookService = new BookService(); Book headFirstJavaBook = new Book("1", "Head first Java", "wrox"); bookService.addBook(headFirstJavaBook); List<Book> listOfBooks = bookService.books(); assertTrue(listOfBooks.isEmpty(), "List of Books is not empty!"); } @Test public void assertTrueWIthMessageSupplier() { BookService bookService = new BookService(); Book headFirstJavaBook = new Book("1", "Head first Java", "wrox"); bookService.addBook(headFirstJavaBook); List<Book> listOfBooks = bookService.books(); // we are using lambda expression assertTrue(listOfBooks.isEmpty(), () -> "List of Books is not empty!"); } @Test public void assertTrueWithBooleanSupplierAndNoMessage() { BookService bookService = new BookService(); Book headFirstJavaBook = new Book("1", "Head First Java ", "Wrox"); bookService.addBook(headFirstJavaBook); List<Book> listOfBooks = bookService.books(); // using booleanSupplier functional interface assertTrue(() -> listOfBooks.isEmpty()); } @Test public void assertTrueWIthBooleanSupplierWithMessage() { BookService bookService = new BookService(); Book headFirstJavaBook = new Book("1", "Head first Java", "wrox"); bookService.addBook(headFirstJavaBook); List<Book> listOfBooks = bookService.books(); // with boolean supplier functional interface with string message assertTrue(() -> listOfBooks.isEmpty(), "List of Books is not empty!"); } @Test public void assertTrueWIthBooleanSupplierAndMessageSupplier() { BookService bookService = new BookService(); Book headFirstJavaBook = new Book("1", "Head first Java", "wrox"); bookService.addBook(headFirstJavaBook); List<Book> listOfBooks = bookService.books(); // we are using lambda expression, boolean supplier for first argument, second as supplier assertTrue(() -> listOfBooks.isEmpty(), () -> "List of Books is not empty!"); } }
//package com.fruntier.fruntier.running.repository; // //import com.fruntier.fruntier.running.domain.Coordinate; //import com.fruntier.fruntier.running.domain.Edge; //import com.fruntier.fruntier.running.domain.Vertex; //import org.assertj.core.api.Assertions; //import org.junit.jupiter.api.AfterEach; //import org.junit.jupiter.api.Test; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.SpringBootConfiguration; //import org.springframework.boot.autoconfigure.EnableAutoConfiguration; //import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; //import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; //import org.springframework.boot.test.context.SpringBootTest; // //import java.util.ArrayList; //import java.util.List; //import java.util.Optional; // //@SpringBootTest //@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) //public class EdgeMemoryRepositoryTest { // // EdgeRepository edgeRepository; // // @Autowired // public EdgeMemoryRepositoryTest(EdgeRepository edgeRepository) { // this.edgeRepository = edgeRepository; // } // // @Test // void save(){ // List<Edge> v1Edge = new ArrayList<>(); // List<Edge> v2Edge = new ArrayList<>(); // Coordinate c1 = new Coordinate(10.0,10.0); // Coordinate c2 = new Coordinate(20.0,20.0); // Vertex v1 = new Vertex(1L,c1,"대흥동",v1Edge); // Vertex v2 = new Vertex(2L,c2,"서강동",v2Edge); // // Edge edge1 = new Edge(1L,v1,v2,20.0,1,1,1,1.1,2.3); // Edge nullEdge = null; // // //test1 : save edge 1 // edgeRepository.save(edge1); // Optional<Edge> resultEdge = edgeRepository.findById(edge1.getId()); // if(resultEdge.isPresent()){ // Assertions.assertThat(resultEdge.get()).isEqualTo(edge1); // }else{ // Assertions.fail("Failed to save edge in repository"); // } // // //test2 : save nulledge // try{ // edgeRepository.save(nullEdge); // Assertions.fail("did not return exception as expected"); // }catch (IllegalArgumentException e){ // Assertions.assertThat(e.getClass()).isEqualTo(IllegalArgumentException.class); // } // // } // @Test // void findById(){ // List<Edge> v1Edge = new ArrayList<>(); // List<Edge> v2Edge = new ArrayList<>(); // Coordinate c1 = new Coordinate(10.0,10.0); // Coordinate c2 = new Coordinate(20.0,20.0); // Vertex v1 = new Vertex(1L,c1,"대흥동",v1Edge); // Vertex v2 = new Vertex(2L,c2,"서강동",v2Edge); // Edge edge1 = new Edge(1L,v1,v2,20.0,1,1,1,1.1,2.3); // Edge edge2 = new Edge(2L,v1,v2,20.0,1,1,1,1.1,2.3); // // edgeRepository.save(edge1); // edgeRepository.save(edge2); // // //test1 : find edge1 // Optional<Edge> resultEdge = edgeRepository.findById(1L); // if(resultEdge.isPresent()){ // Assertions.assertThat(edge1).isEqualTo(resultEdge.get()); // }else{ // Assertions.fail("Edge not found in repository"); // } // // //test2 : find null // try{ // Optional<Edge> noedge = edgeRepository.findById(null); // Assertions.fail("did not return exception as expected"); // }catch (IllegalArgumentException e){ // Assertions.assertThat(edge1).isEqualTo(resultEdge.get()); // } // // } // // @Test // void delete(){ // List<Edge> v1Edge = new ArrayList<>(); // List<Edge> v2Edge = new ArrayList<>(); // Coordinate c1 = new Coordinate(10.0,10.0); // Coordinate c2 = new Coordinate(20.0,20.0); // Vertex v1 = new Vertex(1L,c1,"대흥동",v1Edge); // Vertex v2 = new Vertex(2L,c2,"서강동",v2Edge); // // Edge edge1 = new Edge(1L,v1,v2,20.0,1,1,1,1.1,2.3); // Edge edge2 = new Edge(2L,v1,v2,20.0,1,1,1,1.1,2.3); // // edgeRepository.save(edge1); // edgeRepository.save(edge2); // // edgeRepository.delete(edge1.getId()); // if(edgeRepository.findById(edge1.getId()).isPresent()){ // Assertions.fail("deletion failed"); // } // // // } // //// @AfterEach //// void clear(){ //// edgeRepository.clear(); //// } //}
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { Student } from './student.model'; @Injectable({ providedIn: 'root' }) export class StudentService { private apiUrl = 'assets/students.json'; // Emplacement du fichier JSON constructor(private http: HttpClient) { } getStudents(): Observable<Student[]> { return this.http.get<Student[]>(this.apiUrl); } getStudent(id: number): Observable<Student> { return this.http.get<Student>(`${this.apiUrl}/${id}`); } createStudent(student: Student): Observable<Student> { return this.http.post<Student>(this.apiUrl, student); } updateStudent(student: Student): Observable<Student> { return this.http.put<Student>(`${this.apiUrl}/${student.id}`, student); } deleteStudent(id: number): Observable<void> { return this.http.delete<void>(`${this.apiUrl}/${id}`); } }
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8" /> <title>Task 5</title> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous" ></script> </head> <body> <script type="application/javascript"> function createFamilyTree() { let table = $("<table>"); let thead = $("<thead>"); let head = $("<tr>"); let tbody = $("<tbody>"); head.append($("<th>").text("Firstname")); head.append($("<th>").text("Lastname")); thead.append(head); table.append(thead, tbody); $("body").append(table); } function addNewMember(firstName, lastName) { let nb = $("<tr>"); nb.append($("<td>").text(firstName)); nb.append($("<td>").text(lastName)); let remove = $("<td>").text("(x)"); remove.css("background-color", "orange"); remove.click(() => { nb.remove(); }); nb.append(remove); $("tbody").append(nb); } createFamilyTree(); addNewMember("Guillaume", "Salva"); addNewMember("Arielle", "Snizt"); addNewMember("Fanette", "Snizt"); addNewMember("Gerard", "Snizt"); addNewMember("Victor", "Salva"); </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" href="favicon.ico" /> <link rel="stylesheet" href="main.css" /> <title>Minx</title> </head> <body> <header> <h1 style="font-weight: 500">Minx</h1> </header> <main x-data="app" x-cloak> <p x-show.transition.opacity="alert" :class="alert?.type" x-text="alert?.message" ></p> <div class="input_box"> <input placeholder="Enter a URL to shorten..." x-model="url" x-ref="url" /> <div class="copy" @click="copy()" x-show="result">Copy</div> </div> <details> <summary>Advanced settings</summary> <div> <input placeholder="Custom slug" x-model="slug" /> <select required x-model="expires" @change="parseDate()"> <option value="" disabled>Expire Date</option> <option value="1" selected>1 Day</option> <option value="7" selected>7 Days</option> <option value="30">30 Days</option> <option value="90">90 Days</option> <option value="-1">Unlimited</option> </select> <select required x-model="limits" style="margin-left: 1rem"> <option value="" disabled>Request Limits</option> <option value="-1" selected>Unlimited</option> <option value="1">Once</option> <option value="5">5</option> <option value="10">10</option> <option value="30">30</option> </select> </div> <small x-show="slug == ''" >Slug is a randomly generated short id.</small > <small style="padding-top: 0" x-show="limits != -1 || expires != -1"> Your link will be expired <span x-show="expires != -1"> until <b x-text="date"></b> </span> <span x-show="limits != -1"> <span x-show="expires != -1">or </span> after <b x-text="limits"></b><b> request</b>. </span> <span x-show="limits == -1" >with <b>Unlimited</b> request times. </span> </small> </details> <button :class="{ loading }" :disabled="loading || isValidated()" @click="submit($refs, $nextTick)" > Generate </button> </main> <footer> This service is hosted on <a href="https://vercel.com">Vercel</a><br /> <a href="#">&lt;/&gt;</a> with <i>&hearts;</i> by <a href="https://github.com/Matozz">matoz</a> </footer> <script src="alpine.js"></script> <script src="util.js"></script> <script src="main.js"></script> </body> </html>
import React, { useEffect } from 'react' import { useDispatch, useSelector } from 'react-redux' import { Link, useParams } from 'react-router-dom' import { fetchUser, getUser } from '../features/User' import Display from './Display' const UserDetail = () => { const { id } = useParams() const dispatch = useDispatch() const { loading, user, error } = useSelector(getUser) useEffect(() => { dispatch(fetchUser(id)) }, [dispatch, id]) const renderDetails = () => { if (loading) { return <p>Loading user details...</p>; } if (error) { return <p>{error}</p>; } return user ? <Display id={user.id} user={user} /> : null } return ( <div> {renderDetails()} <Link to="/users">Back to user</Link> </div> ) } export default UserDetail
import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:portfolio/src/common/widgets/animated_fade_slide.dart'; import 'package:portfolio/src/common/widgets/selection_area.dart'; import 'package:portfolio/src/constants/sizes.dart'; import 'package:portfolio/src/features/about/presentation/about_section.dart'; import 'package:portfolio/src/features/experience/presentation/experience_section.dart'; import 'package:portfolio/src/features/personal_info/presentation/personal_info_section.dart'; import 'package:portfolio/src/features/main/presentation/widgets/sliver_app_bar.dart'; import 'package:portfolio/src/features/project/presentation/project_section.dart'; import 'package:portfolio/src/features/main/provider/scroll_controller.dart'; import 'package:portfolio/src/features/main/provider/section_key_provider.dart'; import 'package:portfolio/src/common/widgets/responsive.dart'; class MainTablet extends ConsumerStatefulWidget { const MainTablet({super.key}); @override ConsumerState<MainTablet> createState() => _MainTabletState(); } class _MainTabletState extends ConsumerState<MainTablet> { @override Widget build(BuildContext context) { final scrollController = ref.watch(scrollControllerProvider); return Column( children: [ Expanded( child: MySelectionArea( child: Container( color: Theme.of(context).colorScheme.primary, child: CustomScrollView( controller: scrollController, slivers: [ const MySliverAppBar(), SliverList.list( children: [ Padding( padding: _buildResponsivePadding(), child: Align( alignment: Alignment.topLeft, child: AnimatedFadeSlide( offset: const Offset(-128, 0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.symmetric( horizontal: 12, ), child: PersonalInfoSection( key: ref.watch(homeSectionKeyProvider), ), ), gapH100, Padding( padding: const EdgeInsets.symmetric( horizontal: 12, ), child: AboutSection( key: ref.watch(aboutSectionKeyProvider), ), ), gapH100, ExperienceSection( key: ref.watch(experienceSectionKeyProvider), ), gapH100, ProjectSection( key: ref.watch(projectSectionKeyProvider), ), ], ), ), ), ), ], ) ], ), ), ), ), ], ); } EdgeInsetsGeometry _buildResponsivePadding() { if (Responsive.isTablet(context)) { return const EdgeInsets.fromLTRB(48, 60, 48, 88); } else if (Responsive.isMobile(context)) { return const EdgeInsets.fromLTRB(20, 32, 20, 88); } return EdgeInsets.zero; } }
defmodule TextClient.Impl.Player do @typep game :: Hangman.game @typep tally :: Hangman.tally @typep state :: { game, tally } @spec start() :: :ok def start() do game = Hangman.new_game() tally = Hangman.tally(game) interact({ game, tally }) end # @type state :: :intializing | :won | :lost | :good_guess | :bad_guess | :already_used @spec interact(state) :: :ok def interact({ _game, _tally = %{ game_state: :won }}) do IO.puts "Congratulations. You won!" end def interact({ _game, tally = %{ game_state: :lost }}) do IO.puts "Sorry, you lost... the word was #{tally.letters |> Enum.join}" end # def interact({ game, tally }) do # IO.puts feedback_for(tally) # IO.puts current_word(tally) # guess = get_guess() # { updated_game, updated_tally } = Hangman.make_move(game, guess) # interact({ updated_game, updated_tally }) # end def interact({ game, tally }) do IO.puts feedback_for(tally) IO.puts current_word(tally) Hangman.make_move(game, get_guess()) |> interact() end # :intializing | :good_guess | :bad_guess | :already_used def feedback_for(tally = %{ game_state: :intializing }) do "Welcome! I'm thinking of a #{tally.letters |> length} letter word" end def feedback_for(%{ game_state: :good_guess }), do: "Good guess!" def feedback_for(%{ game_state: :bad_guess }), do: "Sorry, that letter's not in the word" def feedback_for(%{ game_state: :already_used }), do: "You already used that letter" def current_word(tally) do [ "Word so far: ", tally.letters |> Enum.join(" "), " turns left: ", tally.turns_left |> to_string, " used so far: ", tally.used |> Enum.join(",") ] end def get_guess() do IO.gets("Next letter: ") |> String.trim() |> String.downcase() end end
import React, { useContext, useState } from 'react' import { createContext } from 'react' const AuthContext=createContext(null) const AuthProvider = ({children}) => { const [user ,setUser]=useState(null) const login = (user)=>{ setUser(user) } const logout = ()=>{ setUser(null) } return ( <AuthContext.Provider value={{user,login,logout}}> {children} </AuthContext.Provider> ) } export const useAuth = ()=>{ return useContext(AuthContext) } export default AuthProvider
package com.example.colorquest import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.colorquest.ui.ColourQuestApp import com.example.colorquest.ui.screens.SketchInterface import com.example.colorquest.ui.theme.ColorQuestTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // applicationContext.createTempUri() setContent { ColorQuestTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { // SketchInterfaceScreen() ColourQuestApp(context = this@MainActivity) // Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { ColorQuestTheme { Greeting("Android") } }
/* * Copyright (C) 2013-2017 microG Project Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.microg.tools.ui; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; public abstract class AbstractAboutFragment extends Fragment { protected abstract void collectLibraries(List<Library> libraries); public static Drawable getIcon(Context context) { try { PackageManager pm = context.getPackageManager(); return pm.getPackageInfo(context.getPackageName(), 0).applicationInfo.loadIcon(pm); } catch (PackageManager.NameNotFoundException e) { // Never happens, self package always exists! throw new RuntimeException(e); } } public static String getAppName(Context context) { try { PackageManager pm = context.getPackageManager(); CharSequence label = pm.getPackageInfo(context.getPackageName(), 0).applicationInfo.loadLabel(pm); if (TextUtils.isEmpty(label)) return context.getPackageName(); return label.toString().trim(); } catch (PackageManager.NameNotFoundException e) { // Never happens, self package always exists! throw new RuntimeException(e); } } protected String getAppName() { return getAppName(getContext()); } public static String getLibVersion(String packageName) { try { String versionName = (String) Class.forName(packageName + ".BuildConfig").getField("VERSION_NAME").get(null); if (TextUtils.isEmpty(versionName)) return ""; return versionName.trim(); } catch (Exception e) { return ""; } } public static String getSelfVersion(Context context) { return getLibVersion(context.getPackageName()); } protected String getSelfVersion() { return getSelfVersion(getContext()); } protected String getSummary() { return null; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View aboutRoot = inflater.inflate(R.layout.about_root, container, false); ((ImageView) aboutRoot.findViewById(android.R.id.icon)).setImageDrawable(getIcon(getContext())); ((TextView) aboutRoot.findViewById(android.R.id.title)).setText(getAppName()); ((TextView) aboutRoot.findViewById(R.id.about_version)).setText(getString(R.string.about_version_str, getSelfVersion())); String summary = getSummary(); if (summary != null) { ((TextView) aboutRoot.findViewById(android.R.id.summary)).setText(summary); aboutRoot.findViewById(android.R.id.summary).setVisibility(View.VISIBLE); } List<Library> libraries = new ArrayList<Library>(); collectLibraries(libraries); Collections.sort(libraries); ViewGroup list = aboutRoot.findViewById(android.R.id.list); for (Library library : libraries) { View v = inflater.inflate(android.R.layout.simple_list_item_2, list, false); ((TextView) v.findViewById(android.R.id.text1)).setText(getString(R.string.about_name_version_str, library.name, getLibVersion(library.packageName))); ((TextView) v.findViewById(android.R.id.text2)).setText(library.copyright != null ? library.copyright : getString(R.string.about_default_license)); list.addView(v); } return aboutRoot; } protected static class Library implements Comparable<Library> { private final String packageName; private final String name; private final String copyright; public Library(String packageName, String name, String copyright) { this.packageName = packageName; this.name = name; this.copyright = copyright; } @Override public String toString() { return name + ", " + copyright; } @Override public int compareTo(Library another) { return name.toLowerCase(Locale.US).compareTo(another.name.toLowerCase(Locale.US)); } } }
<x-app-layout> <x-slot name="header"> <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight"> {{ __('Code') }} </h2> </x-slot> <div class="container text-center" x-data="{ number:'' }"> <div class="row"> <div class="col-4 flex items-center gap-4" > <x-input-label for="name" :value="__('Number of codes')"/> <x-text-input id="number" name="number" type="text" class="mt-1 block" :value="old('number')" required autofocus autocomplete="number" x-model="number"/> </div> <div class="flex items-center gap-4 col-4"> <button x-on:click="generateCode" class="btn btn-success" type="button" name="save">{{ __('Generate') }}</button> <p x-data="{ isGenerated: false }" x-show="isGenerated" x-transition x-init="setTimeout(() => show = false, 2000)" class="text-sm text-gray-600 dark:text-gray-400" >{{ __('Created.') }}</p> </div> </div> </div> <x-widgets.table :url="'/code/list'" :x-ref="'table'"> <x-slot name="th"> <tr> <th>ID</th> <th>Code</th> <th>Door</th> <th>Action</th> </tr> </x-slot> <x-slot name="content"> <tr> <th x-text="event.id"></th> <th x-text="event.code"></th> <th x-text="(event.doors.length>0)?event.doors[0].name:''"></th> <th><a class="btn btn-primary" x-bind:href="'/code/detail/' + event.id">Edit</a></th> </tr> </x-slot> </x-app-widgets.table> </x-app-layout> <script> async function generateCode(){ let code = await(await fetch('/code/generate', { method: 'POST', headers: { 'Content-Type': 'application/json; charset=UTF-8', 'X-CSRF-TOKEN': document.head.querySelector('meta[name=csrf-token]').content }, body: JSON.stringify({'number':this.number,'generate':true}) })).json(); if(code.success){ this.isGenerated = true; alert("Code Generated"); location.reload(); }else{ if(code?.message?.number){ alert(code.message.number); }else{ alert(code.message); } } } </script>
import uniq from "lodash/uniq"; import uniqBy from "lodash/uniqBy"; import { useCallback, useEffect, useMemo, useState } from "react"; import { useQuery } from "react-query"; import { useNotification } from "../../components/NotificationProvider"; import { KeywordSearchResponse } from "../../connector/AbstractConnector"; import { useConfiguration } from "../../core"; import useConnector from "../../core/ConnectorProvider/useConnector"; import useDebounceValue from "../../hooks/useDebounceValue"; import usePrefixesUpdater from "../../hooks/usePrefixesUpdater"; import useTextTransform from "../../hooks/useTextTransform"; export interface PromiseWithCancel<T> extends Promise<T> { cancel?: () => void; } const useKeywordSearch = ({ isOpen }: { isOpen: boolean }) => { const config = useConfiguration(); const connector = useConnector(); const [searchTerm, setSearchTerm] = useState(""); const debouncedSearchTerm = useDebounceValue(searchTerm, 1000); const [selectedVertexType, setSelectedVertexType] = useState("__all"); const [selectedAttribute, setSelectedAttribute] = useState("__all"); const [exactMatch, setExactMatch] = useState(false); const [neighborsLimit, setNeighborsLimit] = useState(true); const textTransform = useTextTransform(); const exactMatchOptions = [{ label: "Exact", value: "Exact" }, { label: "Partial", value: "Partial" }]; const vertexOptions = useMemo(() => { const vertexOps = config?.vertexTypes .map(vt => { const vtConfig = config?.getVertexTypeConfig(vt); return { label: textTransform(vtConfig?.displayLabel || vt), value: vt, }; }) .sort((a, b) => a.label.localeCompare(b.label)) || []; return [{ label: "All", value: "__all" }, ...vertexOps]; }, [config, textTransform]); const onSearchTermChange = useCallback((value: string) => { setSearchTerm(value); }, []); const onVertexOptionChange = useCallback((value: string | string[]) => { setSelectedVertexType(value as string); }, []); const onAttributeOptionChange = useCallback((value: string | string[]) => { setSelectedAttribute(value as string); }, []); const onExactMatchChange = useCallback((value: string) => { if (value === "Exact") { setExactMatch(true); } else { setExactMatch(false); } }, []); const onNeighborsLimitChange = useCallback(() => { setNeighborsLimit(neighborsLimit => !neighborsLimit); }, []); const searchableAttributes = useMemo(() => { if (selectedVertexType !== "__all") { return ( config?.getVertexTypeSearchableAttributes(selectedVertexType) || [] ); } return ( config?.schema?.vertices.flatMap(vertex => config?.getVertexTypeSearchableAttributes(vertex.type) ) || [] ); }, [config, selectedVertexType]); const searchPlaceholder = useMemo(() => { const searchById = config?.connection?.queryEngine === "sparql" ? "URI" : "Id"; if (selectedVertexType === "__all") { const attributes = uniq( searchableAttributes.map( attr => attr.displayLabel || textTransform(attr.name) ) ) .sort((a, b) => a.localeCompare(b)) .slice(0, 5) .join(", "); return `Search by ${attributes || searchById}...`; } const attributes = uniq( config ?.getVertexTypeSearchableAttributes(selectedVertexType) .map(attr => attr.displayLabel || textTransform(attr.name)) ) .sort((a, b) => a.localeCompare(b)) .slice(0, 5) .join(", "); return `Search for ${vertexOptions.find(vt => vt.value === selectedVertexType)?.label } by ${attributes || searchById}`; }, [ config, searchableAttributes, selectedVertexType, textTransform, vertexOptions, ]); const attributesOptions = useMemo(() => { if (selectedVertexType === "__all") { const attributes = uniqBy( searchableAttributes.map(attr => ({ value: attr.name, label: attr.displayLabel || textTransform(attr.name), })), op => op.value ); return [{ label: "All", value: "__all" }, ...attributes]; } const attributes = uniqBy( config ?.getVertexTypeSearchableAttributes(selectedVertexType) .map(attr => ({ value: attr.name, label: attr.displayLabel || textTransform(attr.name), })), op => op.value ); return [{ label: "All", value: "__all" }, ...attributes]; }, [config, searchableAttributes, selectedVertexType, textTransform]); const { enqueueNotification } = useNotification(); const [isMount, setMount] = useState(false); const vertexTypes = selectedVertexType === "__all" ? config?.vertexTypes : [selectedVertexType]; const searchByAttributes = selectedAttribute === "__all" ? uniq(searchableAttributes.map(attr => attr.name).concat("__all")) : [selectedAttribute]; const updatePrefixes = usePrefixesUpdater(); const { data, isFetching } = useQuery( [ "keyword-search", debouncedSearchTerm, vertexTypes, searchByAttributes, exactMatch, neighborsLimit, isMount, isOpen, ], () => { if (!isOpen || !config) { return; } const controller = new AbortController(); const promise = connector.explorer?.keywordSearch( { searchTerm: debouncedSearchTerm, vertexTypes, searchByAttributes, searchById: true, exactMatch: exactMatch, }, { abortSignal: controller.signal } ) as PromiseWithCancel<KeywordSearchResponse>; promise.cancel = () => { controller.abort(); }; return promise; }, { enabled: !!config, onSuccess: response => { if (!response) { return; } updatePrefixes(response.vertices.map(v => v.data.id)); }, onError: (e: Error) => { enqueueNotification({ type: "error", title: "Something went wrong", message: e.message, }); }, } ); if (isOpen && !isMount) { setMount(true); } useEffect(() => { setSelectedAttribute("__all"); setExactMatch(false); setNeighborsLimit(true); }, [selectedVertexType]); return { isFetching, debouncedSearchTerm, onSearchTermChange, onVertexOptionChange, searchPlaceholder, searchTerm, selectedVertexType, vertexOptions, selectedAttribute, attributesOptions, onAttributeOptionChange, exactMatch, exactMatchOptions, onExactMatchChange, neighborsLimit, onNeighborsLimitChange, searchResults: data?.vertices || [], }; }; export default useKeywordSearch;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using LawAPI.Database.Entities; using LawAPI.Dto.MenuElement; using LawAPI.ORM; using LawAPI.Repositories.ExtendedBaseEntityRepositories; using Swashbuckle.Swagger.Annotations; using System.Net; namespace LawAPI.Controllers { [ApiController] [Route("[controller]")] public class MenuElementController : ControllerBase { private readonly ILogger<MenuElementController> logger; private readonly ITransactionCoordinator transactionCoordinator; private readonly IMenuElementRepository menuElementRepository; public MenuElementController(ILogger<MenuElementController> logger, ITransactionCoordinator transactionCoordinator, IMenuElementRepository menuElementRepository) { this.logger = logger; this.transactionCoordinator = transactionCoordinator; this.menuElementRepository = menuElementRepository; } [HttpPost] [Route("/AddMenuElement")] [Authorize] [SwaggerResponse(HttpStatusCode.OK, "MenuElement inserted successfully")] public async Task<ActionResult> AddMenuElement([FromBody] AddMenuElementDto menuElementDto) { var menuElement = await GetMenuElement(menuElementDto); await transactionCoordinator.InCommitScopeAsync(async session => { await menuElementRepository.InsertAsync(menuElement, session); }); return Ok("MenuElement inserted successfully"); } [HttpGet] [Route("/GetAllMenuElementList")] [SwaggerResponse(HttpStatusCode.OK, "MenuElement List")] public async Task<ActionResult<IList<MenuElementDto>>> GetAllMenuElementList() { IList<MenuElementDto> menuElementDtoList = new List<MenuElementDto>(); await transactionCoordinator.InRollbackScopeAsync(async session => { var menuElementList = await menuElementRepository.GetAllAsync(session); if (menuElementList != null) menuElementDtoList = menuElementList.Select(GetMenuElementDto).ToList(); }); return Ok(menuElementDtoList); } [HttpGet] [Route("/GetVisibleMenuElementList")] [SwaggerResponse(HttpStatusCode.OK, "MenuElement List")] public async Task<ActionResult<IList<MenuElementDto>>> GetVisibleMenuElementList() { IList<MenuElementDto> menuElementDtoList = new List<MenuElementDto>(); await transactionCoordinator.InRollbackScopeAsync(async session => { var menuElementList = await menuElementRepository.GetVisibleAsync(session); if (menuElementList != null) menuElementDtoList = menuElementList.Select(GetMenuElementDto).ToList(); }); return Ok(menuElementDtoList); } [HttpPatch] [Route("/UpdateMenuElement")] [Authorize] [SwaggerResponse(HttpStatusCode.OK, "MenuElement updated successfully")] [SwaggerResponse(HttpStatusCode.BadRequest, "MenuElement not found")] public async Task<ActionResult> UpdateMenuElement([FromBody] MenuElementDto menuElementDto) { var menuElement = await transactionCoordinator.InRollbackScopeAsync(async session => { return await menuElementRepository.GetByIdAsync(menuElementDto.MenuElementId, session); }); if (menuElement == null) return BadRequest("MenuElement not found"); await UpdateMenuElement(menuElement, menuElementDto); await transactionCoordinator.InCommitScopeAsync(async session => { await menuElementRepository.UpdateAsync(menuElement, session); }); return Ok("MenuElement updated successfully"); } private async Task UpdateMenuElement(MenuElement menuElement, MenuElementDto menuElementDto) { await transactionCoordinator.InRollbackScopeAsync(async session => { menuElement.Id = menuElementDto.MenuElementId; menuElement.Text = menuElementDto.Text; menuElement.Link = menuElementDto.Link; menuElement.IsVisible = menuElementDto.IsVisible; menuElement.ParentMenuElement = await menuElementRepository.GetByIdAsync(menuElementDto.ParentMenuElementId ?? 0, session); }); } [HttpDelete] [Route("/DeleteMenuElement/{menuElementId}")] [Authorize] [SwaggerResponse(HttpStatusCode.OK, "MenuElement was deleted successfully")] public async Task<ActionResult> DeleteMenuElement([FromRoute] int menuElementId) { await transactionCoordinator.InCommitScopeAsync(async session => { await menuElementRepository.DeleteAsync(menuElementId, session); }); return Ok("MenuElement was deleted successfully"); } private MenuElementDto GetMenuElementDto(MenuElement menuElement) { return new MenuElementDto() { MenuElementId = menuElement.Id, Text = menuElement.Text, Link = menuElement.Link, IsVisible = menuElement.IsVisible, ParentMenuElementId = menuElement.ParentMenuElement?.Id }; } private async Task<MenuElement> GetMenuElement(MenuElementDto menuElementDto) { return await transactionCoordinator.InRollbackScopeAsync(async session => { return new MenuElement() { Id = menuElementDto.MenuElementId, Text = menuElementDto.Text, Link = menuElementDto.Link, IsVisible = menuElementDto.IsVisible, IsDeleted = false, ParentMenuElement = await menuElementRepository.GetByIdAsync(menuElementDto?.ParentMenuElementId ?? 0, session) }; }); } private async Task<MenuElement> GetMenuElement(AddMenuElementDto menuElementDto) { return await transactionCoordinator.InRollbackScopeAsync(async session => { return new MenuElement() { Text = menuElementDto.Text, Link = menuElementDto.Link, IsVisible = menuElementDto.IsVisible, IsDeleted = false, ParentMenuElement = await menuElementRepository.GetByIdAsync(menuElementDto?.ParentMenuElementId ?? 0, session) }; }); } } }
import { useDispatch, useSelector } from "react-redux"; import {FaWhatsapp,FaMoneyCheckAlt} from 'react-icons/fa' import { useNavigate } from "react-router"; import { Link } from "react-router-dom"; import { addToCart } from "../slices/cartSlice"; import { useEffect, useState } from "react"; import axios from "axios"; // import { useGetAllProductsQuery } from "../slices/productsApi"; const excerpt = (str) => { if (str.length > 45) { str = str.substring(0, 45) + " ..."; } return str; }; const Home = () => { function compare(a,b){ if(a._id <b._id){ return 1 } if(a._id >b._id){ return -1 }return 0 } const {items: data , status } = useSelector((state) => state.products); const dispatch = useDispatch(); const navigate = useNavigate(); const [users,setUsers]=useState([]); // const { data, error, isLoading } = useGetAllProductsQuery(); const [query,setQuery]=useState('') const handleAddToCart = (product) => { dispatch(addToCart(product)); navigate("/cart"); }; useEffect(()=>{ async function fetchData(){ try { const res= await axios.get(`http://localhost:5000/api/products`) res.data.sort(compare) const result = res.data.filter((_, index) => index < 30); setUsers( result) console.log(users); } catch (error) { console.log(error); } } fetchData() },[]) return ( <div className="home-container"> {status === "success" ? ( <> <div className='search'> <input type="text" placeholder='Search by title...' onChange={(e)=>setQuery(e.target.value)} /> </div> <h3 style={{color:'blue ' ,textAlign:'center'}}>New Arrivals</h3> <div className="products"> {users && users.filter((user)=>user.name.toLowerCase().includes(query)).map((product) => ( <div key={product._id} className="product"> <h3>{product.name}</h3> <img src={product.image?.url} alt={product.name} /> {/* <div className="details"> <span className="pric"><span style={{display:'flex', gap:'2rem'}}>Price</span> <span>ksh{product.price}</span> </span> </div> */} <div className="details"> <span style={{display:'flex', gap:'4rem'}} > <span> price </span> <span> ksh {product.price}</span></span> </div> <div className="details"> <span style={{display:'flex', gap:'4rem'}} > <span >location</span> <span>{product.location}</span> </span> </div> <div className="details"> <span style={{display:'flex', gap:'4rem'}} > <span>{excerpt(product.desc)} <Link to={`/tour/${product._id}`}>Read More</Link></span> </span> </div> <button onClick={() => handleAddToCart(product)}> Buy </button> <a href={`https://wa.me/${product.No}`} target="_blank" rel="noreferrer noopener" style={{color:'orangered',listStyle:'none',textDecoration:'none'}}> <button style={{backgroundColor:'red'}}>get in touch <FaWhatsapp/>Whatsapp</button> </a> </div> ))} </div> </> ) : status === "pending" ? ( <p>Loading...</p> ) : ( <p>Unexpected error occured...</p> )} </div> ); }; export default Home;
<h3>Add / Edit Performer <small>Add a new Performer or Edit an existing Performer.</small> </h3> <!-- START row--> <div class="row"> <div class="col-lg-6"> <form name="artistInfo" validate-form="" novalidate role="form"> <!-- START panel--> <div class="panel panel-default"> <div class="panel-heading"> <div class="panel-title">Artist Information</div> </div> <div class="panel-body"> <toaster-container toaster-options="{'position-class': 'toast-top-center', 'close-button':true}"></toaster-container> <div class="row"> <div class="form-group col-sm-6"> <label class="control-label">Name *</label> <input type="text" name="name" required="required" class="form-control" ng-model="data.performerName"/> </div> <div class="form-group col-sm-6"> <label class="control-label nowrap">Group Name* </label> <input type="text" name="groupName" required="required" class="form-control" ng-model="data.groupName"/> </div> </div> <div class="form-group"> <label class="control-label nowrap">Artist Type</label> <select name="supervisorId" class="form-control col-sm-4" ng-model="data.artistTypeCode"> <option value="0">Select a Type</option> <option ng-selected="data.artistTypeCode == 1" value="1">DJ</option> <option ng-selected="data.artistTypeCode == 2" value="2">MUSICIAN</option> <option ng-selected="data.artistTypeCode == 4" value="4">SINGER</option> <option ng-selected="data.artistTypeCode == 8" value="8">KARAOKE</option> <option ng-selected="data.artistTypeCode == 16" value="16">COMEDY</option> <option ng-selected="data.artistTypeCode == 32" value="32">MIMIC</option> <option ng-selected="data.artistTypeCode == 1024" value="1024">OTHER</option> </select> </div> <div class="form-group"> <label>Description</label> <textarea placeholder="Enter description" rows="3" ng-model="data.description" class="form-control"></textarea> </div> <div class="form-group"> <label class="control-label nowrap">Email *</label> <input type="email" data-parsley-type="email" name="email" class="form-control" required="required" ng-model="data.email"/> </div> <div class="form-group"> <label class="control-label nowrap">Phone *</label> <input id="phoneNumberId" type="text" masked="" data-inputmask="'mask': '(999) 999-9999', 'autoUnmask': true" name="phone" required="required" class="form-control" ng-model="data.phone"/> </div> <div class="form-group"> <label class="control-label nowrap">Performance Url </label> <input type="text" name="performanceUrl" class="form-control" ng-model="data.performanceUrl"/> </div> <div class="form-group"> <label class="control-label nowrap">Website</label> <input type="text" name="website" class="form-control" ng-model="data.website"/> </div> <div class="form-group"> <label class="control-label nowrap">Facebook Url </label> <input type="text" name="facebook" class="form-control" ng-model="data.facebookSocial"/> </div> <div class="form-group"> <label class="control-label nowrap">Twitter Url </label> <input type="text" name="twitter" class="form-control" ng-model="data.twitterSocial"/> </div> <div class="form-group"> <label class="control-label nowrap">Instagram Url </label> <input type="text" name="instagram" class="form-control" ng-model="data.instagramSocial"/> </div> <div class="form-group"> <label class="control-label nowrap">SoundCloud Url </label> <input type="text" name="soundCloud" class="form-control" ng-model="data.soundCloud"/> </div> <div class="form-group"> <div class="checkbox c-checkbox"> <label> <input type="checkbox" name="enabled" ng-model="data.enabled" ng-true-value="Y" ng-false-value="N"/> <span class="fa fa-check"></span>Activate </label> </div> </div> <div class="required">* Required fields</div> </div> <div class="panel-footer"> <button type="submit" class="btn btn-primary" ng-click="update(artistInfo.$valid,data)">Save</button> </div> </div> <!-- END panel--> </form> </div> <div class="col-sm-6"> <div class="form-group"> <div class="col-sm-12"> <div id="upload-drop" class="box-placeholder text-center"> <p> <em class="fa fa-cloud-upload fa-2x"></em> </p>Upload files by dropping them here or <div class="btn-link form-file">selecting one <input id="upload-select" type="file" name="file" /> </div> </div> <div id="progressbar" class="progress hidden"> <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="progress-bar"></div> </div> </div> <div class="col-sm-12"> <img ng-src="{{data.thumbnailImageUrl}}" alt="" class="img-responsive" style="max-height: 300px; width: auto; margin:auto;"/> </div> </div> </div> </div> <!-- END row-->
#include "CalculateScore.h" class CalculateScore : public ICalculateScore { public: /// <summary> /// Tüm taþlarýn katsayýsýna göre puanlamalarýnýn hesaplanmasýný saðlar. /// </summary> /// <param name="chessboard">Santranç Tahtasý</param> std::map<std::string,double> calculateScore(std::vector<std::vector<Piece>>& chessboard) { findThreatenedCell(chessboard); double totalWhiteScore = 0; double totalBlackScore = 0; for (int xAxis = 0; xAxis < Chessboard::CHESSBOARD_SIZE; ++xAxis) { for (int yAxis = 0; yAxis < Chessboard::CHESSBOARD_SIZE; ++yAxis) { Piece piece = chessboard[xAxis][yAxis]; bool is_threatened = threatenedPieces[{xAxis, yAxis}]; if (piece.pieceType != PieceType::IDLE || piece.color != Color::IDLE) { double score = calculatePieceScore(piece, is_threatened); (piece.color == Color::SIYAH) ? totalBlackScore += score : totalWhiteScore += score; } } } scoreMap["WhiteScore"] = totalWhiteScore; scoreMap["BlackScore"] = totalBlackScore; return scoreMap; } private: //DEFINATIONS std::map<std::pair<int, int>, bool> threatenedPieces; std::map<std::string, double> scoreMap; std::map<PieceType, int> pieceScores = { {PieceType::PÝYON, 1}, {PieceType::AT, 3}, {PieceType::FIL, 3}, {PieceType::KALE, 5}, {PieceType::VEZIR, 9}, {PieceType::SAH, 100} }; // Inherited via ICalculateScore /// <summary> /// Santraç taþýnýn tehdit durumlarýnýn kontrolü için oluþturulmuþ ortak logic yapýsý /// (Bulunan tehdit alaný santranç taþýnýn alanýnýn içinde mi?, /// Santranç tahtasýnda bulunan pozisyon deðerlerinde taþ var mý?, /// bulunan taþ tehdit mi?) /// </summary> /// <param name="newPosX">Bulunan yeni posX deðeri</param> /// <param name="newPosY">Bulunan yeni posY deðeri</param> /// <param name="chessboard">Santranç Tahtasý</param> /// <param name="piece">Santranç Taþý</param> /// <returns>True veya False</returns> bool isChessboardControl(int newPosX, int newPosY, std::vector<std::vector<Piece>>& chessboard, const Piece& piece) override { if (newPosX >= 0 && newPosX < Chessboard::CHESSBOARD_SIZE && newPosY >= 0 && newPosY < Chessboard::CHESSBOARD_SIZE && chessboard[newPosX][newPosY].pieceType != PieceType::IDLE && piece.color != chessboard[newPosX][newPosY].color) { return true; } return false; } /// <summary> /// Taþa göre tehdit edilen santranç taþlarýnýn konumlarýnýn bulunmasýný saðlar. /// </summary> /// <param name="piece">Santranç Taþý</param> /// <param name="chessboard">Santranç Tahtasý</param> void findThreatenedCellsByPiece(const Piece& piece, std::vector<std::vector<Piece>>& chessboard) override { switch (piece.pieceType) { /// <summary> /// Piyon tehditleri /// Beyaz piyonlarýn yukarý yönlü ve siyah piyonlarýn aþaðý yönlü hareketi mevcuttur. /// Bu sebeple newPosX deðerleri renge göre kontrol edilmektedir. /// </summary> /// <param name="piece">Santranç Taþý</param> /// <param name="chessboard">Santraç Tahtasý</param> case PieceType::PÝYON: { int yAxisMotion[] = { -1, 1 }; int newPosX = -1; int newPosY = -1; for (int i = 0; i < 2; ++i) { newPosX = (piece.color == Color::BEYAZ) ? (piece.position.posX - 1) : (piece.position.posX + 1); newPosY = (piece.position.posY) + yAxisMotion[i]; if (isChessboardControl(newPosX, newPosY, chessboard, piece)) { threatenedPieces[{newPosX, newPosY}] = true; } } } break; /// <summary> /// At tehditleri /// L þeklinde tehdit hareketleri mevcut (2 yukarý - 1 sola, 2 yukarý - 1 saða, 2 sola - 1 yukarý, 2 saða - 1 yukarý gibi.) /// </summary> /// <param name="piece">Santranç Taþý</param> /// <param name="chessboard">Santraç Tahtasý</param> case PieceType::AT: { int xAxisMotion[] = { 2, 2, 1, 1, -1, -1, -2, -2 }; int yAxisMotion[] = { 1, -1, 2, -2, 2, -2, 1, -1 }; for (int i = 0; i < 8; ++i) { int newPosX = piece.position.posX + xAxisMotion[i]; int newPosY = piece.position.posY + yAxisMotion[i]; if (isChessboardControl(newPosX, newPosY, chessboard, piece)) { threatenedPieces[{newPosX, newPosY}] = true; } } } break; /// <summary> /// Vezir tehditleri /// Vezirin çapraz ve düz eksenli hareketi mevcuttur. /// Vezirin hareketi kendi grubundan taþa kadar devam eder, kendi grubundan deðilse tehdittir. /// </summary> /// <param name="piece">Santranç Taþý</param> /// <param name="chessboard">Santranç Tahtasý</param> case PieceType::VEZIR: { int xAxisMotion[] = { 1, -1, 0, 0, 1, 1, -1, -1 }; int yAxisMotion[] = { 0, 0, 1, -1, 1, -1, 1, -1 }; for (int axis = 0; axis < 8; axis++) { for (int i = 1; piece.position.posX + xAxisMotion[axis] < 8; ++i) { if (isChessboardControl(piece.position.posX + xAxisMotion[axis], piece.position.posY + yAxisMotion[axis], chessboard, piece)) { threatenedPieces[{piece.position.posX + xAxisMotion[axis], piece.position.posY + yAxisMotion[axis]}] = true; break; } if (piece.color == chessboard[piece.position.posX + xAxisMotion[axis]][piece.position.posY + yAxisMotion[axis]].color) break; } } } break; default: break; } } /// <summary> /// Tüm tehdit edilen taþlarýn bulunmasýný saðlar. /// </summary> /// <param name="chessboard">Santranç Tahtasý</param> void findThreatenedCell(std::vector<std::vector<Piece>>& chessboard) { for (const auto& xAxis : chessboard) { for (const auto& piece : xAxis) { if (piece.pieceType != PieceType::IDLE || piece.color != Color::IDLE) findThreatenedCellsByPiece(piece, chessboard); } } } /// <summary> /// Santranç taþýnýn hesaplamaya alýnacak katsayý deðerinin belirlenmesi, /// tehdit durumunda ise 2'ye bölünecek, deðilse default hesaplama katsayýsý dikkate alýnacak /// </summary> /// <param name="piece">Santranç Taþý</param> /// <param name="isThreatened">Tehdit durumunu tutan deðiþken</param> /// <returns></returns> double calculatePieceScore(Piece& piece, bool isThreatened) override { return isThreatened ? (pieceScores[piece.pieceType] / 2.0) : pieceScores[piece.pieceType]; } };
import { Alert, FlatList, Pressable, StyleSheet, Text, View } from "react-native"; import { useDispatch, useSelector } from "react-redux"; import CartListItem from "../components/CartListItem"; import { selectSubCartTotal, selectDeliveryFee, selectTotal, clearCart, } from "../store/cartSlice"; import { useCreateOrderMutation, useCreatePaymentIntentMutation } from "../store/apiSlice"; import {useStripe} from '@stripe/stripe-react-native' const ShoppingCartTotals = ({subTotal, deliveryFee, total}) => ( <View style={styles.totalContainer}> <View style={styles.row}> <Text style={styles.text}>Subtotal</Text> <Text style={styles.text}>${subTotal}</Text> </View> <View style={styles.row}> <Text style={styles.text}>Delievery</Text> <Text style={styles.text}>${deliveryFee}</Text> </View> <View style={styles.row}> <Text style={[styles.text, { fontWeight: "600" }]}>Total</Text> <Text style={[styles.text, { fontWeight: "600" }]}>${total}</Text> </View> </View> ); const ShoppingCart = () => { const cart = useSelector(state => state.cart.item) const cartSubTotal = useSelector(selectSubCartTotal) const deliveryFee = useSelector(selectDeliveryFee) const total = useSelector(selectTotal) const dispatch = useDispatch() const [createOrder, {data, error, isLoading}] = useCreateOrderMutation(); const [createPaymentIntent] = useCreatePaymentIntentMutation(); const {initPaymentSheet, presentPaymentSheet} = useStripe() const onCheckout = async() => { const response = await createPaymentIntent({ amount: Math.floor(total*100)}); if(response.error) { Alert.alert("Something went wrong"); return; } const initResponse = await initPaymentSheet({ merchantDisplayName: 'Virendra Khorwal', paymentIntentClientSecret: response.data.client_secret, }) if(initResponse.error) { console.log(error); Alert.alert('Something went Wrong'); return; } const paymentResponse = await presentPaymentSheet(); if(paymentResponse.error){ Alert.alert( `Error code: ${paymentResponse.error.code}`, paymentResponse.error.message ) return; } onCreateOrder(); } const onCreateOrder = async() => { const result = await createOrder({ items: cart, subTotal: cartSubTotal, deliveryFee: deliveryFee, total: total, customer: { name: "John Doe", phone: "1234567890", address: "123 Main St", city: "New York", postalCode: "12345", country: "USA" } }) if(result.data?.status ==="OK") { Alert.alert("Success", `Your order has been placed successfully. Your order reference is : ${result.data.data.ref}`) dispatch(clearCart()); } } return ( <> <FlatList data={cart} renderItem={({ item }) => <CartListItem cartItem={item} />} ListFooterComponent={() => <ShoppingCartTotals subTotal={cartSubTotal} deliveryFee={deliveryFee} total={total} />} /> <Pressable onPress={onCheckout} style={styles.button}> <Text style={styles.buttonText}> {isLoading ? "Placing Order..." : "Checkout"} </Text> </Pressable> </> ); }; export default ShoppingCart; const styles = StyleSheet.create({ totalContainer: { margin: 20, paddingTop: 10, borderColor: "#e3e3e3", borderTopWidth: 1, }, row: { flexDirection: "row", justifyContent: "space-between", marginVertical: 5, }, text: { fontSize: 16, color: "#8e8e8e", }, button: { backgroundColor: "black", borderRadius: 100, alignItems: "center", position: "absolute", alignSelf: "center", bottom: 40, padding: 16, width: "90%", }, buttonText: { fontSize: 16, fontWeight: "500", color: "white", }, });
import 'package:flutter/material.dart'; import 'package:kima/src/utils/colors.dart'; import 'package:qr_flutter/qr_flutter.dart'; import '../../utils/widgets/common/button_widget.dart'; class ProfileQRCodeScreen extends StatefulWidget { const ProfileQRCodeScreen({super.key}); static const route = '/profile/qr_code'; @override State<ProfileQRCodeScreen> createState() => _ProfileQRCodeScreenState(); } class _ProfileQRCodeScreenState extends State<ProfileQRCodeScreen> { /// For QR Code final GlobalKey _qrGlobalKey = GlobalKey(); String _strQRCodeFormat = ''; @override void initState() { super.initState(); _strQRCodeFormat = 'Rafael Desuyo\'s Profile'; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( 'Create QR Code', style: TextStyle(color: Colors.white), ), backgroundColor: Colors.black, centerTitle: true, // elevation: 0, // titleSpacing: 0, leading: IconButton( icon: const Icon( Icons.clear, color: Colors.grey, ), tooltip: 'close', onPressed: () async { Navigator.of(context).pop(); }, ), ), backgroundColor: Colors.black, body: SafeArea( child: Container( padding: const EdgeInsets.all(16), width: double.infinity, height: double.infinity, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ const SizedBox(height: 30,), RepaintBoundary( key: _qrGlobalKey, child: QrImageView( data: _strQRCodeFormat, version: QrVersions.auto, backgroundColor: AppColors.primaryColor, size: MediaQuery.of(context).size.width / 2, ), ), const SizedBox(height: 20,), Text( 'Rafael Desuyo\'s Profile', style: TextStyle( color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold, ), ), const Spacer(), ButtonWidget( onTap: () async { }, title: 'Share QR Code', fontSize: 15, fontWeight: FontWeight.bold, textColor: Colors.white, buttonWidth: double.infinity, buttonHeight: 30, buttonColor: AppColors.primaryColor, borderRadius: 20, ), ButtonWidget( onTap: () async { }, title: 'Save as Image', fontSize: 15, fontWeight: FontWeight.bold, textColor: AppColors.primaryColor, buttonWidth: double.infinity, buttonHeight: 30, buttonColor: Colors.black, borderColor: AppColors.primaryColor, borderWidth: 2, borderRadius: 20, margin: const EdgeInsets.only(top: 10, bottom: 20), ), ], ), ), ), ); } }
import torch import numpy as np import os from typing import Tuple from torch.utils.data import Dataset from torchvision.transforms import ToTensor, Resize from LookGenerator.datasets.utils import load_image class PersonSegmentationDatasetMultichannel(Dataset): """ DEPRECATED Dataset for a Person Segmentation task, uses multichannel mask Might be deprecated soon """ def __init__(self, image_dir: str, transform_input=None, transform_output=None, augment=None): """ Args: image_dir: Directory with all images transform_input: A transform to be applied on input images. Default: None transform_output: A transform to be applied on mask of image. Default: None """ super().__init__() self.root = image_dir self.transform_input = transform_input self.transform_output = transform_output self.augment = augment list_of_files = os.listdir(image_dir + r"\image") self._files_list = [file.split('.')[0] for file in list_of_files] def __getitem__(self, idx) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: idx: The index of data sample Returns: A Pair of X and y objects for segmentation """ seed = torch.random.seed() if torch.is_tensor(idx): idx = idx.tolist() to_tensor = ToTensor() input_ = load_image(self.root, "image", self._files_list[idx], ".jpg") target = torch.tensor([]) channel_list = os.listdir(os.path.join( self.root, "image-parse-v3-multichannel", self._files_list[idx] )) channel_files_list = [file.split('.')[0] for file in channel_list] for channel in channel_files_list: part = to_tensor((load_image(self.root, os.path.join("image-parse-v3-multichannel", self._files_list[idx]), channel, ".png"))) if self.transform_output: torch.manual_seed(seed) part = self.transform_output(part) target = torch.cat((target, part), dim=0) input_ = to_tensor(input_) if self.transform_input: torch.manual_seed(seed) input_ = self.transform_input(input_) return input_.float(), target.float() def __len__(self): """ Returns: the length of the dataset """ return len(self._files_list) class PersonSegmentationDatasetMultichannelV2(Dataset): """ DEPRECATED Dataset for a Person Segmentation task, uses multichannel mask Might be deprecated soon """ def __init__(self, image_dir: str, transform_input=None, transform_output=None, augment=None): """ Args: image_dir: Directory with all images transform_input: A transform to be applied on input images. Default: None transform_output: A transform to be applied on mask of image. Default: None """ super().__init__() self.root = image_dir self.transform_input = transform_input self.transform_output = transform_output self.augment = augment list_of_files = os.listdir(image_dir + r"\image") self._files_list = [file.split('.')[0] for file in list_of_files] def __getitem__(self, idx) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: idx: The index of data sample Returns: A Pair of X and y objects for segmentation """ if torch.is_tensor(idx): idx = idx.tolist() to_tensor = ToTensor() input_ = np.array(load_image(self.root, "image", self._files_list[idx], ".jpg")) target = [] channel_list = os.listdir(os.path.join( self.root, "image-parse-v3.1-multichannel", self._files_list[idx] )) for channel in channel_list: target.append(np.array(load_image( self.root, os.path.join("image-parse-v3.1-multichannel", self._files_list[idx]), channel, "" ))) target = np.dstack(target) transformed = self.augment(image=input_, mask=target) transformed['mask'][:, :, 0] = (~transformed['mask'][:, :, 0]).astype(np.uint8) input_ = to_tensor(transformed['image']) target = to_tensor(transformed['mask']) return input_, target def __len__(self): """ Returns: the length of the dataset """ return len(self._files_list) class PersonSegmentationDataset(Dataset): """Dataset for a Person Segmentation task""" def __init__(self, image_dir: str, transform_input=None, transform_output=None, augment=None): """ Args: image_dir: Directory with all images transform_input: transform to be performed on an input, from pytorch transform_output: transform to be performed on an output, from pytorch augment: transforms from albumentations to be used on image and mask """ super().__init__() self.root = image_dir self.transform_input = transform_input self.transform_output = transform_output self.augment = augment list_of_files = os.listdir(image_dir + r"\image") self._files_list = [file.split('.')[0] for file in list_of_files] def __getitem__(self, idx) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: idx: The index of data sample Returns: A Pair of X and y objects for segmentation """ if torch.is_tensor(idx): idx = idx.tolist() to_tensor = ToTensor() input_ = np.array(load_image(self.root, "image", self._files_list[idx], ".jpg")) target = np.array(load_image(self.root, "agnostic-v3.3", self._files_list[idx], ".png")) if self.augment: transformed = self.augment(image=input_, mask=target) input_ = transformed['image'] target = transformed['mask'] input_ = to_tensor(input_) target = to_tensor(target) if self.transform_input: input_ = self.transform_input(input_) if self.transform_output: input_ = self.transform_output(target) return input_, target def __len__(self): """ Returns: the length of the dataset """ return len(self._files_list)
--- date: 2024-06-06 id: processors title: Log Processors --- Every pipeline includes a chain of processors that define the transformations it will apply to logs. When a log matches a pipeline's filter, it is transformed by each processor in the pipeline one by one. The following log transformation processors are available for defining pipelines. ## Regex The Regex processor can be used to extract information out of text using [regular expressions](https://www3.ntu.edu.sg/home/ehchua/programming/howto/Regexe.html). #### Processor Fields | Field | Description | |---------------|-----------------| | Name | A descriptive name for the processor. | | Pattern | The regex pattern to be used. Must include atleast one named capture group | | Parse&#160;From | The log text field to parse from. Eg: `body` or `attributes.sessionInfo` | | Parse&#160;To | The path to parse to. Eg: If set to `attributes`, a capture group like `(?P<userId>.+)` in the regex pattern would get stored in `attributes.userId` | | On&#160;Error | What to do if the processor fails. Options are to `drop` the log or `send` it to the next processor | ## Grok The Grok processor can be used to extract information out of text using grok patterns. [Grok](https://www.elastic.co/guide/en/elasticsearch/reference/current/grok.html) is a regular expression dialect with convenient [aliases](https://github.com/vjeantet/grok/blob/master/patterns.go) for commonly used expressions. #### Processor Fields | Field | Description | |---------------|-----------------| | Name | A descriptive name for the processor. | | Pattern | The [grok pattern](https://grokdebugger.com/) to be used. Must include atleast one named capture group | | Parse&#160;From | The log text field to parse from. Eg: `body` or `attributes.sessionInfo` | | Parse&#160;To | The path to parse to. Eg: If set to `attributes`, a capture group like `%{WORD:userId}` in the grok pattern would get stored in `attributes.userId` | | On&#160;Error | What to do if the processor fails. Options are to `drop` the log or `send` it to the next processor | <Admonition> By default, values extracted using grok patterns are strings. For example, parsing `status: 202` with the pattern `status: %{INT:status_code}` will extract `status_code` as a string with value `"202"`. However, it is possible to extract `float` or `int` typed values by adding a 3rd part to grok capture groups. For example, parsing `status: 202` with the pattern `status: %{INT:status_code:int}` will extract `status_code` as an integer with value `202`. This can enable the use of numeric operators (`>`, `<` etc) on the extracted values and unlock features like using the values as metrics in dashboards. </Admonition> ## JSON Parser The JSON parsing processor can be used to parse serialized JSON text into log attributes. #### Processor Fields | Field | Description | |---------------|-----------------| | Name | A descriptive name for the processor. | | Parse&#160;From | The log field containing serialized JSON text. Eg: `body` or `attributes.sessionInfo` | | Parse&#160;To | The path to parse to. Eg: If set to `attributes`, parsing the JSON text `'{ "userId": 8888 }'` would set `attributes.userId` to `8888` | ## Trace Parser The trace processor can be used to populate trace id, span id and trace flags for a log. Populating trace identifiers in logs allows navigation to and from corresponding traces for correlation. #### Processor Fields | Field | Description | |---------------|-----------------| | Name | A descriptive name for the processor. | | Parse&#160;Trace&#160;Id&#160;From | The log field containing otel Trace Id. Eg: `attributes.myTraceId` <br/> Value at the specified path must be an even length string of hex characters | | Parse&#160;Span&#160;Id&#160;From | The log field containing otel Span Id. Eg: `attributes.mySpanId` <br/> Value at the specified path must be an even length string of hex characters | | Parse&#160;Trace&#160;Flags&#160;From | The log field containing otel Trace Flags. Eg: `attributes.myTraceFlags` <br/> Value at the specified path must be an unsigned int | <Admonition> At least one field among `Parse Trace Id From`, `Parse Span Id From` and `Parse Trace Flags From` must be specified. </Admonition> ## Timestamp Parser The timestamp parsing processor can be used to parse log timestamp out of a log field. #### Processor Fields | Field | Description | |---------------|-----------------| | Name&#160;of&#160;Timestamp&#160;Parsing&#160;Processor | A descriptive name for the processor. | | Parse&#160;Timestamp&#160;Value&#160;From | The log field containing timestamp value. Eg: `attributes.timestamp` | | Timestamp&#160;Format&#160;Type | Type of timestamp value to be parsed. <br/> `epoch` can be used for parsing [unix time](https://en.wikipedia.org/wiki/Unix_time) and `strptime` can be used for parsing human readable values using [ctime-like directives](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/internal/coreinternal/timeutils/internal/ctimefmt/ctimefmt.go#L68) such as %Y (4-digit year) and %H (2-digit hour). | | Timestamp&#160;Format | Format for parsing timestamp value. <br/> For example `%Y-%m-%d` can be used for parsing values like `2023-12-06` when Timestamp Format Type is `strptime`, or `seconds.milliseconds` can be used for parsing unix time values like `1701869406.245` when Timestamp Format Type is `epoch` | ## Severity Parser The severity parsing processor can be used to parse log severity out of a log field. #### Processor Fields | Field | Description | |---------------|-----------------| | Name&#160;of&#160;Severity&#160;Parsing&#160;Processor | A descriptive name for the processor. | | Parse&#160;Severity&#160;Value&#160;From | The log field to parse severity from. For example `attributes.log_level` | | Values&#160;for&#160;level&#160;TRACE | Comma separated list of values that should be mapped to level TRACE. For example `0, trace` | | Values&#160;for&#160;level&#160;DEBUG | Comma separated list of values that should be mapped to level DEBUG. For example `debug, 2xx` | | Values&#160;for&#160;level&#160;INFO | Comma separated list of values that should be mapped to level INFO. For example `info, 3xx` | | Values&#160;for&#160;level&#160;WARN | Comma separated list of values that should be mapped to level WARN. For example `warning, 4xx` | | Values&#160;for&#160;level&#160;ERROR | Comma separated list of values that should be mapped to level ERROR. For example `error, 5xx` | | Values&#160;for&#160;level&#160;FATAL | Comma separated list of values that should be mapped to level FATAL. For example `panic, -1` | <Admonition> Severity level values are case insensitive.<br/> As a special case, 2xx, 3xx, 4xx and 5xx can be used to map number ranges to severity levels. This can be useful for mapping HTTP status codes. For example `5xx` can be used to parse numbers between 500-599 into level `ERROR`. </Admonition> ## Add The add processor can be used to add a field to the log. #### Processor Fields | Field | Description | |---------------|-----------------| | Name | A descriptive name for the processor. | | Field | Path of the field to be added. Must be of the form `attributes.*` or `resource.*` | | Value | The value to be set in the specified field | <Admonition> The value field can be set to an [expression](https://github.com/open-telemetry/opentelemetry-log-collection/blob/main/docs/types/expression.md) which will get evaluated for each entry to set the value. For example the value can be set to `EXPR(attributes.subtotal + attributes.taxes)` to add a new field for total. Value expressions are also useful for accessing array items that can't be referenced with field paths in operators like `COPY` and `MOVE`, for example `EXPR(attributes.locale[0])`. </Admonition> ## Remove The remove processor can be used for removing unwanted log fields such as PII. #### Processor Fields | Field | Description | |---------------|-----------------| | Name | A descriptive name for the processor. | | Field | Path of the field to be removed. Must be of the form `attributes.*` or `resource.*` | ## Move The move processor can be used to move or rename a log field. #### Processor Fields | Field | Description | |---------------|-----------------| | Name | A descriptive name for the processor. | | From | Path of the field to be moved. Must be of the form `attributes.*` or `resource.*` | | To | Path to move the field to. Must be of the form `attributes.*` or `resource.*` | ## Copy The copy processor can be used to copy log fields. #### Processor Fields | Field | Description | |---------------|-----------------| | Name | A descriptive name for the processor. | | From | Path of the field to be copied. Must be of the form `attributes.*` or `resource.*` | | To | Path to copy the field to. Must be of the form `attributes.*` or `resource.*` |
// // SignUpViewModel.swift // VolunteerSigniiner // // Created by Jhen Mu on 2023/4/2. // import Foundation import RxSwift import RxCocoa import RxRelay import GoogleSignIn import FirebaseAuth import FBSDKLoginKit enum AuthError: Error { case unknown case cancelled } class SignUpViewModel { var pushToController: (() -> Void)? //MARK: - UI let loginButtonLoginTapped = PublishSubject<Void>() let accountInputChanged = BehaviorRelay<String>(value: "") let passwordInputChanged = BehaviorRelay<String>(value: "") private let disposeBag = DisposeBag() private let authService = FirebaseAuthService() private let facebookLoginManager = LoginManager() private var inputAccount: String = "" private var inputPassword: String = "" private let accountCheckHelper = AccountCheckHelper() //MARK: - initialization init() { accountInputChanged .subscribe(onNext: { text in self.inputAccount = text }) .disposed(by: disposeBag) passwordInputChanged .subscribe(onNext: { text in self.inputPassword = text }) .disposed(by: disposeBag) loginButtonLoginTapped .subscribe(onNext: { self.normalSignUp(completion: { message in print("message:\(message)") }) }) .disposed(by: disposeBag) } private func normalSignUp(completion: @escaping (String) -> (Void)) { let fillState = accountCheckHelper.checkBothAcountAndPassword(with: inputAccount, with: inputPassword) switch fillState { case .acountUnfill: print(fillState.text) completion(fillState.text) case .passwordUnfill: print(fillState.text) completion(fillState.text) case .bothUnfill: print(fillState.text) completion(fillState.text) case .fillComplete: print(fillState.text) if accountCheckHelper.checkAccount(with: inputAccount) == .unverify { print(accountCheckHelper.checkAccount(with: inputAccount).acountVerify) } else if accountCheckHelper.checkPassword(with: inputPassword) == .unverify { print(accountCheckHelper.checkPassword(with: inputPassword).passwordVerify) } else { authService.createUser(with: inputAccount, with: inputPassword) { response in print("authService response:\(response.description)") //如果電子郵件已經註冊過了,那就跳出Alert去提示,然後確定之後就跳回登入頁面去執行正規登入 completion(fillState.text) } } } } }
--- description: 設定可傳送Customer Journey Analytics資料的雲端匯出位置 keywords: Analysis Workspace title: 設定雲端匯出位置 feature: Components exl-id: 93f1cca0-95da-41a0-a4f9-5ab620a5b9da source-git-commit: dbc0210936e8205fbe97b3c88e6c37597e7e43e3 workflow-type: tm+mt source-wordcount: '1510' ht-degree: 4% --- # 設定雲端匯出位置 在您可以將Customer Journey Analytics報表匯出至雲端目的地之前(如所述) [將Customer Journey Analytics報表匯出至雲端](/help/analysis-workspace/export/export-cloud.md),您需要新增並設定傳送資料的位置。 此程式包括新增及設定帳戶(例如Amazon S3、Google Cloud Platform等),如所述 [設定雲端匯出帳戶](/help/components/exports/cloud-export-accounts.md),然後在該帳戶內新增並設定位置(例如帳戶內的資料夾),如本文所述。 如需有關如何管理現有位置(包括檢視、編輯和刪除位置)的資訊,請參閱 [管理雲端匯出位置和帳戶](/help/components/exports/manage-export-locations.md). ## 開始建立雲端匯出位置 1. 您必須先新增帳戶,才能新增位置。 如果您尚未新增帳戶,請依照所述新增帳戶 [設定雲端匯出帳戶](/help/components/exports/cloud-export-accounts.md). 1. 在Customer Journey Analytics中選取 [!UICONTROL **元件**] > [!UICONTROL **匯出**]. 1. 選取 [!UICONTROL **位置**] 索引標籤,然後選取 [!UICONTROL **新增位置**]. ![匯出視窗,其中選取了「位置」標籤,並醒目提示新增位置按鈕](assets/location-add.png) 或 選取 [!UICONTROL **位置帳戶**] 索引標籤中,選取現有帳戶上要新增位置的3點圖示,然後選取 [!UICONTROL **新增位置**]. ![GCP帳戶和省略符號下拉式功能表,其中顯示已選取新增位置](assets/add-location-existing-account.png) 「位置」對話方塊隨即顯示。 1. 指定下列資訊: |欄位 |函式 | ---------|----------| | [!UICONTROL **名稱**] |位置名稱。 | | [!UICONTROL **說明**] |提供帳戶的簡短說明,以協助將其與相同帳戶型別的其他帳戶區分開來。 | | [!UICONTROL **位置帳戶**] |選取您要建立位置的帳戶。 如需有關如何建立帳戶的資訊,請參閱 [設定雲端匯出帳戶](/help/components/exports/cloud-export-accounts.md). | 1. 在 [!UICONTROL **位置屬性**] 區段,指定您位置帳戶之帳戶型別的專屬資訊。 繼續以下對應至您在所選帳戶型別的區段 [!UICONTROL **位置帳戶**] 欄位。 ### AEP 資料登陸區域 >[!IMPORTANT] > >將Customer Journey Analytics報表匯出至Adobe Experience Platform資料登陸區域時,請務必在7天內下載資料,然後從AEP資料登陸區域將其刪除。 7天後,資料會自動從AEP資料登陸區域刪除。 1. [開始建立雲端匯出位置](#begin-creating-a-cloud-export-location),如上所述。 1. 在 [!UICONTROL **位置屬性**] 的區段 [!UICONTROL **新增位置**] 對話方塊中,指定下列資訊以設定Adobe Experience Platform資料登陸區域的位置: <!-- still need to update; can't create AEP account --> | 欄位 | 函數 | |---------|----------| | [!UICONTROL **前置詞**] | 容器內您要放置資料的資料夾。 指定資料夾名稱,然後在名稱后面加上斜線以建立資料夾。 例如, `folder_name/` | {style="table-layout:auto"} 1. 選取&#x200B;[!UICONTROL **「儲存」**]。 1. 您現在可以將資料從Analysis Workspace匯出至您設定的帳戶和位置。 如需如何將資料匯出至雲端的詳細資訊,請參閱 [將專案資料匯出至雲端](/help/analysis-workspace/export/export-cloud.md). 1. 在AEP資料登陸區域中存取資料的最簡單方式是使用Microsoft Azure Storage Explorer。 此工具與設定相關資訊的指示相同, [AEP資料登陸區域帳戶](/help/components/exports/cloud-export-accounts.md#aep-data-landing-zone). 1. 開啟 [Microsoft Azure儲存體總管](https://azure.microsoft.com/en-us/products/storage/storage-explorer/). 1. 前往 [!UICONTROL **儲存體帳戶**] > [!UICONTROL **(附加的容器)**] > [!UICONTROL **Blob容器**] > **[!UICONTROL cjaexport-_數字_]**>*** your_container_name ***. >[!NOTE] > >資料夾名稱 **[!UICONTROL cjaexport-_數字_]**是Azure儲存體總管提供的預設名稱。 如果您只有與SAS URI關聯的單一連線(正常),則此資料夾的名稱將為&#x200B;**[!UICONTROL cjaexport-1]**. ![存取Azure儲存體總管中的檔案](assets/azure-storage-explorer-access.png) 1. 選取您要下載的匯出,然後選取「 」 [!UICONTROL **下載**] 以下載。 ### Amazon S3 Role ARN 1. [開始建立雲端匯出位置](#begin-creating-a-cloud-export-location),如上所述。 1. 在 [!UICONTROL **位置屬性**] 的區段 [!UICONTROL **新增位置**] 對話方塊中,指定下列資訊以設定Amazon S3角色ARN位置: <!-- still need to update; can't create S3 role ARN account --> | 欄位 | 函數 | |---------|----------| | [!UICONTROL **分段**] | 您想要將Adobe Analytics資料傳送至的Amazon S3帳戶中的貯體。 確保Adobe提供的使用者ARN有權將檔案上傳到此貯體。 | | [!UICONTROL **前置詞**] | 要放置資料之儲存貯體中的資料夾。 指定資料夾名稱,然後在名稱后面加上斜線以建立資料夾。 例如, folder_name/ | {style="table-layout:auto"} 1. 選取&#x200B;[!UICONTROL **「儲存」**]。 1. 您現在可以將資料從Analysis Workspace匯出至您設定的帳戶和位置。 如需如何將資料匯出至雲端的詳細資訊,請參閱 [將專案資料匯出至雲端](/help/analysis-workspace/export/export-cloud.md). ### Google Cloud Platform 1. [開始建立雲端匯出位置](#begin-creating-a-cloud-export-location),如上所述。 1. 在 [!UICONTROL **位置屬性**] 的區段 [!UICONTROL **新增位置**] 對話方塊中,指定下列資訊以設定Google Cloud平台位置: <!-- still need to update; can't create GCP account --> | 欄位 | 函數 | |---------|----------| | [!UICONTROL **分段**] | 您想要傳送Customer Journey Analytics資料的GCP帳戶中的貯體。 確保您已授予Adobe所提供之主體的許可權,可將檔案上傳至此儲存貯體。 (本金提供於 [設定Google Cloud Platform帳戶](/help/components/exports/cloud-export-accounts.md).) 如需授與許可權的詳細資訊,請參閱 [將主體新增至貯體層級原則](https://cloud.google.com/storage/docs/access-control/using-iam-permissions#bucket-add) (位於Google Cloud檔案中)。 | | [!UICONTROL **前置詞**] | 要放置資料之儲存貯體中的資料夾。 指定資料夾名稱,然後在名稱后面加上斜線以建立資料夾。 例如, folder_name/ | {style="table-layout:auto"} 1. 選取&#x200B;[!UICONTROL **「儲存」**]。 1. 您現在可以將資料從Analysis Workspace匯出至您設定的帳戶和位置。 如需如何將資料匯出至雲端的詳細資訊,請參閱 [將專案資料匯出至雲端](/help/analysis-workspace/export/export-cloud.md). ### Azure SAS 1. [開始建立雲端匯出位置](#begin-creating-a-cloud-export-location),如上所述。 1. 在 [!UICONTROL **位置屬性**] 的區段 [!UICONTROL **新增位置**] 對話方塊中,指定下列資訊以設定Azure SAS位置: | 欄位 | 函數 | |---------|----------| | [!UICONTROL **容器名稱**] | 您指定要將Customer Journey Analytics資料傳送到的帳戶中的容器。 | | [!UICONTROL **前置詞**] | 容器內您要放置資料的資料夾。 指定資料夾名稱,然後在名稱后面加上斜線以建立資料夾。 例如, `folder_name/` | {style="table-layout:auto"} 1. 選取&#x200B;[!UICONTROL **「儲存」**]。 1. 您現在可以將資料從Analysis Workspace匯出至您設定的帳戶和位置。 如需如何將資料匯出至雲端的詳細資訊,請參閱 [將專案資料匯出至雲端](/help/analysis-workspace/export/export-cloud.md). ### Azure RBAC 1. [開始建立雲端匯出位置](#begin-creating-a-cloud-export-location),如上所述。 1. 在 [!UICONTROL **位置屬性**] 的區段 [!UICONTROL **新增位置**] 對話方塊中,指定下列資訊以設定Azure RBAC位置: | 欄位 | 函數 | |---------|----------| | [!UICONTROL **容器**] | 您指定要將Adobe Analytics資料傳送至何處的帳戶中的容器。 請確定您授與許可權,可以將檔案上傳至您先前建立的Azure應用程式。 | | [!UICONTROL **前置詞**] | 容器內您要放置資料的資料夾。 指定資料夾名稱,然後在名稱后面加上斜線以建立資料夾。 例如, `folder_name/` | | [!UICONTROL **帳戶**] | Azure儲存體帳戶。 | {style="table-layout:auto"} 1. 選取&#x200B;[!UICONTROL **「儲存」**]。 1. 您現在可以將資料從Analysis Workspace匯出至您設定的帳戶和位置。 如需如何將資料匯出至雲端的詳細資訊,請參閱 [將專案資料匯出至雲端](/help/analysis-workspace/export/export-cloud.md). ### Snowflake 1. [開始建立雲端匯出位置](#begin-creating-a-cloud-export-location),如上所述。 1. 在 [!UICONTROL **位置屬性**] 的區段 [!UICONTROL **新增位置**] 對話方塊中,指定下列資訊以設定Snowflake位置: | 欄位 | 函數 | |---------|----------| | [!UICONTROL **資料庫**] | 指定的資料庫應為現有資料庫。 您建立的角色必須具備存取此資料庫的許可權。<p>這是與階段名稱關聯的資料庫。</p><p>您可以使用下列命令,將此角色許可權授與Snowflake中的資料庫: `GRANT USAGE ON DATABASE <your_database> TO ROLE <your_role>;`</p> <p>如需詳細資訊,請參閱 [Snowflake檔案中的「資料庫、綱要,以及共用命令」頁面](https://docs.snowflake.com/en/sql-reference/commands-database).</p> | | [!UICONTROL **綱要**] | 指定的結構描述應該是現有的結構描述。 您建立的角色必須具備存取此綱要的許可權。<p>這是與階段名稱關聯的結構描述。<p>您可以使用下列命令,將您建立的許可權授與Snowflake綱要中的角色: `GRANT USAGE ON SCHEMA <your_database>.<your_schema> TO ROLE <your_role>;`</p><p>如需詳細資訊,請參閱 [Snowflake檔案中的「資料庫、綱要,以及共用命令」頁面](https://docs.snowflake.com/en/sql-reference/commands-database).</p> | | [!UICONTROL **階段名稱**] | 以Snowflake儲存資料檔案的內部階段名稱。<p>請確定您在帳戶中指定的角色具有此階段名稱的讀取和寫入許可權。 (由於您正在授與讀取和寫入存取權,我們建議您使用僅由Adobe使用的階段。)<p>您可以使用以下命令授予Snowflake中階段名稱的讀取和寫入許可權: `GRANT READ, WRITE ON STAGE <your_database>.<your_schema>.<your_stage_name> TO ROLE <your_role>;`</p> <p>如需授與許可權給角色的相關資訊,請參閱 [在Snowflake檔案中授與許可權](https://docs.snowflake.com/en/sql-reference/sql/grant-privilege). <p>如需有關階段名稱的詳細資訊,請參閱 [在Snowflake檔案中選擇「本機檔案的內部階段」頁面](https://docs.snowflake.com/en/user-guide/data-load-local-file-system-create-stage).</p> | | [!UICONTROL **階段路徑**] | 資料檔以Snowflake儲存所在位置的路徑。 <p>如需詳細資訊,請參閱 [在Snowflake檔案中選擇「本機檔案的內部階段」頁面](https://docs.snowflake.com/en/user-guide/data-load-local-file-system-create-stage).</p> | {style="table-layout:auto"} 1. 選取&#x200B;[!UICONTROL **「儲存」**]。 1. 您現在可以將資料從Analysis Workspace匯出至您設定的帳戶和位置。 如需如何將資料匯出至雲端的詳細資訊,請參閱 [將專案資料匯出至雲端](/help/analysis-workspace/export/export-cloud.md).
package com.google.android.setupdesign.view; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.widget.FrameLayout; import androidx.recyclerview.widget.RecyclerView; import com.google.android.setupdesign.DividerItemDecoration; import com.google.android.setupdesign.R$styleable; import java.util.Objects; public class HeaderRecyclerView extends RecyclerView { public View header; public int headerRes; public boolean shouldHandleActionUp = false; public static class HeaderAdapter<CVH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public final RecyclerView.Adapter<CVH> adapter; public View header; public final C21551 observer; public final int getItemCount() { int itemCount = this.adapter.getItemCount(); if (this.header != null) { return itemCount + 1; } return itemCount; } public final long getItemId(int i) { if (this.header != null) { i--; } if (i < 0) { return Long.MAX_VALUE; } return this.adapter.getItemId(i); } public final int getItemViewType(int i) { if (this.header != null) { i--; } if (i < 0) { return Integer.MAX_VALUE; } return this.adapter.getItemViewType(i); } public final void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) { View view = this.header; if (view != null) { i--; } if (!(viewHolder instanceof HeaderViewHolder)) { this.adapter.onBindViewHolder(viewHolder, i); } else if (view != null) { if (view.getParent() != null) { ((ViewGroup) this.header.getParent()).removeView(this.header); } ((FrameLayout) viewHolder.itemView).addView(this.header); } else { throw new IllegalStateException("HeaderViewHolder cannot find mHeader"); } } public HeaderAdapter(RecyclerView.Adapter<CVH> adapter2) { C21551 r0 = new RecyclerView.AdapterDataObserver() { public final void onChanged() { HeaderAdapter.this.notifyDataSetChanged(); } public final void onItemRangeChanged(int i, int i2) { HeaderAdapter headerAdapter = HeaderAdapter.this; if (headerAdapter.header != null) { i++; } RecyclerView.AdapterDataObservable adapterDataObservable = headerAdapter.mObservable; Objects.requireNonNull(adapterDataObservable); adapterDataObservable.notifyItemRangeChanged(i, i2, (Object) null); } public final void onItemRangeInserted(int i, int i2) { HeaderAdapter headerAdapter = HeaderAdapter.this; if (headerAdapter.header != null) { i++; } headerAdapter.notifyItemRangeInserted(i, i2); } public final void onItemRangeMoved(int i, int i2) { if (HeaderAdapter.this.header != null) { i++; i2++; } for (int i3 = 0; i3 < 1; i3++) { HeaderAdapter.this.notifyItemMoved(i + i3, i2 + i3); } } public final void onItemRangeRemoved(int i, int i2) { HeaderAdapter headerAdapter = HeaderAdapter.this; if (headerAdapter.header != null) { i++; } headerAdapter.notifyItemRangeRemoved(i, i2); } }; this.observer = r0; this.adapter = adapter2; adapter2.registerAdapterDataObserver(r0); setHasStableIds(adapter2.mHasStableIds); } public final RecyclerView.ViewHolder onCreateViewHolder(RecyclerView recyclerView, int i) { if (i != Integer.MAX_VALUE) { return this.adapter.onCreateViewHolder(recyclerView, i); } FrameLayout frameLayout = new FrameLayout(recyclerView.getContext()); frameLayout.setLayoutParams(new FrameLayout.LayoutParams(-1, -2)); return new HeaderViewHolder(frameLayout); } } public HeaderRecyclerView(Context context) { super(context); init((AttributeSet) null, 0); } public final boolean dispatchKeyEvent(KeyEvent keyEvent) { View findFocus; boolean z = false; if (this.shouldHandleActionUp && keyEvent.getAction() == 1) { this.shouldHandleActionUp = false; z = true; } else if (keyEvent.getAction() == 0) { int keyCode = keyEvent.getKeyCode(); if (keyCode != 19) { if (keyCode == 20 && (findFocus = findFocus()) != null) { int[] iArr = new int[2]; int[] iArr2 = new int[2]; findFocus.getLocationInWindow(iArr); getLocationInWindow(iArr2); int measuredHeight = (findFocus.getMeasuredHeight() + iArr[1]) - (getMeasuredHeight() + iArr2[1]); if (measuredHeight > 0) { smoothScrollBy$1(0, Math.min((int) (((float) getMeasuredHeight()) * 0.7f), measuredHeight), false); } } this.shouldHandleActionUp = z; } else { View findFocus2 = findFocus(); if (findFocus2 != null) { int[] iArr3 = new int[2]; int[] iArr4 = new int[2]; findFocus2.getLocationInWindow(iArr3); getLocationInWindow(iArr4); int i = iArr3[1] - iArr4[1]; if (i < 0) { smoothScrollBy$1(0, Math.max((int) (((float) getMeasuredHeight()) * -0.7f), i), false); } } this.shouldHandleActionUp = z; } z = true; this.shouldHandleActionUp = z; } if (z) { return true; } return super.dispatchKeyEvent(keyEvent); } public final void setAdapter(RecyclerView.Adapter adapter) { if (!(this.header == null || adapter == null)) { HeaderAdapter headerAdapter = new HeaderAdapter(adapter); headerAdapter.header = this.header; adapter = headerAdapter; } super.setAdapter(adapter); } public final void init(AttributeSet attributeSet, int i) { if (!isInEditMode()) { TypedArray obtainStyledAttributes = getContext().obtainStyledAttributes(attributeSet, R$styleable.SudHeaderRecyclerView, i, 0); this.headerRes = obtainStyledAttributes.getResourceId(0, 0); obtainStyledAttributes.recycle(); } } public final void onInitializeAccessibilityEvent(AccessibilityEvent accessibilityEvent) { int i; super.onInitializeAccessibilityEvent(accessibilityEvent); if (this.header != null) { i = 1; } else { i = 0; } accessibilityEvent.setItemCount(accessibilityEvent.getItemCount() - i); accessibilityEvent.setFromIndex(Math.max(accessibilityEvent.getFromIndex() - i, 0)); accessibilityEvent.setToIndex(Math.max(accessibilityEvent.getToIndex() - i, 0)); } public final void setLayoutManager(RecyclerView.LayoutManager layoutManager) { super.setLayoutManager(layoutManager); if (layoutManager != null && this.header == null && this.headerRes != 0) { this.header = LayoutInflater.from(getContext()).inflate(this.headerRes, this, false); } } public HeaderRecyclerView(Context context, AttributeSet attributeSet) { super(context, attributeSet); init(attributeSet, 0); } public HeaderRecyclerView(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); init(attributeSet, i); } public static class HeaderViewHolder extends RecyclerView.ViewHolder implements DividerItemDecoration.DividedViewHolder { public final boolean isDividerAllowedAbove() { return false; } public final boolean isDividerAllowedBelow() { return false; } public HeaderViewHolder(FrameLayout frameLayout) { super(frameLayout); } } }
<script lang="ts"> import { PatientReadingGraph } from '$lib/components'; import type { PageData } from './$types'; import { page } from '$app/stores'; import { getContext } from 'svelte'; import type { Writable } from 'svelte/store'; import type { Toast } from '$lib/stores'; import { goto } from '$app/navigation'; import { getPreOpReading, getReadingArray, isPostOp } from '$lib/utils/utils'; export let data: PageData; $: patient = data.patient; $: reading = getReadingArray(patient.reading); $: preOpReading = getPreOpReading(reading, patient.case_date); $: preOpIop = preOpReading ? preOpReading['iop'] : null; $: preOpMeds = preOpReading ? preOpReading['medication'] : null; const redirectFrom = $page.url.searchParams.get('redirectFrom'); const toast = getContext<Writable<Toast>>('toast'); if (redirectFrom === 'editReading') { const recordDate = new Date($page.url.searchParams.get('date') ?? ''); toast.set({ hasMessage: true, message: `Updated IOP Reading from ${recordDate.toDateString()}` }); } let showConfirmDelete = false; const toggleShowConfirmDelete = () => { showConfirmDelete = !showConfirmDelete; }; const handleAddReading = () => goto(`/patient/${patient?.id}/reading/add`); </script> <main class="container-fluid grid"> <section> <header> <h3 class="label">Patient</h3> <h4 id="detail-heading-name"> <span>{patient?.name_last}, </span><span>{patient.name_first}</span> </h4> </header> <table> <tbody> <tr> <td> Case Date </td> <td> {patient.case_date} </td> </tr> <tr> <td> Pre-Op IOP </td> <td> {preOpIop ?? 'N/A'} </td> </tr> <tr> <td> Pre-Op Meds </td> <td> {preOpMeds ?? 'N/A'} </td> </tr></tbody > </table> <div class="container"> <button on:click={handleAddReading}> Add Reading </button> </div> </section> <section> {#if patient} <section class="container-fluid"> <header> <h3>IOP and Meds</h3> </header> <PatientReadingGraph reading={ reading.filter(reading => isPostOp(reading, patient.case_date)) } /> </section> {:else} <section> <article> <header> <h2>Patient Not Found</h2> </header> </article> </section> {/if} </section> <dialog open={showConfirmDelete}> <article> <header> <h2>Confirm Delete</h2> </header> <p>Are you sure you want to delete this patient?</p> <form action="?/deletePatient" method="post"> <input type="hidden" name="name_last" value={patient.name_last} /> <input type="hidden" name="name_first" value={patient.name_first} /> <button type="submit">Delete</button> </form> <footer> <button on:click={toggleShowConfirmDelete}>Cancel</button> </footer> </article> </dialog> </main> <style lang="scss"> main { @media (min-width: 992px) { grid-template-columns: 1fr 4fr; } } .label { font-size: 12px; border: 1px solid black; padding: 0 0.25rem; border-radius: 1rem; background-color: var(--secondary); color: var(--secondary-inverse); margin: 0 auto 0.25rem 0; } #detail-heading-name { margin: 0; } table { border: 1px solid #ccc; } tr { border: none; td:first-child { font-weight: bold; } } td { border: none; font-size: 12px; } header { display: flex; flex-direction: column; justify-content: center; } h2, h3 { margin: auto; } </style>
=head1 NAME WebService::UMLSKS::ConnectUMLS - Authenticate the user before accessing UMLSKS with valid username and password. =head1 SYNOPSIS =head2 Basic Usage use WebService::UMLSKS::ConnectUMLS; print "Enter username to connect to UMLSKS:"; my $username = <>; print "Enter password:"; ReadMode 'noecho'; my $pwd = ReadLine 0; ReadMode 'normal'; my $c = new Connect; my $service = $c->connect_umls( $username, $pwd ); =head1 DESCRIPTION This module has package ConnectUMLS which has three subroutines 'new', 'get_pt' and 'connect_umls'. This module takes the username and password from getUserDetails module and connects to the authentication server. It returns a valid proxy ticket if the user is valid or returns an invalid service object if UMLS sends an invalid proxy ticket. =head1 SUBROUTINES The subroutines are as follows: =cut ############################################################################### ########## CODE STARTS HERE ################################################# # This module has package Connect which has three subroutines 'new', 'get_pt' and 'connect_umls'. use warnings; use SOAP::Lite; use strict; no warnings qw/redefine/; #http://www.perlmonks.org/?node_id=582220 package WebService::UMLSKS::ConnectUMLS; use Log::Message::Simple qw[msg error debug]; # This sub creates a new object of Connect =head2 new This sub creates a new object of ConnectUMLS. =cut sub new { my $class = shift; my $self = {}; bless( $self, $class ); return $self; } #-------Following code is taken from the reference program provided by Olivier B. #-------and is modified according to the need of the application. # These are the Universal Resource Identifier for WSDL and authentication service. # These URIs will be used for authentication of the user. # Please see 'http://umlsks.nlm.nih.gov/DocPortlet/html/dGuide/appls/appls1.html' for details. my $KSAUTH_WSDL_URI = #'http://mor.nlm.nih.gov/auth-ob.wsdl'; 'https://uts-ws.nlm.nih.gov/authorization/services/AuthorizationPort?WSDL'; #'http://mor.nlm.nih.gov/auth-ob.wsdl'; my $UMLSKS_WSDL_URI = 'https://uts-ws.nlm.nih.gov/UMLSKS/services/UMLSKSService?wsdl'; #'http://umlsks.nlm.nih.gov/UMLSKS/services/UMLSKSService?WSDL'; my $UMLSKS_URI = #'https://uts-ws.nlm.nih.gov'; #'https://uts.nlm.nih.gov'; 'http://umlsks.nlm.nih.gov'; my $pt_service; my $pgt; =head2 connect_umls This sub takes username and password as arguments and returns a proxy ticket object after it authenticates the user. =cut sub connect_umls { my $self = shift; my $username = shift; my $pwd = shift; my $verbose = shift; # Initialize Authentication service. $pt_service = SOAP::Lite->service($KSAUTH_WSDL_URI); # Get proxy granting ticket. $pgt = $pt_service->getProxyGrantTicket( $username, $pwd ); # If proxy granting ticket is not defined dispalying the error message. if ( not defined $pgt ) { print "\nYou entered wrong username or password\n"; return 0; } # If pgt is obtained, user is a valid user. else { msg("\nProxy granting ticket : $pgt", $verbose); # Get proxy ticket. my $pt = get_pt(); msg("\n Proxy Ticket:$pt",$verbose); # Initialize UMLSKS service. my $service = SOAP::Lite->service($UMLSKS_WSDL_URI); msg("\n service=$service\n",$verbose); return $service; } } # This sub returns the proxy ticket. =head2 get_pt This sub returns a proxy ticket. =cut sub get_pt { return $pt_service->getProxyTicket( $pgt, $UMLSKS_URI ); } 1; #-------------------------------PERLDOC STARTS HERE------------------------------------------------------------- =head1 SEE ALSO ValidateTerm.pm GetUserData.pm Query.pm ws-getUMLSInfo.pl =cut =head1 AUTHORS Mugdha Choudhari, University of Minnesota Duluth E<lt>chou0130 at d.umn.eduE<gt> Ted Pedersen, University of Minnesota Duluth E<lt>tpederse at d.umn.eduE<gt> =head1 COPYRIGHT Copyright (C) 2011, Mugdha Choudhari, Ted Pedersen This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to The Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. =cut #---------------------------------PERLDOC ENDS HERE---------------------------------------------------------------
<!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"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <!-- MI CSS --> <link rel="stylesheet" href="css/main.css"> <title> BODEN - Suscripción Literaria </title> </head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-pale"> <div class="container-fluid"> <a class="navbar-brand" href="index.html"> <img src="images/logo.png" alt="BODEN"> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ms-auto"> <li class="nav-item"> <a class="nav-link active" href="suscripciones.html">SUSCRIPCIONES</a> </li> <li class="nav-item"> <a class="nav-link active" href="entregas-anteriores.html"> ENTREGAS ANTERIORES </a> </li> <li class="nav-item"> <a class="nav-link active" href="club.html">CLUB</a> </li> <li class="nav-item"> <a class="nav-link active" href="consultas.html">CONSULTAS</a> </li> </ul> </div> </div> </nav> </header> <main class="mainIndex"> <!-- CARROUSEL --> <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button> </div> <div class="carousel-inner w-100"> <div class="carousel-item active"> <img src="images/biblioteca/biblio2.png" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="images/biblioteca/biblio1.png" class="d-block w-100" alt="..."> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" 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="#carouselExampleIndicators" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> <!-- ENDS CARROUSEL --> <div class="intro"> <h1 class="descBoden"> <strong>RECIBILO CADA MES EN TU CASA</strong> </h1> <h2 class="descBoden">RECIBÍ CADA MES UNA NOVEDAD O CLÁSICO LITERARIO EN LA PUERTA DE TU CASA. <br> DATE UN GUSTO CON ESTA CUIDADOSA SELECCIÓN DE LIBROS PARA VOS O PARA REGALAR.</h2> </div> <div class="container-fluid "> <div class="d-flex justify-content-center align-content-center"> <h2 class="h2index"> <strong>ENTREGAS ANTERIORES</strong> </h2> </div> <div class="row m-1 d-flex justify-content-center align-content-center gridIndex"> <img src="images/tapas/tapa-horda.png" alt="Tapa libro La horda primitiva" class="tapaHorda tapa py-5 col-sm-6 col-md-4 col-lg-3"> <img src="images/tapas/tapa-balada.png" alt="Tapa libro Balada de pajaros cantores y serpientes" class="tapaBalada tapa py-5 col-sm-6 col-md-4 col-lg-3"> <img src="images/tapas/tapa-viento.png" alt="Tapa libro El viento que arrasa" class="tapaViento tapa py-5 col-sm-6 col-md-4 col-lg-3"> <img src="images/tapas/tapa-cielo.png" alt="Tapa libro El cielo con las manos" class="tapaCielo tapa py-5 col-sm-6 col-md-4 col-lg-3"> <img src="images/tapas/tapa-coronel.png" alt="Tapa libro El Coronel no tiene quien le escriba" class="tapaCoronel tapa py-5 col-sm-6 col-md-4 col-lg-3"> <img src="images/tapas/tapa-salvatierra.png" alt="Tapa libro Salvatierra" class="tapaSalvatierra tapa py-5 col-sm-6 col-md-4 col-lg-3"> <img src="images/tapas/tapa-uruguaya.png" alt="Tapa libro La Uruguaya" class="tapaUruguaya tapa py-5 col-sm-6 col-md-4 col-lg-3"> <img src="images/tapas/tapa-rio.png" alt="Tapa libro No es un río" class="tapaRio tapa py-5 col-sm-6 col-md-4 col-lg-3"> </div> </div> </main> <footer> <div> <h4>REDES SOCIALES</h4> <ul> <li><a href="https://www.facebook.com/" target="_blank"> <img src="images/redes/facebook.png" alt="logo de facebook" class="redes"> </a> </li> <li><a href="https://www.instagram.com/" target="_blank"><img src="images/redes/instagram.png" alt="logo de instagram" class="redes"></a> </li> <li><a href="https://twitter.com" target="_blank"><img src="images/redes/twitter.png" alt="logo de twitter" class="redes"></a> </li> <li><a href="https://www.whatsapp.com/" target="_blank"><img src="images/redes/whatsapp.png" alt="logo de whatsapp" class="redes"></a> </li> </ul> </div> </footer> <div> <p class="misDatos"> MANUELA D'AGOSTO - <a href="https://www.coderhouse.com/" target="_blank"> <b> CODER HOUSE </b> </a> Comision 37195</p> <div> <!-- BOOTSTRAP --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> </html>
import axios from 'axios'; import { faker } from '@faker-js/faker'; import { AxiosHttpClient } from './axios-http-client'; import { mockFailureHttpResponse, mockGetRequest } from '@/data/test/mock-http'; import { mockAxios, MockedAxios } from '../test'; jest.mock('axios'); type SutTypes = { sut: AxiosHttpClient; mockedAxios: MockedAxios; }; const makeSut = (key?: string, defaultParams?: any): SutTypes => { const sut = new AxiosHttpClient(key, defaultParams); const mockedAxios = mockAxios(); return { sut, mockedAxios }; }; describe('Infra: AxiosHttpClient', () => { afterEach(() => jest.clearAllMocks()); it('should call axios with correct values', async () => { const request = mockGetRequest(); const { sut, mockedAxios } = makeSut(); await sut.get(request); const params = { ...request.params }; expect(mockedAxios.get).toHaveBeenCalledWith(request.url, { params }); }); it('should call axios with correct values and key if its passed', async () => { const request = mockGetRequest(); const key = faker.datatype.uuid(); const { sut, mockedAxios } = makeSut(key); await sut.get(request); const params = { ...request.params, key }; expect(mockedAxios.get).toHaveBeenCalledWith(request.url, { params }); }); it('should return the correct statusCode and data', () => { const { sut, mockedAxios } = makeSut(); const promise = sut.get(mockGetRequest()); expect(promise).toEqual(mockedAxios.get.mock.results[0].value); }); it('should return the correct statusCode on failure', () => { const { sut, mockedAxios } = makeSut(); mockedAxios.get.mockRejectedValueOnce(mockFailureHttpResponse()); const promise = sut.get(mockGetRequest()); expect(promise).toEqual(mockedAxios.get.mock.results[0].value); }); });
import React, { useContext, useState, useEffect } from "react"; import { AuthContext } from "../../context/auth-context"; import { PostContext } from "../../context/post-context"; import { useHttpClient } from "../../hoc/http-hook"; import LikeThumb from "./LikeThumb"; function PostLikeButton() { const auth = useContext(AuthContext); const { postData, purpose } = useContext(PostContext); const [liked, setLiked] = useState(false); const [likeNum, setLikeNum] = useState(postData?.like); const { sendRequest } = useHttpClient(); useEffect(() => { if (!auth.isLoggedIn) { return; } const checkAlreadyLike = async () => { try { const responseData = await sendRequest( `${process.env.REACT_APP_BASE_URL}/users/checkLike/${ purpose === "lecture" ? "lecture" : "qa" }/${postData._id}`, "GET", null, { Authorization: "Bearer " + auth.token, } ); if (responseData.isLiked) { setLiked(responseData.isLiked); } } catch (err) {} }; checkAlreadyLike(); }, []); const likeHandler = async () => { if (!auth.isLoggedIn) { return alert("로그인이 필요한 기능입니다."); } try { const responseData = await sendRequest( `${process.env.REACT_APP_BASE_URL}/${ purpose === "lecture" ? "lecture" : "qa" }/like/${postData._id}`, "PATCH", null, { Authorization: "Bearer " + auth.token, } ); if (responseData.likeSuccess) { setLiked(true); setLikeNum((prev: number) => prev + 1); } } catch (err) {} }; const dislikeHandler = async () => { if (!auth.isLoggedIn) { return alert("로그인이 필요한 기능입니다."); } try { const responseData = await sendRequest( `${process.env.REACT_APP_BASE_URL}/${ purpose === "lecture" ? "lecture" : "qa" }/dislike/${postData._id}`, "PATCH", null, { Authorization: "Bearer " + auth.token, } ); if (responseData.disLikeSuccess) { setLiked(false); setLikeNum((prev: number) => prev - 1); } } catch (err) {} }; return ( <div className="flex justify-center mb-4"> <div className="flex flex-col items-center justify-center"> <button className={`flex items-center px-2 py-1 mb-2 border-2 rounded hover:bg-[rgba(0,0,0,0.1)] ${ liked ? "border-[#ffcdd2]" : "border-black" }`} onClick={liked ? dislikeHandler : likeHandler} > {liked ? <LikeThumb isLike={true} /> : <LikeThumb isLike={false} />} <span className={`text-xl font-semibold ${liked && "text-[#ffcdd2]"}`} > {likeNum} </span> </button> {liked && auth.isLoggedIn && purpose === "lecture" && ( <span className="text-[#ffcdd2] font-bold"> 마이페이지에서 강의를 확인할 수 있어요! </span> )} </div> </div> ); } export default PostLikeButton;
import React from "react"; import { NOTE_TYPE } from "../../../const.js"; import { useStoryMap } from "../../../hooks/useStoryMap/useStoryMap.js"; import { Story } from "../../../models/story.model.ts"; import { Note } from "../../Note/Note.tsx"; interface StoryNoteComponentProps { story: Story; selected: { id: string }; setSelected: (selected: any) => void; updateStoryTitle: (epicId: string, featureId: string, storyId: string, title: string) => void; addNewStory: (epicId: string, featureId: string, storyId: string) => void; maybeRemoveStory: (epicId: string, featureId: string, storyId: string) => Promise<Story | null | undefined>; focusStoryAfterRemoval: (story: any) => void; maybeNavigate: (arrowKey: string) => void; } class StoryNoteComponent extends React.Component<StoryNoteComponentProps> { constructor(props: StoryNoteComponentProps) { super(props); this.markAsSelected = this.markAsSelected.bind(this); this.updateTitle = this.updateTitle.bind(this); this.add = this.add.bind(this); this.remove = this.remove.bind(this); this.navigate = this.navigate.bind(this); } markAsSelected() { const { setSelected } = this.props; setSelected({ id: this.props.story.id, epicId: this.props.story.epicId, featureId: this.props.story.featureId, type: NOTE_TYPE.STORY }); } updateTitle(editedTitle: any) { const { updateStoryTitle, story } = this.props; updateStoryTitle(story.epicId, story.featureId, story.id, editedTitle); } add() { const { addNewStory, story } = this.props; addNewStory(story.epicId, story.featureId, story.id); } async remove() { const { maybeRemoveStory, focusStoryAfterRemoval, story } = this.props; const removedStory = await maybeRemoveStory(story.epicId, story.featureId, story.id); if (removedStory) focusStoryAfterRemoval(story); } navigate(arrowKey: any) { const { maybeNavigate } = this.props; maybeNavigate(arrowKey); } render() { const { story, selected } = this.props; return <Note id={story.id} title={story.title} type={NOTE_TYPE.STORY} focusable={false} selected={selected.id === story.id} markAsSelected={this.markAsSelected} updateTitle={this.updateTitle} add={this.add} remove={this.remove} navigate={this.navigate} />; } } export function StoryNote({ story }) { const { addNewStory, updateStoryTitle, maybeRemoveStory, focusStoryAfterRemoval, selected, setSelected, maybeNavigate } = useStoryMap(); return ( <StoryNoteComponent story={story} selected={selected} setSelected={setSelected} updateStoryTitle={updateStoryTitle} addNewStory={addNewStory} maybeRemoveStory={maybeRemoveStory} focusStoryAfterRemoval={focusStoryAfterRemoval} maybeNavigate={maybeNavigate} /> ); }
/* * @lc app=leetcode.cn id=120 lang=cpp * * [120] 三角形最小路径和 */ #include <vector> #include <algorithm> using namespace std; // @lc code=start class Solution { public: int minimumTotal(vector<vector<int>> &triangle) { if (triangle.size() == 1) { return triangle[0][0]; } vector<vector<int>> dp(triangle.size()); // dp[i][j]代表到triangle[i][j]的距离 dp[0].push_back(triangle[0][0]); for (int i = 1; i < triangle.size(); i++) { dp[i] = vector<int>(dp[i - 1].size() + 1, 0); for (int j = 0; j < triangle[i].size(); j++) { if (j == 0) { dp[i][j] = dp[i - 1][j] + triangle[i][j]; continue; } if (j == triangle[i].size() - 1) { dp[i][j] = dp[i - 1][j - 1] + triangle[i][j]; continue; } dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j]) + triangle[i][j]; } } return *min_element(dp[triangle.size() - 1].begin(), dp[triangle.size() - 1].end()); } }; // @lc code=end int main(int argc, char const *argv[]) { Solution solution; vector<vector<int>> ret = {{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}}; solution.minimumTotal(ret); return 0; }
<ion-header> <nl-modal-navbar [title]="title" (modalClosed)="dismiss()"></nl-modal-navbar> </ion-header> <ion-content class="csPlainGray"> <form #newCircularForm="ngForm" (ngSubmit)="onSubmit()"> <ion-card> <ion-item> <ion-label stacked> <b>Title</b><ion-badge class="csRight">{{50 - circularTitle?.length}}</ion-badge> </ion-label> <ion-textarea [(ngModel)]="circularTitle" placeholder="Enter Title" maxlength=50 required name="circularTitle"> </ion-textarea> </ion-item> </ion-card> <ion-card> <ion-item> <ion-label stacked> <b>Description</b><ion-badge class="csRight">{{2500 - description?.length}}</ion-badge> </ion-label> <ion-textarea [(ngModel)]="description" placeholder="Enter Description" maxlength=200 required name="description"> </ion-textarea> </ion-item> </ion-card> <ion-card> <ion-item> <ion-label><b>Effective Date</b></ion-label> <ion-datetime max="2018" [min]="todayDate()" displayFormat="MMM DD YYYY" pickerFormat="DD MMM YYYY" name="expireDate" [(ngModel)]="effectiveDate" ></ion-datetime> </ion-item> </ion-card> <ion-card > <ion-item> <ion-label><b>Circular For</b></ion-label> <ion-select [disabled]="amyDisabled" [(ngModel)]="mainAudience" (ionChange)="onAudienceChange()" required name="mainAudience"> <ion-option *ngFor="let audience of audienceList" [value]="audience">{{audience.name}}</ion-option> </ion-select> </ion-item> </ion-card> <div *ngIf="departmentList && mainAudience.id == 2"> <ion-card> <ion-item> <ion-label><b>Select Departments</b></ion-label> <ion-select [(ngModel)]="departmentIds" multiple required name="departments"> <ion-option *ngFor="let dep of departmentList" [value]="dep.id">{{dep.name}}</ion-option> </ion-select> </ion-item> </ion-card> </div> <div *ngIf="mainAudience?.subAudience && (mainAudience.id == 1 || mainAudience.id == 2)"> <ion-card> <ion-item> <ion-label><b>Subcategories</b></ion-label> <ion-select [(ngModel)]="audienceIds" multiple required name="subCategory"> <ion-option *ngFor="let subCat of mainAudience.subAudience" [value]="subCat.id">{{subCat.name }}</ion-option> </ion-select> </ion-item> </ion-card> </div> <div *ngIf="programList && mainAudience?.id == 3 "> <ion-card> <ion-item> <ion-label><b>Select Programs</b></ion-label> <ion-select [(ngModel)]="programIds" multiple required name="programs"> <ion-option *ngFor="let pgm of programList" [value]="pgm.id">{{pgm.name}}</ion-option> </ion-select> </ion-item> </ion-card> </div> <div *ngIf=" mainAudience?.id == 3 "> <ion-card> <ion-item> <ion-label><b>Select Years</b></ion-label> <ion-select [(ngModel)]="yearIds" multiple required name="years"> <ion-option *ngFor="let y of yearList" [value]="y.id">{{y.name}}</ion-option> </ion-select> </ion-item> </ion-card> </div> <div *ngIf=" mainAudience?.id == 4 && yearsListForModule"> <ion-card> <ion-item> <ion-label><b>Select Year</b></ion-label> <ion-select [disabled]="amyDisabled" [(ngModel)]="yearForModule" (ionChange)="onYearForModuleChange()" required name="yearsModule"> <ion-option *ngFor="let y of yearsListForModule" [value]="y">{{y.name || y.yearName}}</ion-option> </ion-select> </ion-item> </ion-card> </div> <div *ngIf=" mainAudience?.id == 4 && yearForModule"> <ion-card> <ion-item> <ion-label><b>Select Modules</b></ion-label> <ion-select [disabled]="amyDisabled" [(ngModel)]="moduleIds" multiple required name="years"> <ion-option *ngFor="let module of modulesObject[yearForModule.id || yearForModule.yearId]" [value]="module.moduleId || module.id">{{module.moduleName || module.name}}</ion-option> </ion-select> </ion-item> </ion-card> </div> <div> <ion-icon name="cloud-upload" class="large-icon"></ion-icon> <button type="button" class="csCenter" ion-button (click)="onUploadBtn()">Upload File</button> <button type="button" ion-button clear (click)="onFileUnselect()" *ngIf="image || file">unselect File </button> <ion-spinner name="bubbles" *ngIf="showSpinner"></ion-spinner> <ion-card *ngIf="image"> Image Preview <img [src]="image" alt="Image File"> </ion-card> <h2 *ngIf="file && fileName"> Attached File: {{fileName}} </h2> </div> <div padding> <button [disabled]="!newCircularForm.valid" ion-button full type="submit">Submit</button> </div> </form> </ion-content>
import * as path from "path"; import * as nodeDir from "node-dir"; let fs: any = require("fs-extra"); // reference: https://www.gregjs.com/javascript/2016/checking-whether-a-file-directory-exists-without-using-fs-exists/ /** * checks whether a path specified by filePath is a file * @param filePath path to the file */ export async function isFile(filePath: string): Promise<boolean> { return new Promise<boolean>((resolve: any, reject: any) => { return fs.lstat(filePath, (err: any, stats: any) => { if (err !== null && err !== undefined) { resolve(false); } else { resolve(stats.isFile()); } }); }); } /** * checks whether a file specified by filePath is existed * @param filePath absolute path to the file */ export async function exists(filePath: string): Promise<boolean> { return await isFile(filePath); } /** * read all text of a file specified by filePath * @param filePath path to the text file */ export async function readAllText(filePath: string): Promise<string> { return new Promise<string>((resolve: any, reject: any) => { try { fs.readFile(filePath, "utf8", (err: any, buffer: any) => { if (err) { reject(err); } else { resolve(buffer); } }); } catch (err) { reject(err); } }); } /** * get all file paths inside a directory synchronously * @param dir path of the directory * @param recursive specify whether the function should load files in subdirectories recursively, default is true */ export function getFilesSync(dir: string, recursive: boolean = true): Array<string> { var files: Array<string> = []; fs.readdirSync(dir).forEach((file: string) => { var subpath: string = path.join(dir, file); if (fs.lstatSync(subpath).isFile()) { files.push(subpath); } else if (recursive === true) { files = files.concat(getFilesSync(subpath, recursive)); } }); return files; } /** * get all file paths inside a directory recursively and asynchronously * @param dir path of the directory */ export async function getFiles(dir: string): Promise<string[]> { return new Promise<string[]>((resolve: any, reject: any) => { nodeDir.files(dir, (err: any, filePaths: string[]) => { if (err) { reject(err); } else { resolve(filePaths); } }); }); } export async function writeFile(p: string, data: any): Promise<boolean> { return new Promise<boolean>((resolve: any, reject: any) => { fs.writeFile(p, data, (err: any) => { if (err) { reject(err); } else { resolve(true); } }); }); } export async function readTextFile(filePath: string): Promise<string> { return new Promise<string>((resolve: any, reject: any) => { fs.readFile(filePath, "utf8", (err: any, data: any) => { if (err) { reject(err); } else { resolve(data); } }); }); } export async function saveFile(filePath: string, data: any): Promise<boolean> { return new Promise<boolean>((resolve: any, reject: any) => { let folder: string = path.dirname(filePath); return fs.ensureDir(folder) .then(() => { fs.writeFile(filePath, data, (err: any) => { if (err) { reject(err); } else { resolve(true); } }); }) .catch((err: any) => { reject(err); }); }); } export async function deleteFile(fileAbsolutePath: string): Promise<boolean> { return new Promise<boolean>((resolve: any, reject: any) => { let filePath: string = path.join(fileAbsolutePath); fs.unlink(filePath, (err: any) => { if (err) { resolve(false); } else { resolve(true); } }); }); }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using SocialNetwork.DataAccess.Context; using SocialNetwork.DataAccess.Entities; using SocialNetwork.DataAccess.Repositories.Abstract; using System.Linq.Expressions; namespace SocialNetwork.DataAccess.Repositories.Concrete { public class GenericRepository<TEntity, TKey> : IGenericRepository<TEntity, TKey> where TEntity : BaseEntity<TKey> { protected readonly ILogger _logger; protected AppDbContext _context; protected DbSet<TEntity> _dbSet; public GenericRepository(ILogger logger, AppDbContext context) { _logger = logger; _context = context; _dbSet = context.Set<TEntity>(); } public virtual async Task<ICollection<TEntity>> GetAll() { return await _dbSet.AsNoTracking().ToListAsync(); } public virtual async Task<ICollection<TEntity>> FindBy(Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, object>>[] includes = null) { var query = _dbSet.AsNoTracking().Where(filter); if (includes != null) { foreach (var include in includes) { query = query.Include(include); } } return await query.ToListAsync(); } public virtual async Task<TEntity> FindOneBy(Expression<Func<TEntity, bool>> filter = null) { return await _dbSet.AsNoTracking().FirstOrDefaultAsync(filter); } public async Task<TEntity> FindOneBy(Expression<Func<TEntity, bool>> filter = null, Expression<Func<TEntity, object>>[] includes = null) { var query = _dbSet.AsNoTracking().Where(filter); foreach (var include in includes) { query = query.Include(include); } return await query.FirstOrDefaultAsync(); } public virtual async Task Add(TEntity entity) { await _dbSet.AddAsync(entity); } public virtual async Task AddRange(List<TEntity> entities) { await _dbSet.AddRangeAsync(entities); } public virtual async Task<TEntity> GetById(TKey id) { return await GetById(id, Array.Empty<Expression<Func<TEntity, object>>>()); } // No implement public virtual Task Update(TEntity entity) { throw new NotImplementedException(); } public virtual async Task Delete(TKey id) { var entity = await _dbSet.FindAsync(id); _dbSet.Remove(entity); } public virtual async Task<int> GetCount(Expression<Func<TEntity, bool>> filter = null) { var query = _dbSet.AsNoTracking(); if (filter != null) { query = query.Where(filter); } return await query.CountAsync(); } public virtual async Task<ICollection<TEntity>> GetPaged(int pageSize, int pageNumber, Expression<Func<TEntity, bool>> filter = null, Expression<Func<TEntity, object>> orderBy = null, bool isDesc = true) { return await GetPaged(pageSize, pageNumber, Array.Empty<Expression<Func<TEntity, object>>>(), filter, orderBy, isDesc); } public virtual async Task<ICollection<TEntity>> GetPaged(int pageSize, int pageNumber, Expression<Func<TEntity, object>>[] includes, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, object>> orderby, bool isDesc = true) { var query = _dbSet.AsNoTracking(); if (filter != null) { query = query.Where(filter); } foreach (var include in includes) { query = query.Include(include); } query = isDesc ? query.OrderByDescending(orderby) : query.OrderBy(orderby); return await query.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync(); } public IQueryable<TEntity> GetQueryable() { return _dbSet.AsQueryable(); } public async Task<TEntity> GetById(TKey id, Expression<Func<TEntity, object>>[] includes) { var query = _dbSet.AsNoTracking().Where(x => x.Id.Equals(id) && x.Status == 1); foreach (var include in includes) { query = query.Include(include); } return await query.FirstOrDefaultAsync(); } public virtual async Task<ICollection<TEntity>> GetCursorPaged(int pageSize, Expression<Func<TEntity, bool>> filter, bool getNext = true) { return await GetCursorPaged(pageSize, filter, Array.Empty<Expression<Func<TEntity, object>>>(), getNext); } public virtual async Task<ICollection<TEntity>> GetCursorPaged(int pageSize, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, object>>[] includes, bool getNext = true) { var query = _dbSet.AsNoTracking().Where(filter); foreach (var include in includes) { query = query.Include(include); } if (getNext) { return await query.OrderByDescending(x => x.CreatedAt).ThenByDescending(x => x.Id).Take(pageSize).ToListAsync(); } else { var result = await query.OrderBy(x => x.CreatedAt).ThenBy(x => x.Id).Take(pageSize).ToListAsync(); result.Reverse(); return result; } } public virtual async Task<ICollection<TEntity>> GetCursorPaged(int pageSize, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, object>> orderBy, bool getNext = true) { return await GetCursorPaged(pageSize, filter, orderBy, Array.Empty<Expression<Func<TEntity, object>>>(), getNext); } public virtual async Task<ICollection<TEntity>> GetCursorPaged(int pageSize, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, object>> orderBy, Expression<Func<TEntity, object>>[] includes, bool getNext = true) { var query = _dbSet.AsNoTracking().Where(filter); foreach (var include in includes) { query = query.Include(include); } if (getNext) { return await query.OrderByDescending(orderBy).ThenByDescending(x => x.Id).Take(pageSize).ToListAsync(); } else { var result = await query.OrderBy(orderBy).ThenBy(x => x.Id).Take(pageSize).ToListAsync(); result.Reverse(); return result; } } public async Task RestoreEntity(TKey id) { var entity = await _dbSet.FirstOrDefaultAsync(x => x.Id.Equals(id)); if (entity != null) { entity.Status = 1; } } } }
import { Component, OnInit } from '@angular/core'; import { ClientService} from '../client.service'; import { AnnouncementPost } from '../annocement_post'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { Brand } from '../brand'; import { Subject, Observable, merge, of, throwError } from 'rxjs'; import { Model } from '../model' import { debounceTime, distinctUntilChanged, switchMap, startWith, tap, map, catchError } from 'rxjs/operators'; @Component({ selector: 'app-add-annoucement', templateUrl: './add-annoucement.component.html', styleUrls: ['./add-annoucement.component.sass'] }) export class AddAnnoucementComponent implements OnInit { annoucementPost: AnnouncementPost[] = []; getBrands: Brand[]; getModels: Model[]; model$: Observable<Model[]>; brands: Brand[] = []; private searchId = new Subject<string>(); constructor(private clientService: ClientService) { } brandControl = new FormControl(null, Validators.required); annoucementGroup = new FormGroup({ modelId: new FormControl(null, Validators.required), colorId: new FormControl(null, Validators.required), year: new FormControl(2019,Validators.required) }); listYear: number[] = []; get modelId(): any{ return this.annoucementGroup.get('modelId')} get colorId(): any{return this.annoucementGroup.get('colorId')} get year(): any{return this.annoucementGroup.get('year')} searchModelsId(id: string): void{ console.log(typeof id); this.searchId.next(id); } ngOnInit() { this.dateGenerate(); this.model$ = merge(this.searchId, this.getBrand()).pipe( debounceTime(300), map(_ => { if(_.constructor === Array){ this.brands = _ as Brand[]; this.brandControl.setValue(this.brands[0].id); return this.brands[0].id; } return _; }), switchMap((id: string) =>{ return this.clientService.searchByBrandId(id); }), tap(_ => { if(_[0]){ this.annoucementGroup.controls.modelId.setValue(_[0].id) } }), catchError(_ => { return throwError(_) }) ); this.brandControl.valueChanges.subscribe((value)=> this.searchModelsId(value)) this.annoucementGroup.valueChanges.subscribe((value) => console.log(value)); } getModelsByBrand(id: number): void{ this.clientService.getModelsByBrand(id) .subscribe(getModels => this.getModels = getModels) } add(model_id: number, color_id: number, year: number): void{ this.clientService.addAnnoucement({model_id, color_id, year} as AnnouncementPost) .subscribe(annoucement => { console.log(this.annoucementPost); this.annoucementPost.push(annoucement); }) } dateGenerate(){ let now = new Date().getFullYear(); for( now; now > 1950; now--){ this.listYear.push(now); } console.log(this.listYear); } getBrand(){ return this.clientService.getBrand(); } onSubmitAnnoucement(){ this.add(this.modelId.value, this.colorId.value, this.year.value); } }
<div class="row"> <div class="col"> <h1>*ngIf</h1> <div *ngIf="mostrar" class="card text-white bg-dark mb-3" style="width:100;%"> <div class="card-header">Card</div> <div class="card-body"> <h5 class="card-title">{{frase.autor}}</h5> <p class="card-text">{{frase.mensaje}}</p> </div> </div> <button (click)="mostrar = !mostrar" class="btn btn-outline-dark btn-block"> Mostrar/Ocultar </button> </div> <div class="col"> <h1>*ngFor</h1> <ul class="list-group" style="width:100%;"> <li *ngFor="let personaje of personajes;let i=index" class="list-group-item"> {{i+1}}. {{personaje}} </li> </ul> </div> </div> <div class="row"> <label class="checkbox-label" for="articleTypes-FLA"> <input type="checkbox" id="articleTypes-FLA" name="Research articles" class="checkbox-input checkbox-small checkbox-label-indent"> <span class="checkbox-check checkbox-small checkbox-label-indent"></span> <span class="checkbox-label-value checkbox-small checkbox-label-indent">Prueba de checkbox</span> </label> </div>
// // ScoreViewer.swift // ScoreViewer // // Created by Leonore Yardimli on 2021/12/17. // import Foundation import SwiftUI import WebKit struct ScoreViewer: UIViewRepresentable { var url: URL var scoreXML: String func makeUIView(context: UIViewRepresentableContext<ScoreViewer>) -> WKWebView { let preferences = WKPreferences() preferences.javaScriptEnabled = true let configuration = WKWebViewConfiguration() configuration.preferences = preferences let userContentController = WKUserContentController() userContentController.add(context.coordinator, name:"observer") configuration.userContentController = userContentController let webView = WKWebView(frame: .zero, configuration: configuration) webView.navigationDelegate = context.coordinator DispatchQueue.main.async { let request = NSURLRequest(url: url) webView.load(request as URLRequest) } return webView } func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<ScoreViewer>) { } func makeCoordinator() -> Coordinator { Coordinator(self) } typealias UIViewType = WKWebView class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler { var control: ScoreViewer init(_ control: ScoreViewer) { self.control = control } func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { //showAlert(body: message.body) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { //let name = UIDevice.current.name //let systemVersion = UIDevice.current.systemVersion //let javaScriptString = "device('\(name)', '\(systemVersion)');" //webView.evaluateJavaScript(javaScriptString, completionHandler: nil) webView.evaluateJavaScript("load_score_view(\"\(control.scoreXML)\");", completionHandler: nil) } /*func showAlert(body: Any) { let content = "\(body)" let alertController = UIAlertController(title: "Trigger", message: content, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default)) let window = UIApplication.shared.windows.first window?.rootViewController?.present(alertController, animated: true) }*/ } }
/** * Copyright (C) 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.dashboard.ui.config.formatters; import org.jboss.dashboard.ui.config.ConfigurationTree; import org.jboss.dashboard.ui.config.ConfigurationTreeStatus; import org.jboss.dashboard.ui.taglib.formatter.Formatter; import org.jboss.dashboard.ui.taglib.formatter.FormatterException; import org.jboss.dashboard.ui.config.Tree; import org.jboss.dashboard.ui.config.TreeNode; import org.jboss.dashboard.ui.config.TreeStatus; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Iterator; import java.util.List; public class TreeNodeFormatter extends Formatter { @Inject private Logger log; @Inject private ConfigurationTreeStatus treeStatus; @Inject private ConfigurationTree tree; public TreeNodeFormatter() { } public TreeStatus getTreeStatus() { return treeStatus; } public Tree getTree() { return tree; } public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws FormatterException { try { int nodeIndex = 0; TreeNode an = (TreeNode) getParameter("treenode"); renderFragment("nodeTab"); if (an != null) { if ((treeStatus.isExpanded(an))) { List children = an.getChildren(); if (children != null) { Iterator i = children.iterator(); while (i.hasNext()) { TreeNode subNode = (TreeNode) i.next(); if (treeStatus.isExpanded(subNode)) { if (i.hasNext()) { setAttribute("expand_path", "branch_contract.gif"); setAttribute("line_path", "line_expand.gif"); } else { setAttribute("expand_path", "branch_contract_01.gif"); setAttribute("line_path", "spacer.png"); } setAttribute("expand_action", "collapse-node"); } else { if (i.hasNext()) { setAttribute("expand_path", "branch_expand_02.gif"); setAttribute("line_path", "line_expand.gif"); } else { setAttribute("expand_path", "branch_expand_01.gif"); setAttribute("line_path", "spacer.png"); } setAttribute("expand_action", "expand-node"); } if (i.hasNext()) { setAttribute("line_path", "line_expand.gif"); setAttribute("branchPath", "branch_02.gif"); } else { setAttribute("branchPath", "branch_01.gif"); setAttribute("line_path", "spacer.png"); } setAttribute("isEditable", subNode.isEditable()); setAttribute("path_Node", subNode.getPath()); setAttribute("id_Node", subNode.getId()); setAttribute("name_Node", StringEscapeUtils.ESCAPE_HTML4.translate(StringUtils.defaultString(subNode.getName(getLocale())))); setAttribute("icon_Node", subNode.getIconId()); setAttribute("iconNodePath", subNode.getIconCategory()); setAttribute("parent_Node", subNode.getParent()); setAttribute("node", subNode); setAttribute("level_Node", subNode.getLevel()); setAttribute("isEdited", getTreeStatus().isEdited(subNode)); setAttribute("nodeIndex",nodeIndex++); renderFragment("subNode"); } } } } } catch (Exception e) { // Error fragment. renderFragment("error"); log.error("Cannot render node.", e); } } }
"use client"; import React, { useState, useEffect } from "react"; import { useUser } from "@auth0/nextjs-auth0/client"; import CommentView from "./CommentView"; const CommentSection = ({ postId }) => { //console.log("userName in CommentSection:", userName); const { user } = useUser(); const [comment, setComment] = useState(""); const [comments, setComments] = useState([]); const [userData, setUserData] = useState({}); const [userName, setUserName] = useState(""); const [userId, setUserId] = useState(""); useEffect(() => { if (!user) return; const fetchUserName = async () => { setUserId(user.sub); try { const response = await fetch(`/api/users/${userId}`); const data = await response.json(); setUserName(data.userName); } catch (error) { console.error("Error fetching userName:", error); } }; fetchUserName(); }, [user]); const handleSubmit = async (e) => { e.preventDefault(); //const userId = userData.userId; //const tripId = tripId; if (!comment.trim()) return; const newComment = { userId, comment, postId, userName, }; const response = await fetch(`/api/comments/post/${postId}`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(newComment), }); if (!response.ok) { console.error("Failed to submit comment"); return; } const data = await response.json(); setComments([...comments, data]); setComment(""); console.log("Comment submitted"); }; const deleteComment = async (uuid) => { await fetch(`/api/comments/${uuid}`, { method: "DELETE", }); setComments(comments.filter((comment) => comment.uuid !== uuid)); }; useEffect(() => { const fetchComments = async () => { try { const response = await fetch(`/api/comments/post/${postId}`); const data = await response.json(); if (!response.ok) { console.error("Failed to fetch comments"); return; } setComments(data); } catch (error) { console.error("Error fetching comments:", error); } }; fetchComments(); }, [postId]); return ( <div className="flex-initial flex flex-col items-center justify-center border border-white p-4 shadow-lg rounded-lg"> <h3 className="text-xl font-semibold mb-2">Comments Section</h3> <form className="w-full max-w-xl flex flex-col" onSubmit={handleSubmit}> <div className="flex flex-col mb-4 md:flex-row"> <textarea className="textarea textarea-bordered flex-auto mr-4" placeholder="Type your comment here..." value={comment} onChange={(e) => setComment(e.target.value)} style={{ height: "2.5rem", resize: "none" }} ></textarea> <button type="submit" className="btn mt-4 md:mt-0" style={{ backgroundColor: "rgb(33,138,255)", color: "white", }} > Submit </button> </div> </form> <div className="w-full max-w-xl" style={{ paddingBottom: "5rem" }}> {comments.map((comment) => ( <CommentView key={comment.uuid} deleteComment={deleteComment} {...comment} /> ))} </div> </div> ); }; export default CommentSection;
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/ash/services/bluetooth_config/device_name_manager_impl.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "device/bluetooth/chromeos/bluetooth_utils.h" #include "device/bluetooth/floss/floss_features.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h" #include "testing/gtest/include/gtest/gtest.h" namespace ash::bluetooth_config { namespace { using NiceMockDevice = std::unique_ptr<testing::NiceMock<device::MockBluetoothDevice>>; const uint32_t kTestBluetoothClass = 1337u; const char kTestBluetoothName[] = "testName"; const char kTestIdBluez[] = "/org/bluez/hci0/dev_7C_96_D2_8B_FB_17"; const char kTestIdFloss0[] = "7C:96:D2:8B:FB:17"; const char kTestIdFloss1[] = "C7:69:2D:B8:BF:71"; const char kTestNickname[] = "nickname"; class FakeObserver : public DeviceNameManager::Observer { public: FakeObserver() = default; ~FakeObserver() override = default; size_t num_device_nickname_changed_calls() const { return num_device_nickname_changed_calls_; } const std::string& last_device_id_nickname_changed() const { return last_device_id_nickname_changed_; } const std::optional<std::string>& last_device_nickname_changed() const { return last_device_nickname_changed_; } private: // DeviceNameManager::Observer: void OnDeviceNicknameChanged( const std::string& device_id, const std::optional<std::string>& nickname) override { ++num_device_nickname_changed_calls_; last_device_id_nickname_changed_ = device_id; last_device_nickname_changed_ = nickname; } size_t num_device_nickname_changed_calls_ = 0u; std::string last_device_id_nickname_changed_; std::optional<std::string> last_device_nickname_changed_; }; } // namespace class DeviceNameManagerImplTest : public testing::Test { protected: DeviceNameManagerImplTest() = default; DeviceNameManagerImplTest(const DeviceNameManagerImplTest&) = delete; DeviceNameManagerImplTest& operator=(const DeviceNameManagerImplTest&) = delete; ~DeviceNameManagerImplTest() override = default; // testing::Test: void SetUp() override { DeviceNameManagerImpl::RegisterLocalStatePrefs( test_pref_service_.registry()); mock_adapter_ = base::MakeRefCounted<testing::NiceMock<device::MockBluetoothAdapter>>(); ON_CALL(*mock_adapter_, GetDevices()) .WillByDefault( testing::Invoke(this, &DeviceNameManagerImplTest::GetMockDevices)); } std::unique_ptr<DeviceNameManagerImpl> CreateDeviceNameManager() { auto device_name_manager = std::make_unique<DeviceNameManagerImpl>(mock_adapter_); device_name_manager->AddObserver(&fake_observer_); device_name_manager->SetPrefs(&test_pref_service_); return device_name_manager; } void AddDevice(std::string* id_out) { // We use the number of devices created in this test as the address. std::string address = base::NumberToString(num_devices_created_); ++num_devices_created_; // Mock devices have their ID set to "${address}-Identifier". *id_out = base::StrCat({address, "-Identifier"}); auto mock_device = std::make_unique<testing::NiceMock<device::MockBluetoothDevice>>( mock_adapter_.get(), kTestBluetoothClass, kTestBluetoothName, address, /*paired=*/false, /*connected=*/false); mock_devices_.push_back(std::move(mock_device)); } size_t GetNumDeviceNicknameObserverEvents() const { return fake_observer_.num_device_nickname_changed_calls(); } const std::string& GetLastDeviceIdNicknameChanged() const { return fake_observer_.last_device_id_nickname_changed(); } const std::optional<std::string>& GetLastDeviceNicknameChanged() const { return fake_observer_.last_device_nickname_changed(); } sync_preferences::TestingPrefServiceSyncable* local_state() { return &test_pref_service_; } base::HistogramTester histogram_tester; private: std::vector<raw_ptr<const device::BluetoothDevice, VectorExperimental>> GetMockDevices() { std::vector<raw_ptr<const device::BluetoothDevice, VectorExperimental>> devices; for (auto& device : mock_devices_) devices.push_back(device.get()); return devices; } base::test::TaskEnvironment task_environment_; std::vector<NiceMockDevice> mock_devices_; size_t num_devices_created_ = 0u; scoped_refptr<testing::NiceMock<device::MockBluetoothAdapter>> mock_adapter_; sync_preferences::TestingPrefServiceSyncable test_pref_service_; FakeObserver fake_observer_; }; TEST_F(DeviceNameManagerImplTest, GetThenSetValidThenSetInvalidFlossDisabled) { base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(floss::features::kFlossEnabled); EXPECT_FALSE(floss::features::IsFlossEnabled()); std::string device_id; AddDevice(&device_id); std::unique_ptr<DeviceNameManagerImpl> manager = CreateDeviceNameManager(); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); manager->SetDeviceNickname(device_id, kTestNickname); EXPECT_EQ(manager->GetDeviceNickname(device_id), kTestNickname); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 1u); EXPECT_EQ(GetLastDeviceIdNicknameChanged(), device_id); EXPECT_EQ(GetLastDeviceNicknameChanged(), kTestNickname); histogram_tester.ExpectBucketCount( "Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kInvalidNicknameFormat, 0); histogram_tester.ExpectBucketCount("Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kSuccess, 1); // Set an empty nickname, this should fail and the nickname should be // unchanged. manager->SetDeviceNickname(device_id, ""); EXPECT_EQ(manager->GetDeviceNickname(device_id), kTestNickname); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 1u); histogram_tester.ExpectBucketCount( "Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kInvalidNicknameFormat, 1); histogram_tester.ExpectBucketCount("Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kSuccess, 1); // Set nickname above character limit, this should also fail and the nickname // should be unchanged. manager->SetDeviceNickname(device_id, "123456789012345678901234567890123"); EXPECT_EQ(manager->GetDeviceNickname(device_id), kTestNickname); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 1u); histogram_tester.ExpectBucketCount( "Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kInvalidNicknameFormat, 2); histogram_tester.ExpectBucketCount("Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kSuccess, 1); } TEST_F(DeviceNameManagerImplTest, NicknameIsPersistedBetweenManagerInstancesFlossDisabled) { base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(floss::features::kFlossEnabled); EXPECT_FALSE(floss::features::IsFlossEnabled()); std::string device_id; AddDevice(&device_id); std::unique_ptr<DeviceNameManagerImpl> manager = CreateDeviceNameManager(); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); manager->SetDeviceNickname(device_id, kTestNickname); EXPECT_EQ(manager->GetDeviceNickname(device_id), kTestNickname); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 1u); EXPECT_EQ(GetLastDeviceIdNicknameChanged(), device_id); EXPECT_EQ(GetLastDeviceNicknameChanged(), kTestNickname); histogram_tester.ExpectBucketCount( "Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kInvalidNicknameFormat, 0); histogram_tester.ExpectBucketCount("Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kSuccess, 1); // Create a new manager and destroy the old one. manager = CreateDeviceNameManager(); EXPECT_EQ(manager->GetDeviceNickname(device_id), kTestNickname); } TEST_F(DeviceNameManagerImplTest, SetNicknameDeviceNotFoundFlossDisabled) { base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(floss::features::kFlossEnabled); EXPECT_FALSE(floss::features::IsFlossEnabled()); const std::string device_id = "device_id"; std::unique_ptr<DeviceNameManagerImpl> manager = CreateDeviceNameManager(); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); // Setting the nickname of an unknown device should fail. manager->SetDeviceNickname(device_id, kTestNickname); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 0u); histogram_tester.ExpectBucketCount("Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kDeviceNotFound, 1); histogram_tester.ExpectBucketCount("Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kSuccess, 0); } TEST_F(DeviceNameManagerImplTest, RemoveThenSetThenRemoveFlossDisabled) { base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(floss::features::kFlossEnabled); EXPECT_FALSE(floss::features::IsFlossEnabled()); std::string device_id; AddDevice(&device_id); std::unique_ptr<DeviceNameManagerImpl> manager = CreateDeviceNameManager(); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); // Nothing should happen when removing a nickname that doesn't exist. manager->RemoveDeviceNickname(device_id); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 0u); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); manager->SetDeviceNickname(device_id, kTestNickname); EXPECT_EQ(manager->GetDeviceNickname(device_id), kTestNickname); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 1u); EXPECT_EQ(GetLastDeviceIdNicknameChanged(), device_id); EXPECT_EQ(GetLastDeviceNicknameChanged(), kTestNickname); manager->RemoveDeviceNickname(device_id); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 2u); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); EXPECT_EQ(GetLastDeviceIdNicknameChanged(), device_id); EXPECT_EQ(GetLastDeviceNicknameChanged(), std::nullopt); // Create a new manager and destroy the old one. manager = CreateDeviceNameManager(); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); } TEST_F(DeviceNameManagerImplTest, GetThenSetValidThenSetInvalidFlossEnabled) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(floss::features::kFlossEnabled); EXPECT_TRUE(floss::features::IsFlossEnabled()); std::string device_id; AddDevice(&device_id); std::unique_ptr<DeviceNameManagerImpl> manager = CreateDeviceNameManager(); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); manager->SetDeviceNickname(device_id, kTestNickname); EXPECT_EQ(manager->GetDeviceNickname(device_id), kTestNickname); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 1u); EXPECT_EQ(GetLastDeviceIdNicknameChanged(), device_id); EXPECT_EQ(GetLastDeviceNicknameChanged(), kTestNickname); histogram_tester.ExpectBucketCount( "Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kInvalidNicknameFormat, 0); histogram_tester.ExpectBucketCount("Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kSuccess, 1); // Set an empty nickname, this should fail and the nickname should be // unchanged. manager->SetDeviceNickname(device_id, ""); EXPECT_EQ(manager->GetDeviceNickname(device_id), kTestNickname); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 1u); histogram_tester.ExpectBucketCount( "Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kInvalidNicknameFormat, 1); histogram_tester.ExpectBucketCount("Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kSuccess, 1); // Set nickname above character limit, this should also fail and the nickname // should be unchanged. manager->SetDeviceNickname(device_id, "123456789012345678901234567890123"); EXPECT_EQ(manager->GetDeviceNickname(device_id), kTestNickname); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 1u); histogram_tester.ExpectBucketCount( "Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kInvalidNicknameFormat, 2); histogram_tester.ExpectBucketCount("Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kSuccess, 1); } TEST_F(DeviceNameManagerImplTest, NicknameIsPersistedBetweenManagerInstancesFlossEnabled) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(floss::features::kFlossEnabled); EXPECT_TRUE(floss::features::IsFlossEnabled()); std::string device_id; AddDevice(&device_id); std::unique_ptr<DeviceNameManagerImpl> manager = CreateDeviceNameManager(); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); manager->SetDeviceNickname(device_id, kTestNickname); EXPECT_EQ(manager->GetDeviceNickname(device_id), kTestNickname); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 1u); EXPECT_EQ(GetLastDeviceIdNicknameChanged(), device_id); EXPECT_EQ(GetLastDeviceNicknameChanged(), kTestNickname); histogram_tester.ExpectBucketCount( "Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kInvalidNicknameFormat, 0); histogram_tester.ExpectBucketCount("Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kSuccess, 1); // Create a new manager and destroy the old one. manager = CreateDeviceNameManager(); EXPECT_EQ(manager->GetDeviceNickname(device_id), kTestNickname); } TEST_F(DeviceNameManagerImplTest, SetNicknameDeviceNotFoundFlossEnabled) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(floss::features::kFlossEnabled); EXPECT_TRUE(floss::features::IsFlossEnabled()); const std::string device_id = "device_id"; std::unique_ptr<DeviceNameManagerImpl> manager = CreateDeviceNameManager(); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); // Setting the nickname of an unknown device should fail. manager->SetDeviceNickname(device_id, kTestNickname); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 0u); histogram_tester.ExpectBucketCount("Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kDeviceNotFound, 1); histogram_tester.ExpectBucketCount("Bluetooth.ChromeOS.SetNickname.Result", device::SetNicknameResult::kSuccess, 0); } TEST_F(DeviceNameManagerImplTest, RemoveThenSetThenRemoveFlossEnabled) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(floss::features::kFlossEnabled); EXPECT_TRUE(floss::features::IsFlossEnabled()); std::string device_id; AddDevice(&device_id); std::unique_ptr<DeviceNameManagerImpl> manager = CreateDeviceNameManager(); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); // Nothing should happen when removing a nickname that doesn't exist. manager->RemoveDeviceNickname(device_id); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 0u); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); manager->SetDeviceNickname(device_id, kTestNickname); EXPECT_EQ(manager->GetDeviceNickname(device_id), kTestNickname); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 1u); EXPECT_EQ(GetLastDeviceIdNicknameChanged(), device_id); EXPECT_EQ(GetLastDeviceNicknameChanged(), kTestNickname); manager->RemoveDeviceNickname(device_id); EXPECT_EQ(GetNumDeviceNicknameObserverEvents(), 2u); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); EXPECT_EQ(GetLastDeviceIdNicknameChanged(), device_id); EXPECT_EQ(GetLastDeviceNicknameChanged(), std::nullopt); // Create a new manager and destroy the old one. manager = CreateDeviceNameManager(); EXPECT_FALSE(manager->GetDeviceNickname(device_id)); } TEST_F(DeviceNameManagerImplTest, Migration_DisablingClearsPrefs) { base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(floss::features::kFlossEnabled); EXPECT_FALSE(floss::features::IsFlossEnabled()); // Set the pref to some arbitrary value since we just want to confirm it will // be cleared when the feature flag is disabled. local_state()->Set(DeviceNameManager::kDeviceIdToNicknameMapPrefName, base::Value(base::Value::Dict())); EXPECT_TRUE(local_state()->HasPrefPath( DeviceNameManager::kDeviceIdToNicknameMapPrefName)); CreateDeviceNameManager(); EXPECT_FALSE(local_state()->HasPrefPath( DeviceNameManager::kDeviceIdToNicknameMapPrefName)); } TEST_F(DeviceNameManagerImplTest, Migration_MigrationHappensOnce) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(floss::features::kFlossEnabled); EXPECT_TRUE(floss::features::IsFlossEnabled()); // The value that we will set the existing/pre-migration prefs to. auto existing_prefs = base::Value::Dict().Set(kTestIdBluez, kTestNickname); local_state()->Set(DeviceNameManager::kDeviceIdToNicknameMapPrefNameLegacy, base::Value(existing_prefs.Clone())); // Set the pref to some arbitrary value since we just want to confirm that if // the pref has a value we will assume that we have already performed the // migration and will not attempt another migration. base::Value::Dict new_prefs; local_state()->Set(DeviceNameManager::kDeviceIdToNicknameMapPrefName, base::Value(new_prefs.Clone())); EXPECT_TRUE(local_state()->HasPrefPath( DeviceNameManager::kDeviceIdToNicknameMapPrefName)); CreateDeviceNameManager(); const base::Value::Dict& migrated_prefs = local_state()->GetDict(DeviceNameManager::kDeviceIdToNicknameMapPrefName); EXPECT_EQ(new_prefs, migrated_prefs); } TEST_F(DeviceNameManagerImplTest, Migration) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(floss::features::kFlossEnabled); EXPECT_TRUE(floss::features::IsFlossEnabled()); // The value that we expect to be migrated. auto existing_prefs = base::Value::Dict() .Set(kTestIdBluez, kTestNickname) .Set(kTestIdFloss1, kTestNickname); local_state()->Set(DeviceNameManager::kDeviceIdToNicknameMapPrefNameLegacy, base::Value(existing_prefs.Clone())); EXPECT_FALSE(local_state()->HasPrefPath( DeviceNameManager::kDeviceIdToNicknameMapPrefName)); CreateDeviceNameManager(); auto migrated_prefs = base::Value::Dict() .Set(kTestIdFloss0, kTestNickname) .Set(kTestIdFloss1, kTestNickname); EXPECT_EQ(migrated_prefs, local_state()->GetDict( DeviceNameManager::kDeviceIdToNicknameMapPrefName)); } } // namespace ash::bluetooth_config
package com.wanted.budget.guardian.app.web.controller.auth; import com.wanted.budget.guardian.app.domain.auth.AuthService; import com.wanted.budget.guardian.app.web.dto.auth.AccessTokenResponseDto; import com.wanted.budget.guardian.app.web.dto.auth.LoginRequestDto; import com.wanted.budget.guardian.app.web.dto.auth.RefreshTokenRequestDto; import com.wanted.budget.guardian.app.web.dto.auth.SignUpRequestDto; import com.wanted.budget.guardian.app.web.dto.auth.TokenResponseDto; import com.wanted.budget.guardian.app.web.dto.member.MemberIdResponseDto; import com.wanted.budget.guardian.app.web.path.ApiPath; import com.wanted.budget.guardian.common.config.security.context.LoginMember; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @Tag(name = "인증") @RequiredArgsConstructor @RestController public class AuthController { private final AuthService authService; @Operation(summary = "멤버 회원가입") @PostMapping(ApiPath.SIGNUP) public ResponseEntity<MemberIdResponseDto> signup( @Valid @RequestBody SignUpRequestDto body ) { return ResponseEntity.ok(authService.signUp(body)); } @Operation(summary = "멤버 로그인") @PostMapping(ApiPath.LOGIN) public ResponseEntity<TokenResponseDto> login( @Valid @RequestBody LoginRequestDto body ) { return ResponseEntity.ok(authService.generateAccessAndRefreshToken(body)); } @Operation(summary = "액세스토큰 재발급") @PostMapping(ApiPath.REFRESH_TOKEN) public ResponseEntity<AccessTokenResponseDto> generateAccessToken( @Valid @RequestBody RefreshTokenRequestDto body ) { return ResponseEntity.ok(authService.refreshAccessToken(body)); } @Operation(summary = "로그아웃") @DeleteMapping(ApiPath.LOGOUT) public ResponseEntity<Void> logout( @Valid @RequestBody RefreshTokenRequestDto body ) { authService.expirationRefreshToken(body); return ResponseEntity.ok().build(); } @Operation(summary = "토큰 유효성 확인") @GetMapping(ApiPath.VALIDATE_TOKEN) public ResponseEntity<Void> validateToken( @AuthenticationPrincipal LoginMember loginMember ) { return ResponseEntity.ok().build(); } }
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:ktr/models/user_model_one.dart'; import 'package:ktr/providers/user_provider.dart'; import 'package:ktr/views/input_location.dart'; class AddContentPage extends ConsumerStatefulWidget { const AddContentPage({super.key}); @override ConsumerState<AddContentPage> createState() => _AddContentPageState(); } class _AddContentPageState extends ConsumerState<AddContentPage> { final _titleController = TextEditingController(); final _userNameController = TextEditingController(); final _userEmailController = TextEditingController(); PlaceLocationOne? _location; @override void dispose() { _titleController.dispose(); _userNameController.dispose(); _userEmailController.dispose(); super.dispose(); } void _saveContent() { final enteredTitle = _titleController.text.trim(); final userNameController = _userNameController.text.trim(); final userEmailController = _userEmailController.text.trim(); if (enteredTitle.isEmpty || userNameController.isEmpty || _location == null || userEmailController.isEmpty) { return; } ref.read(userPlaceProvider.notifier).addUser( enteredTitle, userNameController, userEmailController, _location!); Navigator.of(context).pop(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Title"), ), floatingActionButton: FloatingActionButton( onPressed: () { _saveContent(); }, child: const Icon(Icons.add), ), body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(20), child: Column( children: [ TextField( onTapOutside: (event) { FocusManager.instance.primaryFocus!.unfocus(); }, controller: _titleController, decoration: const InputDecoration(labelText: "Title"), ), TextField( onTapOutside: (event) { FocusManager.instance.primaryFocus!.unfocus(); }, controller: _userNameController, decoration: const InputDecoration(labelText: "Name"), ), TextField( onTapOutside: (event) { FocusManager.instance.primaryFocus!.unfocus(); }, controller: _userEmailController, decoration: const InputDecoration(labelText: "Email"), ), const SizedBox( height: 10, ), const SizedBox( height: 10, ), //location Input InputLocation( onLocationPicked: (pickedLocation) { _location = pickedLocation; }, ) ], ), ), ), ); } }
-- PART 1 -- FOREIGN KEY constraints ALTER TABLE Admins ADD CONSTRAINT FK_Admins_Users FOREIGN KEY (userID) REFERENCES Users(userID); ALTER TABLE Author ADD CONSTRAINT FK_Author_Books FOREIGN KEY (bookID) REFERENCES Books(bookID); ALTER TABLE Books ADD CONSTRAINT FK_Books_Edition FOREIGN KEY (bookID) REFERENCES Books(bookID); ALTER TABLE Borrowing ADD CONSTRAINT FK_Borrowing_Resources FOREIGN KEY (physicalID) REFERENCES Resources(physicalID); ALTER TABLE Borrowing ADD CONSTRAINT FK_Borrowing_Users FOREIGN KEY (userID) REFERENCES Users(userID); ALTER TABLE Edition ADD CONSTRAINT FK_Edition_Books FOREIGN KEY (bookID) REFERENCES Books(bookID); ALTER TABLE Fines ADD CONSTRAINT FK_Fines_Borrowing FOREIGN KEY (borrowingID) REFERENCES Borrowing(borrowingID); ALTER TABLE Genre ADD CONSTRAINT FK_Genre_Books FOREIGN KEY (bookID) REFERENCES Books(bookID); ALTER TABLE Language ADD CONSTRAINT FK_Language_Books FOREIGN KEY (bookID) REFERENCES Books(bookID); ALTER TABLE Prequels ADD CONSTRAINT FK_Book_Prequels_Books FOREIGN KEY (bookID) REFERENCES Books(bookID); -- different naming convention ALTER TABLE Prequels ADD CONSTRAINT FK_Prequel_Prequels_Books FOREIGN KEY (prequelID) REFERENCES Books(bookID); -- different naming convention ALTER TABLE Resources ADD CONSTRAINT FK_Resources_Books FOREIGN KEY (bookID) REFERENCES Books(bookID); ALTER TABLE Students ADD CONSTRAINT FK_Students_Users FOREIGN KEY (userID) REFERENCES Users(userID); ALTER TABLE Transactions ADD CONSTRAINT FK_Transactions_Borrowing FOREIGN KEY (borrowingID) REFERENCES Borrowing(borrowingID); -- Add SET NOT NULL constraints ALTER TABLE Books ALTER COLUMN title SET NOT NULL; ALTER TABLE Books ALTER COLUMN pages SET NOT NULL; ALTER TABLE Edition ALTER COLUMN ISBN SET NOT NULL; ALTER TABLE Author ALTER COLUMN author SET NOT NULL; ALTER TABLE Genre ALTER COLUMN genre SET NOT NULL; ALTER TABLE Language ALTER COLUMN language SET NOT NULL; ALTER TABLE Users ALTER COLUMN name SET NOT NULL; ALTER TABLE Users ALTER COLUMN address SET NOT NULL; ALTER TABLE Users ALTER COLUMN email SET NOT NULL; ALTER TABLE Students ALTER COLUMN program SET NOT NULL; ALTER TABLE Admins ALTER COLUMN department SET NOT NULL; ALTER TABLE Admins ALTER COLUMN phoneNumber SET NOT NULL; ALTER TABLE Fines ALTER COLUMN amount SET NOT NULL; ALTER TABLE Transactions ALTER COLUMN paymentMethod SET NOT NULL; ALTER TABLE Transactions ALTER COLUMN DoP SET NOT NULL; -- Add check constraints ALTER TABLE Fines ADD CONSTRAINT CK_Fines_amount CHECK ( amount > 0 ); ALTER TABLE Books ADD CONSTRAINT CK_Books_pages CHECK ( pages > 0 ); ALTER TABLE Edition ADD CONSTRAINT CK_Edition_edition_positive CHECK ( edition > 0 ); ALTER TABLE Borrowing ADD CONSTRAINT CK_Borrowing_dor_dob CHECK ( dor >= dob ); ALTER TABLE users ADD CONSTRAINT CK_Users_email CHECK ( email LIKE '%@kth.se' ); -- PART 2 -- countries and borders with cte as( select name, count from( select border_count.name, count(border_count.name) from( select country.name from country join borders on borders.country1 = country.code or borders.country2 = country.code ) as border_count group by border_count.name ) as t1) select cte.name, cte.count from cte where cte.count = (select min(cte.count) from cte); -- most spoken language select people.language, round(sum(people.population * people.percentage * 0.01)) as numberspeaker from( select country.population, spoken.percentage, spoken.language from country join spoken on spoken.country = country.code where spoken.percentage IS NOT NULL ) as people group by people.Language order by numberspeaker desc; -- gdp ratio between bordering countries select * from( select c1.country1, c1.gdp1, c1.country2, gdp as gdp2, round(c1.gdp1/gdp) as ratio from( select borders.country1, economy.gdp as gdp1, borders.country2 from Borders join Economy on borders.country1 = economy.country ) as C1 join economy on c1.country2 = economy.country union all select c1.country1, c1.gdp1, c1.country2, gdp as gdp2, round(gdp/c1.gdp1) as ratio from( select borders.country1, economy.gdp as gdp1, borders.country2 from Borders join Economy on borders.country1 = economy.country ) as C1 join economy on c1.country2 = economy.country ) as C2 where ratio is not null order by ratio desc;
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; public class PlayerController : MonoBehaviour { private Rigidbody2D rb; private SpriteRenderer spriteRenderer; private PhysicsCheck physicsCheck; public PlayerInputControl inputControl; public Vector2 inputDirection; private CapsuleCollider2D coll; private PlayerAnimation playerAnimation; [Header("基本参数")] public float speed; private float runSpeed; private float walkSpeed => speed / 2.5f; public float jumpForce; public float hurtForce; private Vector2 originalOffset; private Vector2 originalSize; [Header("物理材质")] public PhysicsMaterial2D normal; public PhysicsMaterial2D wall; [Header("状态")] public bool isCrouch; public bool isHurt; public bool isDead; public bool isAttack; public bool isDefence; private void Awake() { rb = GetComponent<Rigidbody2D>(); physicsCheck = GetComponent<PhysicsCheck>(); spriteRenderer = GetComponent<SpriteRenderer>(); coll = GetComponent<CapsuleCollider2D>(); playerAnimation = GetComponent<PlayerAnimation>(); originalOffset = coll.offset; originalSize = coll.size; inputControl = new PlayerInputControl(); inputControl.Gameplay.Jump.started += Jump; #region 强制走路 runSpeed = speed; inputControl.Gameplay.WalkButton.performed += ctx =>{ if (physicsCheck.isGround) speed = walkSpeed; }; inputControl.Gameplay.WalkButton.canceled += ctx =>{ if (physicsCheck.isGround) speed = runSpeed; }; #endregion; inputControl.Gameplay.Attack.started += PlayerAttack; inputControl.Gameplay.Defence.performed += ctx =>{ isDefence = true; }; inputControl.Gameplay.Defence.canceled += ctx =>{ isDefence = false; }; } private void OnEnable() { inputControl.Enable(); } private void OnDisable() { inputControl.Disable(); } private void Update() { inputDirection = inputControl.Gameplay.Move.ReadValue<Vector2>(); CheckState(); } private void FixedUpdate() { if (!isHurt && !isAttack && !isDefence) Move(); } public void Move() { if (!isCrouch) rb.velocity = new Vector2(inputDirection.x*speed*Time.deltaTime, rb.velocity.y); float faceDir = transform.localScale.x; if (inputDirection.x > 0 && faceDir < 0) faceDir *= -1; //spriteRenderer.flipX = false; if (inputDirection.x < 0 && faceDir > 0) faceDir *= -1; //spriteRenderer.flipX = true; transform.localScale = new Vector3(faceDir,1,1); isCrouch = inputDirection.y < -0.5f && physicsCheck.isGround; if (isCrouch){ coll.offset = new Vector2(-0.12f, 0.8f); coll.size = new Vector2(0.75f, 1.6f); }else{ coll.offset = originalOffset; coll.size = originalSize; } } private void Jump(InputAction.CallbackContext obj) { if (physicsCheck.isGround) rb.AddForce(transform.up*jumpForce, ForceMode2D.Impulse); } private void PlayerAttack(InputAction.CallbackContext obj) { playerAnimation.PlayAttack(); isAttack = true; } public void GetHurt(Transform attacker){ isHurt = true; rb.velocity = Vector2.zero; Vector2 dir = new Vector2((transform.position.x-attacker.transform.position.x),0).normalized; rb.AddForce(dir*hurtForce, ForceMode2D.Impulse); } public void PlayerDead(){ isDead = true; inputControl.Gameplay.Disable(); } private void CheckState() { if (isDead) gameObject.layer = LayerMask.NameToLayer("Enemy"); else gameObject.layer = LayerMask.NameToLayer("Player"); coll.sharedMaterial = physicsCheck.isGround ? normal : wall; } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>내장 객체 - request</title> </head> <body> <% //post 방식으로 전송된 한글이 깨지는 현상을 처리한다. request.setCharacterEncoding("UTF-8"); /* getParameter(): input 태그의 text, radio 타입처럼 하나의 값이 전송되는 경우 사용 입력값이 문자, 숫자에 상관없이 String타입으로 저장된다. getParameterValues(): checkbox 혹은 <select> 태그의 multiple 속성을 부여하여 2개 이상의 값이 전송되는 경우에 사용한다. 받은 값은 String타입의 배열로 저장된다. */ String id = request.getParameter("id"); String sex = request.getParameter("sex"); /*관심사항은 checkbox 이므로 2개 이상이 선택 될 수 있기 때문에 배열로 폼값을 받는다.*/ String[] favo = request.getParameterValues("favo"); String favoStr =""; if(favo!=null){ /*배열은 크기가 생기기 때문에 아래와 같이 반복할 수 있다.*/ for(int i = 0; i< favo.length; i++){ favoStr += favo[i] + " "; } //체크박스는 선택(체크)한 항목만 서버로 전송된다. } /*<textarea> 태그는 2줄 이상 입력가능하므로 엔터를 추가하는 경우 \r\n으로 저장된다. 따라서 웹브라우저에 출력할 때에는 <br>태그로 변경해야한다.*/ String intro = request.getParameter("intro").replace("\r\n", "<br>"); %> <ul> <li>아이디 : <%= id %></li> <li>성별 : <%= sex %></li> <li>관심사항 : <%= favoStr %></li> <li>자기소개: <%= intro %></li> </ul> </body> </html>
import React, { useContext, useEffect, useRef, useState } from "react"; import DeleteIcon from "@mui/icons-material/Delete"; import { IconButton } from "@mui/material"; import SendIcon from "@mui/icons-material/Send"; import MessageSelf from "./MessageSelf"; import MessageOthers from "./MessageOthers"; import { useDispatch, useSelector } from "react-redux"; import { useParams } from "react-router-dom"; import Skeleton from "@mui/material/Skeleton"; import axios from "axios"; import { myContext } from "./MainContainer"; import io from "socket.io-client"; const ENDPOINT = "https://mernproj-uh8p.onrender.com"; var socket, chat, data; function ChatArea() { const [messageContent, setMessageContent] = useState(""); const dyParams = useParams(); const [chat_id, chat_user] = dyParams._id.split("&"); const userData = JSON.parse(localStorage.getItem("userData")); const [allMessages, setAllMessages] = useState([]); const [allMessagesCopy, setAllMessagesCopy] = useState([]); const { refresh, setRefresh } = useContext(myContext); const [loaded, setloaded] = useState(false); const [socketConnectionStatus, setSocketConnectionStatus] = useState(false); const sendMessage = () => { const config = { headers: { Authorization: `Bearer ${userData.data.token}`, }, }; axios .post( "https://mernproj-uh8p.onrender.com/message", { content: messageContent, chatId: chat_id, }, config ) .then(({ response }) => { data = response; console.log("Message Fired"); }); socket.emit("newMessage", data); }; useEffect(() => { socket = io(ENDPOINT); socket.emit("setup", userData); socket.on("connection", () => { setSocketConnectionStatus(!socketConnectionStatus); }); }, []); useEffect(() => { socket.on("message recieved", (newMessage) => { if (!allMessagesCopy || allMessagesCopy._id !== newMessage._id) { } else { setAllMessages([...allMessages], newMessage); } }); }); useEffect(() => { const config = { headers: { Authorization: `Bearer ${userData.data.token}`, }, }; axios .get("https://mernproj-uh8p.onrender.com/message/" + chat_id, config) .then(({ data }) => { setAllMessages(data); setloaded(true); }); setAllMessagesCopy(allMessages); }, [refresh, chat_id, userData.data.token, allMessages]); if (!loaded) { return ( <div style={{ border: "20px", padding: "10px", width: "100%", display: "flex", flexDirection: "column", gap: "10px", }} > <Skeleton variant="rectangular" sx={{ width: "100%", borderRadius: "10px" }} height={60} /> <Skeleton variant="rectangular" sx={{ width: "100%", borderRadius: "10px", flexGrow: "1", }} /> <Skeleton variant="rectangular" sx={{ width: "100%", borderRadius: "10px" }} height={60} /> </div> ); } else { return ( <div className={"chatArea-container"}> <div className={"chatArea-header"}> <p className={"con-icon"}>{chat_user[0]}</p> <div className={"header-text"}> <p className={"con-title"}>{chat_user}</p> </div> {/* <IconButton> <DeleteIcon className={"icon"} /> </IconButton> */} </div> <div className={"messages-container"}> {allMessages .slice(0) .reverse() .map((message, index) => { const sender = message.sender; const self_id = userData.data._id; if (sender._id === self_id) { return <MessageSelf props={message} key={index} />; } else { return <MessageOthers props={message} key={index} />; } })} </div> <div className={"text-input-area"}> <input placeholder="Type a Message" className={"search-box"} value={messageContent} onChange={(e) => { setMessageContent(e.target.value); }} onKeyDown={(event) => { if (event.code == "Enter") { sendMessage(); setMessageContent(""); setRefresh(!refresh); } }} /> <IconButton onClick={() => { sendMessage(); setRefresh(!refresh); }} > <SendIcon className={"icon"} /> </IconButton> </div> </div> ); } } export default ChatArea;
/** * Lists all installed Deno commands by reading the Deno installation directory. * It checks the directory for executable files and prints their names. * * @async * @function listCommands * @description Lists all installed Deno commands. * @returns {Promise<void>} A promise that resolves when the command list is printed. */ import { denoBin, log, walk } from 'bru' /** * Lists all installed Deno commands by reading the Deno bin directory. * * @async * @function listInstalledCommands * @returns {Promise<void>} A promise that resolves when the command list is printed. */ async function listInstalledCommands(): Promise<void> { if (!denoBin) { log.error('Deno bin directory not found') return } log(`Listing Deno commands installed in: %c${denoBin}`, { styles: 'font-weight: bold; color: green; ', }) const commands: string[] = [] for await (const entry of walk(denoBin, { maxDepth: 1 })) { if (entry.isFile) { commands.push(entry.name) } } if (commands.length === 0) { log('No commands found') return } log.info(commands.join(', ')) } listInstalledCommands().catch((err) => log.error(`Error listing commands: ${err.message}`) )
Wrapping a paper net onto a cube This Kata is about wrapping a net onto a cube, not folding one into a cube. There is another kata for that task. Think about how you would fold a net into a cube. You would fold at the creases of the net at a 90 degree angle and make a cube. Wrapping a net onto a cube is simalar to folding one. For example the grey net can cover a cube entirely when folded, with one square on each face. However things are not always perfect. If we use the red net, we still can entirely wrap the net around a cube. But there is one face of the cube having two squares overlaping each other, i.e. squares A and E. The green and blue nets can't fully cover a cube, but it still can wrap onto a cube. All the folding is 90 degree along edges of the squares. In the 3D demontration of the green net below, squares A, F, E, and G overlap.But some nets can't be wrapped around a cube without folding inside a square or cutting an edge open, like the yellow net. Task Create function wrap_cube that uses a net, given as a string, to determine which squares of the net overlap when folded onto a cube. If the net cannot be folded onto a cube without being changed, return None. The input net will be a string. Spaces are empty parts, each char (case sensitive, including numbers) represents one square on the net. Ex.1 | Ex.2 | Ex.3 | | E | A F | 0 9 ABCDE | BCD | 8AB G | E G | a b The red net above could be inputed as a string of Example 1. The green net can be represented as example 2 or 3. If a net can't be wrapped onto a cube without being cut, return None. If it can, return a list of overlapping squares. For example the output of Example 1 above is [['A', 'E']]. The output of the Example 2 could be [["A", "F"], ["E", "G"]]. Your final asnswer does not have to be sorted, it can be in any order. You may find out more in the example test code. Notes: Use common sense to fold the net, only at 90 degree angles along the edges; No 180 degree folding, no cutting, no folding inside a square; For some huge nets, ignore the thickness of paper... All the input chars will be connected; but some trailing spaces may be stripped; There will be 500 large random nets in the test, each of which has >60 squares; but there are some easier tests too Not all 6 faces of the cube need be covered There are no repeating chars in a net, and only one char is only one square The sequence of the chars and lists is not important; test code will sort your answer. One more example: The input string could like this: """ ABCDE """ It's a stripe of paper with 5 squares side by side. If wrap this stripe around a cube, four faces will be covered. Two faces on the cube won't be covered, which is fine in this kata. The squares at the very two ends, A and E, will overlap. So the expected output of this net is [ [ "A" , "E" ] ] Beta Note: I "manually" checked not-so-large nets with my code. It should be able to handle huge nets. But if you found any erros in my expected answers, please let me know. thanks.
@extends('layouts.app') @section('title', (isset($title)) ? $title : '') @section('description', (isset($description)) ? $description : '') @section('content') <?php /* @var $event App\Event */ ?> <section class="main"> <div class="container"> <div class="row"> <div class="col-md-12"> <nav aria-label="breadcrumb"> <ol class="breadcrumb bg-secondary py-0 px-0"> <li class="breadcrumb-item"><a href="/">Home</a></li> <li class="breadcrumb-item"><a href="{{ route('events') }}">Events</a></li> <li class="breadcrumb-item active" aria-current="page">{{ $event->name }}</li> </ol> </nav> </div> </div> <div class="row justify-content-center"> <div class="col-md-12"> <div class="jumbotron bg-primary py-5 mb-3"> <h1>{{ $event->name }}</h1> <hr class="my-4"> <p class="lead"><?= $event->description ?></p> </div> </div> </div> <div class="row justify-content-center"> <div class="col-md-12"> @if($runs) <table class="esa-table" id="mainTable" data-order="[[0,&quot;asc&quot;]]"> <thead> <tr> <th>Schedule Time</th> <th>Game</th> <th>Category</th> <th>Platform</th> <th>Runners</th> <th>Time</th> <th data-sortable="false" data-priority="1">Play</th> </tr> </thead> <tbody> @foreach($runs as $run) <?php /* @var $run \App\Run */ ?> <tr data-id="{{ $run->id }}"> <td data-order="{{{ isset($run->run_date) ? $run->run_date : '' }}}" nowrap> @if(isset($run->run_date)) {{ Date('D M jS, h:ia', strtotime($run->run_date)) }} @endif </td> <td> @if(isset($run->game) && isset($run->game->slug)) <a href="{{ route('game.show', $run->game->slug) }}" title="View all {{ $run->game->name }} runs at ESA">{{ $run->game->name }}</a> @endif </td> <td>{{ $run->category }}</td> <td> @if(isset($run->platform->name) && isset($run->platform->slug)) <a href="{{ route('platform.show', $run->platform->slug) }}" title="View all {{ $run->platform->name }} runs at ESA">{{ $run->platform->name }}</a> @endif </td> <td> @foreach($run->runners as $key => $runner) @if(isset($runner->name) && isset($runner->slug)) <a href="{{ route('runner.show', $runner->slug) }}" title="View runs by {{ $runner->name }}">{{ $runner->name }}</a> @endif @endforeach </td> <td>{{ gmdate('H:i:s', $run->time) }}</td> <td class="video-links" nowrap> @if(isset($run->youtube_vod_id)) <a class="youtube" href="https://youtube.com/watch?v={{ $run->youtube_vod_id }}" title="Youtube Link" data-vod-site="youtube" data-vod="{{ $run->youtube_vod_id }}"><i class="fab fa-youtube"></i></a> @endif @if(isset($run->twitch_vod_id)) <a class="twitch" href="https://www.twitch.tv/videos/{{ $run->twitch_vod_id }}" title="Twitch Link" data-vod-site="twitch" data-vod="{{ $run->twitch_vod_id }}"><i class="fab fa-twitch"></i></a> @endif <a href="#" class="close-vod"><i class="fas fa-times"></i></a> </td> </tr> @endforeach </tbody> </table> @endif </div> </div> </div> </section> @endsection
<?php /** * The template for displaying Comments. * * The area of the page that contains both current comments * and the comment form. The actual display of comments is * handled by a callback to omega_comment() which is * located in the inc/template-tags.php file. * * @package Omega */ /* * If the current post is protected by a password and * the visitor has not yet entered the password we will * return early without loading the comments. */ /* If a post password is required or no comments are given and comments/pings are closed, return. */ if ( post_password_required() || ( !have_comments() && !comments_open() && !pings_open() ) ) return; ?> <div id="comments" class="entry-comments"> <?php // You can start editing here -- including this comment! ?> <?php if ( have_comments() ) : ?> <h3><?php comments_number( '', __( 'One Comment', 'omega' ), __( '% Comments', 'omega' ) ); ?></h3> <?php if ( get_option( 'page_comments' ) && 1 < get_comment_pages_count() ) : // are there comments to navigate through ?> <div class="comments-nav"> <?php previous_comments_link( __( '&larr; Previous', 'omega' ) ); ?> <span class="page-numbers"><?php printf( __( 'Page %1$s of %2$s', 'omega' ), ( get_query_var( 'cpage' ) ? absint( get_query_var( 'cpage' ) ) : 1 ), get_comment_pages_count() ); ?></span> <?php next_comments_link( __( 'Next &rarr;', 'omega' ) ); ?> </div><!-- .comments-nav --> <?php endif; // check for comment navigation ?> <ol class="comment-list"> <?php /* Loop through and list the comments. Tell wp_list_comments() * to use omega_comment() to format the comments. * If you want to overload this in a child theme then you can * define omega_comment() and that will be used instead. * See omega_comment() in lib/inc/template-tags.php for more. */ $args = array( 'walker' => null, 'max_depth' => '', 'style' => 'ul', 'callback' => 'omega_comment', 'end-callback' => null, 'type' => 'all', 'reply_text' => 'Reply', 'page' => '', 'per_page' => '', 'avatar_size' => 48, 'reverse_top_level' => null, 'reverse_children' => '', 'format' => 'xhtml', //or html5 @since 3.6 'short_ping' => false // @since 3.6 ); wp_list_comments( $args ); ?> </ol><!-- .comment-list --> <?php endif; // have_comments() ?> <?php // If comments are closed and there are comments, let's leave a little note, shall we? if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) : ?> <p class="no-comments"><?php _e( 'Comments are closed.', 'omega' ); ?></p> <?php endif; ?> </div><!-- #comments --> <?php comment_form(); ?>
import 'dart:convert'; Weather? weatherFromJson(String str) => Weather.fromJson(json.decode(str)); String weatherToJson(Weather data) => json.encode(data.toJson()); class Weather { Coord? coord; List<WeatherElement> weather; String? base; Main main; int? visibility; Wind? wind; Rain? rain; Clouds? clouds; int? dt; Sys? sys; int? timezone; int? id; String? name; int? cod; Weather({ this.coord, required this.weather, this.base, required this.main, this.visibility, this.wind, this.rain, this.clouds, this.dt, this.sys, this.timezone, this.id, this.name, this.cod, }); factory Weather.fromJson(Map<String, dynamic> json) => Weather( coord: json["coord"] == null ? null : Coord.fromJson(json["coord"]), weather: json["weather"] == null ? [] : List<WeatherElement>.from( json["weather"]!.map((x) => WeatherElement.fromJson(x))), base: json["base"], main: Main.fromJson(json["main"]), visibility: json["visibility"], wind: json["wind"] == null ? null : Wind.fromJson(json["wind"]), rain: json["rain"] == null ? null : Rain.fromJson(json["rain"]), clouds: json["clouds"] == null ? null : Clouds.fromJson(json["clouds"]), dt: json["dt"], sys: json["sys"] == null ? null : Sys.fromJson(json["sys"]), timezone: json["timezone"], id: json["id"], name: json["name"], cod: json["cod"], ); Map<String, dynamic> toJson() => { "coord": coord?.toJson(), "weather": List<dynamic>.from(weather.map((x) => x.toJson())), "base": base, "main": main.toJson(), "visibility": visibility, "wind": wind?.toJson(), "rain": rain?.toJson(), "clouds": clouds?.toJson(), "dt": dt, "sys": sys?.toJson(), "timezone": timezone, "id": id, "name": name, "cod": cod, }; } class Clouds { int? all; Clouds({ this.all, }); factory Clouds.fromJson(Map<String, dynamic> json) => Clouds( all: json["all"], ); Map<String, dynamic> toJson() => { "all": all, }; } class Coord { double? lon; double? lat; Coord({ this.lon, this.lat, }); factory Coord.fromJson(Map<String, dynamic> json) => Coord( lon: json["lon"]?.toDouble(), lat: json["lat"]?.toDouble(), ); Map<String, dynamic> toJson() => { "lon": lon, "lat": lat, }; } class Main { double? temp; double? feelsLike; double? tempMin; double? tempMax; int? pressure; int? humidity; int? seaLevel; int? grndLevel; Main({ this.temp, this.feelsLike, this.tempMin, this.tempMax, this.pressure, this.humidity, this.seaLevel, this.grndLevel, }); factory Main.fromJson(Map<String, dynamic> json) => Main( temp: json["temp"]?.toDouble(), feelsLike: json["feels_like"]?.toDouble(), tempMin: json["temp_min"]?.toDouble(), tempMax: json["temp_max"]?.toDouble(), pressure: json["pressure"], humidity: json["humidity"], seaLevel: json["sea_level"], grndLevel: json["grnd_level"], ); Map<String, dynamic> toJson() => { "temp": temp, "feels_like": feelsLike, "temp_min": tempMin, "temp_max": tempMax, "pressure": pressure, "humidity": humidity, "sea_level": seaLevel, "grnd_level": grndLevel, }; } class Rain { double? the1H; Rain({ this.the1H, }); factory Rain.fromJson(Map<String, dynamic> json) => Rain( the1H: json["1h"]?.toDouble(), ); Map<String, dynamic> toJson() => { "1h": the1H, }; } class Sys { int? type; int? id; String? country; int? sunrise; int? sunset; Sys({ this.type, this.id, this.country, this.sunrise, this.sunset, }); factory Sys.fromJson(Map<String, dynamic> json) => Sys( type: json["type"], id: json["id"], country: json["country"], sunrise: json["sunrise"], sunset: json["sunset"], ); Map<String, dynamic> toJson() => { "type": type, "id": id, "country": country, "sunrise": sunrise, "sunset": sunset, }; } class WeatherElement { int? id; String main; String? description; String? icon; WeatherElement({ this.id, required this.main, this.description, this.icon, }); factory WeatherElement.fromJson(Map<String, dynamic> json) => WeatherElement( id: json["id"], main: json["main"], description: json["description"], icon: json["icon"], ); Map<String, dynamic> toJson() => { "id": id, "main": main, "description": description, "icon": icon, }; } class Wind { double? speed; int? deg; double? gust; Wind({ this.speed, this.deg, this.gust, }); factory Wind.fromJson(Map<String, dynamic> json) => Wind( speed: json["speed"]?.toDouble(), deg: json["deg"], gust: json["gust"]?.toDouble(), ); Map<String, dynamic> toJson() => { "speed": speed, "deg": deg, "gust": gust, }; }
package br.edu.infnet; import java.util.ArrayList; import java.util.List; public class Turma { private String codigo; private Disciplina disciplina; private Professor professor; private List<Aluno> alunosInscritos; public Turma(String codigo, Disciplina disciplina, Professor professor) { this.codigo = codigo; this.disciplina = disciplina; this.professor = professor; this.alunosInscritos = new ArrayList<>(); } public String addAluno(Aluno aluno, Turma turmaNome) { if (alunosInscritos.size() >= 50) { return "Turma cheia"; } else { alunosInscritos.add(aluno); return "Aluno " + aluno.getNome() + " adicionado à turma " + turmaNome; } } public boolean abrirTurma() { // A turma só pode ser aberta se houver pelo menos um aluno matriculado return alunosInscritos.size() >= 1; } public String gerarPauta() { // Construindo a string com as informações da turma StringBuilder pauta = new StringBuilder("Código da Turma: " + codigo + "\n"); pauta.append("Disciplina: ").append(disciplina.getNome()).append("\n"); pauta.append("Professor: ").append(professor.getNome()).append("\n"); pauta.append("Alunos inscritos:\n"); for (Aluno aluno : alunosInscritos) { pauta.append("- ").append(aluno.getNome()).append("\n"); } return pauta.toString(); } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } @Override public String toString(){ return codigo; } }
# -*- coding: utf-8 -*- # # Copyright 2022 Google LLC. 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. """Helpers for flags in commands for Anthos clusters on bare metal.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.calliope import arg_parsers from googlecloudsdk.calliope.concepts import concepts from googlecloudsdk.command_lib.container.bare_metal import cluster_flags from googlecloudsdk.command_lib.util.concepts import concept_parsers def NodePoolAttributeConfig(): return concepts.ResourceParameterAttributeConfig( name='node_pool', help_text='node pool of the {resource}.') def GetNodePoolResourceSpec(): return concepts.ResourceSpec( 'gkeonprem.projects.locations.bareMetalClusters.bareMetalNodePools', resource_name='node_pool', bareMetalNodePoolsId=NodePoolAttributeConfig(), bareMetalClustersId=cluster_flags.ClusterAttributeConfig(), locationsId=cluster_flags.LocationAttributeConfig(), projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG, ) def AddNodePoolResourceArg(parser, verb, positional=True): """Adds a resource argument for a Bare Metal node pool. Args: parser: The argparse parser to add the resource arg to. verb: str, the verb to describe the resource, such as 'to update'. positional: bool, whether the argument is positional or not. """ name = 'node_pool' if positional else '--node-pool' concept_parsers.ConceptParser.ForResource( name, GetNodePoolResourceSpec(), 'node pool {}'.format(verb), required=True).AddToParser(parser) def AddAllowMissingNodePool(parser): """Adds a flag for the node pool operation to return success and perform no action when there is no matching node pool. Args: parser: The argparse parser to add the flag to. """ parser.add_argument( '--allow-missing', action='store_true', help='If set, and the Bare Metal Node Pool is not found, the request will succeed but no action will be taken.', ) # TODO(b/257292798): Move to a shared location. def AddAllowMissingUpdateNodePool(parser): """Adds a flag to enable allow missing in an update node pool request. If set to true, and the Bare Metal Node Pool is not found, the request will create a new Bare Metal Node Pool with the provided configuration. The user must have both create and update permission to call Update with allow_missing set to true. Args: parser: The argparse parser to add the flag to. """ parser.add_argument( '--allow-missing', action='store_true', help='If set, and the Anthos cluster on bare metal is not found, the update request will try to create a new cluster with the provided configuration.', ) def AddNodePoolDisplayName(parser): """Adds a flag to specify the display name of the node pool. Args: parser: The argparse parser to add the flag to. """ parser.add_argument( '--display-name', type=str, help='Display name for the resource.') def AddNodePoolAnnotations(parser): """Adds a flag to specify node pool annotations.""" parser.add_argument( '--annotations', metavar='KEY=VALUE', type=arg_parsers.ArgDict(), help='Annotations on the node pool.', ) def AddNodePoolConfig(parser, is_update=False): """Adds a command group to set the node pool config. Args: parser: The argparse parser to add the flag to. is_update: bool, whether the flag is for update command or not. """ required = not is_update bare_metal_node_pool_config_group = parser.add_group( required=required, help='Anthos on bare metal node pool configuration.', ) _AddNodeConfigs(bare_metal_node_pool_config_group, is_update) _AddNodeLabels(bare_metal_node_pool_config_group) _AddNodeTaints(bare_metal_node_pool_config_group) def _AddNodeConfigs(bare_metal_node_pool_config_group, is_update=False): """Adds flags to set the node configs. Args: bare_metal_node_pool_config_group: The parent group to add the flags to. is_update: bool, whether the flag is for update command or not. """ required = not is_update node_pool_configs_from_file_help_text = """ Path of the YAML/JSON file that contains the node configs. Examples: nodeConfigs: - nodeIp: 10.200.0.10 labels: node1: label1 node2: label2 - nodeIp: 10.200.0.11 labels: node3: label3 node4: label4 List of supported fields in `nodeConfigs` KEY | VALUE | NOTE --------------|---------------------------|--------------------------- nodeIp | string | required, mutable labels | one or more key-val pairs | optional, mutable """ bare_metal_node_pool_config_group.add_argument( '--node-configs-from-file', required=required, help=node_pool_configs_from_file_help_text, type=arg_parsers.YAMLFileContents(), ) def _AddNodeLabels(bare_metal_node_pool_config_group): """Adds a flag to assign labels to nodes in a node pool. Args: bare_metal_node_pool_config_group: The parent group to add the flags to. """ bare_metal_node_pool_config_group.add_argument( '--node-labels', metavar='KEY=VALUE', type=arg_parsers.ArgDict(), help='Labels assigned to nodes of a node pool.', ) def _AddNodeTaints(bare_metal_node_pool_config_group): """Adds a flag to specify the node taint in the node pool. Args: bare_metal_node_pool_config_group: The parent group to add the flags to. """ bare_metal_node_pool_config_group.add_argument( '--node-taints', metavar='KEY=VALUE:EFFECT', help='Node taint applied to every Kubernetes node in a node pool.', type=arg_parsers.ArgDict(), )
<html> <head> <title>Portfolio</title> <link rel="stylesheet" href="styles.css"> <script src="https://kit.fontawesome.com/984e4357af.js" crossorigin="anonymous"></script> </head> <body> <div id="header"> <div class="container"> <nav> <h1 class="logo"><span style="color:orangered">MY </span>Portfolio</h1> <ul id="sidemenu"> <li><a href="#header">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#services">Services</a></li> <li><a href="#portfolio">Projects</a></li> <li><a href="#contact">Contact</a></li> <i class=" oo fa-solid fa-xmark" onclick="closemenu()"></i> </ul> <i class="oo fa-solid fa-bars" onclick="openmenu()"></i> </nav> <div class="header-text"> <p>Full - Stack developer</p> <h1>Hi, I'm <span>Kayathri Manivannan</span><br>From Tamil Nadu</h1> </div> </div> <!-------------about------------> </div> <div id="about"> <div class="container"> <div class="row"> <div class="about-col-1"> <img src="kayathri.jpeg"> </div> <div class="about-col-2"> <h1 class="sub-title">About Me</h1> <p>Enthusiastic and driven current college student with a passion for innovation. An avid learner and proactive team player. Commited to delivering exceptional results through approaches such as teamwork and problem-solving. </p> <div class="tab-titles"> <p class="tab-links active-link" onclick="opentab('skills')">Skills</p> <p class="tab-links" onclick="opentab('experience')">Experience</p> <p class="tab-links" onclick="opentab('education')">Education</p> </div> <div class="tab-contents active-tab" id="skills"> <ul> <li><span>Web development</span><br>Html/CSS/JS</li><br> <li><span>Python</span><br>Python Datastructure and algorithms</li><br> <li><span>Problem solving</span><br>300+ problems in CodeChef</li><br> </ul> </div> <div class="tab-contents" id="experience"> <ul> <li><span>10 March 2024 - 10 April 2024</span><br>Internship at CodSoft</li><br> </ul> </div> <div class="tab-contents" id="education"> <ul> <li><span>2021 - 2025</span><br>BE(cse) from,<br>Sona College Of Technology</li><br> <li><span>2020 - 2021</span><br>HSC from,<br>Alagappa Matriculation Higher Secondary School</li><br> <li><span>2018 - 2019</span><br>SSLC from,<br>Alagappa Matriculation Higher Secondary School</li><br> </ul> </div> </div> </div> </div> </div> <!----------serices--------> <div id="services"> <div class="container"> <h1 class="sub-title">My Services</h1> <div class="services-list"> <div> <i class="fa-solid fa-code"></i> <h2>Web Design</h2> <p>Elevate your brand with our expert web design services. We create visually stunning and user-friendly websites tailored to your unique needs.</p> </div> <div> <i class="fa-brands fa-python"></i> <h2>Python Development</h2> <p>Unlock the power of Python with our skilled developers. From robust backend solutions to innovative applications, we bring your ideas to life with expertise and efficiency.</p> </div> <div> <i class="fa-brands fa-codepen"></i> <h2>Problem Solveing</h2> <p>Tackle challenges head-on with our problem-solving expertise. We provide strategic solutions to navigate complexities and optimize outcomes for your business.</p> </div> </div> </div> </div> <!--------project-----------> <div id="portfolio"> <div class="container"> <h1 class="sub-title">My Projects</h1> <div class="work-list"> <div class="work"> <img src="images1.jpeg"> <div class="layer"> <h3>Portfolio</h3> <p>Explore my portfolio showcasing a diverse range of projects, where creativity meets functionality. Each design tells a unique story, capturing the essence of innovation and precision.</p> </div> </div> <div class="work"> <img src="images2.png"> <div class="layer"> <h3>Landing Page</h3> <p>Step into innovation with our captivating landing page project. Engage visitors instantly with a visually appealing design that reflects your brand essence.</p> </div> </div> <div class="work"> <img src="images3.png"> <div class="layer"> <h3>Calculator</h3> <p>Experience efficiency with our Grid-based calculator project. Seamlessly designed for intuitive functionality, it offers a user-friendly interface for quick and precise calculations.</p> </div> </div> </div> </div> </div> <!-----------contact--------------> <div id="contact"> <div class="container"> <div class="row"> <div class="contact-left"> <h1 class="sub-title">Contact Me</h1> <p><i class="fa-solid fa-paper-plane"></i> [email protected]</p> <p><i class="fa-solid fa-square-phone"></i> 9345992775</p> <div class="social-icons"> <a href="https://www.linkedin.com/in/kayathri-manivannan-161b68288/"><i class="fa-brands fa-linkedin"></i></a> <a href="https://github.com/kayathri11"><i class="fa-brands fa-github"></i></a> </div> <a href="Resume.pdf" download class="btn btn2">Download Resume</a> </div> <div class="contact-right"> <form name='submit-to-google-sheet'> <input type="text" name="Name" placeholder="Your Name" required> <input type="email" name="Mail" placeholder="Your Email" required> <textarea name="Message" rows="6" placeholder="Your Message"></textarea> <button type="submit" class="btn btn2">Submit</button> </form> <span id="msg"></span> </div> </div> </div> <div class="copyright"> <p>Copyright © Kayathri Manivannan 2024 | All rights reserved. </p> </div> </div> <script> var tablinks=document.getElementsByClassName("tab-links"); var tabcontents=document.getElementsByClassName("tab-contents"); function opentab(tagname){ for(tablink of tablinks){ tablink.classList.remove("active-link"); } for(tabcontent of tabcontents){ tabcontent.classList.remove("active-tab"); } event.currentTarget.classList.add("active-link"); document.getElementById(tagname).classList.add("active-tab"); } </script> <script> var sidemenu=document.getElementById("sidemenu"); function openmenu(){ sidemenu.style.right="0"; } function closemenu(){ sidemenu.style.right="-200px"; } </script> <script> const scriptURL = 'https://script.google.com/macros/s/AKfycbwqjJIA_Uj126DLGX8NPidTzt80bYv8NFm17p7wiuFOD5UIqjlUpoTLvRFWqzHDMzVK1Q/exec' const form = document.forms['submit-to-google-sheet'] const msg = document.getElementById("msg") form.addEventListener('submit', e => { e.preventDefault() fetch(scriptURL, { method: 'POST', body: new FormData(form)}) .then(response => { msg.innerHTML="Your response has been submited." setTimeout(function(){ msg.innerHtml="" },5000) form.reset() }) .catch(error => console.error('Error!', error.message)) }) </script> </body> </html>
import { Product } from '@/lib/types'; import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger, } from './ui/sheet'; import { Button } from './ui/button'; import { Input } from './ui/input'; import { useState } from 'react'; import { Separator } from './ui/separator'; export interface ProductCartProps { product: Product; triggerElement: JSX.Element; } export const ProductCart = ({ product, triggerElement }: ProductCartProps) => { const [quantity, setQuantity] = useState(0); const totalPrice = quantity * Number(product.price); return ( <Sheet> <SheetTrigger asChild>{triggerElement}</SheetTrigger> <SheetContent> <SheetHeader> <SheetTitle>{product.title}</SheetTitle> <SheetDescription>{product.description}</SheetDescription> </SheetHeader> <Separator className="my-4" /> <div className="flex flex-col gap-4"> <div> <p className="font-semibold">Price per unit</p> <div className="flex gap-2"> <p>{product.price}</p> <p>{product.currency}</p> </div> </div> <div> <p className="font-semibold">Select quantity</p> <Input type="number" defaultValue={quantity} onChange={(e) => setQuantity(Number(e.target.value))} /> </div> <div> <p className="text-lg font-bold">Total price</p> <div className="flex gap-2"> <p>{totalPrice}</p> <p>{product.currency}</p> </div> </div> <Button className="justify-center mt-4" disabled type="submit"> Send Order </Button> </div> </SheetContent> </Sheet> ); };
import argparse import os import json from distutils.util import strtobool as boolean from pprint import PrettyPrinter import wandb import torch.utils.data.distributed import torchvision.models as models from MBM.better_mistakes.util.rand import make_deterministic from MBM.better_mistakes.util.folders import get_expm_folder from MBM.better_mistakes.util.config import load_config from MBM.scripts import start_training, start_testing from util import logger TASKS = ["training", "testing"] CUSTOM_MODELS = ["custom_resnet18", "wide_resnet"] MODEL_NAMES = sorted(name for name in models.__dict__ if name.islower() and not name.startswith("__") and callable(models.__dict__[name])) MODEL_NAMES.extend(CUSTOM_MODELS) # l5 refers to loss of level-5 for CIFAR-100, l7 refers to loss of level-7 for iNaturalist-19, l12 refers to loss of level-12 for tiered-imageneget-224. LOSS_NAMES = ["cross-entropy", "soft-labels", "hierarchical-cross-entropy", "cosine-distance", "ranking-loss", "cosine-plus-xent", "yolo-v2", "flamingo-l5", "flamingo-l7", "flamingo-l12", # Cheng et al's [7] "ours-l5-cejsd", "ours-l7-cejsd", "ours-l12-cejsd", # HAF with only Soft Hierarchical Consistency Loss (Section 3.2) "ours-l5-cejsd-wtconst", "ours-l7-cejsd-wtconst", "ours-l12-cejsd-wtconst", # HAF with Soft Hierarchical Consistency Loss (Section 3.2) + Geometric Consistency Loss (Section 3.4) "ours-l5-cejsd-wtconst-dissim", "ours-l7-cejsd-wtconst-dissim", "ours-l12-cejsd-wtconst-dissim"] # HAF with all three losses (Section 3.2, 3.3, 3.4) OPTIMIZER_NAMES = ["adagrad", "adam", "adam_amsgrad", "rmsprop", "SGD", "custom_sgd"] DATASET_NAMES = ["tiered-imagenet-84", "inaturalist19-84", "tiered-imagenet-224", "inaturalist19-224", "cifar-100"] if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--start", default="training", choices=TASKS, help="name of the task | ".join(TASKS)) parser.add_argument("--arch", default="resnet18", choices=MODEL_NAMES, help="model architecture: | ".join(MODEL_NAMES)) parser.add_argument("--loss", default="cross-entropy", choices=LOSS_NAMES, help="loss type: | ".join(LOSS_NAMES)) parser.add_argument("--optimizer", default="adam_amsgrad", choices=OPTIMIZER_NAMES, help="optimizer type: | ".join(OPTIMIZER_NAMES)) parser.add_argument("--lr", default=1e-5, type=float, help="initial learning rate of optimizer") parser.add_argument("--weight_decay", default=0.0, type=float, help="weight decay of optimizer") parser.add_argument("--pretrained", type=boolean, default=True, help="start from ilsvrc12/imagenet model weights") parser.add_argument("--pretrained_folder", type=str, default=None, help="folder or file from which to load the network weights") parser.add_argument("--dropout", default=0.0, type=float, help="Prob of dropout for network FC layer") parser.add_argument("--data_augmentation", type=boolean, default=True, help="Train with basic data augmentation") parser.add_argument("--epochs", default=None, type=int, help="number of epochs") parser.add_argument("--num_training_steps", default=200000, type=int, help="number of total steps to train for (num_batches*num_epochs)") parser.add_argument("--start-epoch", default=0, type=int, help="manual epoch number (useful on restarts)") parser.add_argument("--batch-size", default=256, type=int, help="total batch size") parser.add_argument("--shuffle_classes", default=False, type=boolean, help="Shuffle classes in the hierarchy") parser.add_argument("--beta", default=0, type=float, help="Softness parameter: the higher, the closer to one-hot encoding") parser.add_argument("--alpha", type=float, default=0, help="Decay parameter for hierarchical cross entropy.") # Devise/B&D ---------------------------------------------------------------------------------------------------------------------------------------------- parser.add_argument("--devise", type=boolean, default=False, help="Use DeViSe label embeddings") parser.add_argument("--devise_single_negative", type=boolean, default=False, help="Use one negative per samples instead of all") parser.add_argument("--barzdenzler", type=boolean, default=False, help="Use Barz&Denzler label embeddings") parser.add_argument("--train_backbone_after", default=float("inf"), type=float, help="Start training backbone too after this many steps") parser.add_argument("--use_2fc", default=False, type=boolean, help="Use two FC layers for Devise") parser.add_argument("--fc_inner_dim", default=1024, type=int, help="If use_2fc is True, their inner dimension.") parser.add_argument("--lr_fc", default=1e-3, type=float, help="learning rate for FC layers") parser.add_argument("--weight_decay_fc", default=0.0, type=float, help="weight decay of FC layers") parser.add_argument("--use_fc_batchnorm", default=False, type=boolean, help="Batchnorm layer in network head") # Data/paths ---------------------------------------------------------------------------------------------------------------------------------------------- parser.add_argument("--data", default="inaturalist19-224", help="id of the dataset to use: | ".join(DATASET_NAMES)) parser.add_argument("--target_size", default=224, type=int, help="Size of image input to the network (target resize after data augmentation)") parser.add_argument("--data-paths-config", help="Path to data paths yaml file", default="data_paths.yml") parser.add_argument("--data-path", default=None, help="explicit location of the data folder, if None use config file.") parser.add_argument("--data_dir", default="data/", help="Folder containing the supplementary data") parser.add_argument("--output", default="out/", help="path to the model folder") parser.add_argument("--expm_id", default="", type=str, help="Name log folder as: out/<scriptname>/<date>_<expm_id>. If empty, expm_id=time") # Log/val ------------------------------------------------------------------------------------------------------------------------------------------------- parser.add_argument("--log_freq", default=100, type=int, help="Log every log_freq batches") parser.add_argument("--val_freq", default=1, type=int, help="Validate every val_freq epochs (except the first 10 and last 10)") # Execution ----------------------------------------------------------------------------------------------------------------------------------------------- parser.add_argument("--workers", default=2, type=int, help="number of data loading workers") parser.add_argument("--seed", default=None, type=int, help="seed for initializing training. ") parser.add_argument("--gpu", default=0, type=int, help="GPU id to use.") ## CRM ---------------------------------------------------------------------------------- parser.add_argument("--rerank",default=0,type=int,help='whether to use CRM or not') parser.add_argument("--checkpoint_path",default=None,type=str,help='path to the best checkpoint file') parser.add_argument("--feature_space", default=None, type=str, help='use haf++ for using the proposed method') parser.add_argument("--margin", default=5, type=float, help='default to 5') parser.add_argument("--expand_feat_dim", default=1, type=int, help='default to 0') opts = parser.parse_args() # setting the path of level-5 distances and pickle file. if opts.data == "cifar-100": opts.data_dir = os.path.join(opts.data_dir, "cifar-l5/original/") print(opts.data_dir) # setup output folder opts.out_folder = opts.output if opts.output else get_expm_folder(__file__, "out", opts.expm_id) if not os.path.exists(opts.out_folder): print("Making experiment folder and subfolders under: ", opts.out_folder) os.makedirs(os.path.join(opts.out_folder)) # set if we want to output soft labels or one hot opts.soft_labels = opts.beta != 0 # print options as dictionary and save to output PrettyPrinter(indent=4).pprint(vars(opts)) if opts.start == "training": # Create opts.json file with open(os.path.join(opts.out_folder, "opts.json"), "w") as fp: json.dump(vars(opts), fp) # setup data path from config file if needed if opts.data_path is None: opts.data_paths = load_config(opts.data_paths_config) opts.data_path = opts.data_paths[opts.data] # setup random number generation if opts.seed is not None: make_deterministic(opts.seed) # OUR HXE # if opts.weights: # opts.weights = tuple(opts.weights) gpus_per_node = torch.cuda.device_count() if opts.start == "training": # Setup wandb logging parameters if opts.data == "cifar-100": project = "cifar-100" elif opts.data == "inaturalist19-224": project = "iNaturalist19" elif opts.data == "tiered-imagenet-224": project = "TieredImagenet" entity = "hierarchical-classification" if opts.loss == "soft-labels": run_name = "soft-labels (β=%.1f)"%opts.beta elif opts.loss == "cross-entropy": run_name = "cross-entropy" elif opts.loss == "hierarchical-cross-entropy": run_name = "hxe (α=%f)"%opts.alpha else: run_name = opts.loss logger.init(project=project, entity=entity, config=opts, run_name=run_name) # Start training start_training.main_worker(gpus_per_node, opts) else: logger._print("MBM Test Results >>>>>>>>>>", os.path.join(opts.out_folder, "logs.txt")) start_testing.main(opts)
from dataclasses import dataclass from datetime import date from typing import Union from tabatu.periodicidade import Periodicidade from tabatu.premissas import Premissas from src.calculadora_vpa import CalculadoraVPAPagamento from src.idades_prazos import IdadesPrazosPagamento @dataclass(frozen=True) class Pagamento: """Classe abstrata que representa o pagamento associado a uma cobertura de seguro. Realiza uma adptação entre as calculadoras de VPA e os contratos (usualmente capitalizados). Fornece também alguns métodos para auxiliar nas alterações permitadas pelos contratos. Args: calculadora_vpa (CalculadoraVPAPagamento): Calculadora do VPA da cobertura. Usualmente uma das classes de fluxo ou comutação de pagamento. """ calculadora_vpa: CalculadoraVPAPagamento @property def idades_prazos(self) -> IdadesPrazosPagamento: return self.calculadora_vpa.idades_prazos @property def premissas_atuariais(self) -> Premissas: return self.calculadora_vpa.premissas_atuariais @property def data_assinatura(self) -> date: return self.idades_prazos.data_assinatura @property def prazo_pagamento(self) -> Union[int, float]: return self.idades_prazos.prazo_pagamento @property def periodicidade(self) -> Periodicidade: return self.premissas_atuariais.periodicidade @property def periodicidade_pagamento(self) -> Periodicidade: return self.calculadora_vpa.periodicidade_pagamento @property def parcelamento(self) -> int: return int( self.periodicidade_pagamento.quantidade_periodos_1_periodicidade( self.periodicidade ) ) def vpa(self, tempo_decorrido: int) -> float: """Cálculo do valor presente atuarial das obrigações futuras. Args: tempo_decorrido (int): Tempo decorrido desde o início da cobertura, na periodicdade da cobertura. Returns: float: Valor presente das obrigações futuras em tempo_decorrido. """ if tempo_decorrido < 0: raise ValueError("O tempo_decorrido deve ser positivo") return self.calculadora_vpa.calcular_vpa(tempo_atual=tempo_decorrido)
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AlquileresComponent } from '../alquileres/alquileres.component'; import { AppComponent } from '../app.component'; import { LectoresComponent } from '../lectores/lectores.component'; const routes: Routes = [ { path: '', redirectTo: '/libros', pathMatch: 'full' }, { path: 'libros', component: AppComponent }, { path: 'lectores', component: LectoresComponent }, { path: 'alquileres', component: AlquileresComponent } ] @NgModule({ declarations: [], imports: [ CommonModule, RouterModule.forRoot(routes) ], exports: [RouterModule] }) export class NavbarRoutingModule { }
import { createContext, useCallback, useEffect, useMemo, useState, } from "react"; import { Devices } from "../Resources/DeviceResources"; import { DevicePresets, defaultPresets } from "../Resources/PresetResources"; import { ServerResponse } from "../Resources/ServerResponseResources"; import { cloneDeep } from "lodash"; import axios from "axios"; import useTVSettings, { TVSettingsHook, defaultTVSettingsHook, } from "../Hooks/GlobalContext/useTVSettings"; import { TVMappings, defaultTVMappings, defaultTVSettings, } from "../Resources/TVSettingsResources"; import useGlobalDevice from "../Hooks/GlobalContext/useGlobalDevice"; import useTVLightToggle from "../Hooks/GlobalContext/useTVLightToggle"; import useTVMappings from "../Hooks/GlobalContext/useTVMappings"; interface GlobalContextProviderProps { children: React.ReactNode | React.ReactNode[]; } export interface TVPosition { topPx: number; bottomPx: number; leftPx: number; rightPx: number; } type GlobalProps = OtherProps & TVSettingsHook; interface OtherProps { tvShown: boolean; toggleTvShown: (nVal?: boolean) => void; presets: DevicePresets[]; devices: Devices[]; modes: string[]; getModes: () => void; deleteDevice: (i: number) => Promise<ServerResponse>; addDevice: (device: Devices) => Promise<ServerResponse>; updateDevice: (i: number, nDevice: Devices) => Promise<ServerResponse>; updateDevicePreset: ( i: number, presetName: string ) => Promise<ServerResponse>; addNewPreset: (i: number, name: string) => Promise<ServerResponse>; tv_mappings: TVMappings; } export const defaultServerResponse: ServerResponse = { status: "error", message: "Context Provider was not initialized properly", code: 400, }; export const serverNotFoundResponse: ServerResponse = { status: "error", message: "Endpoint or server not found.", code: 404, }; const noCallResponse: ServerResponse = { status: "error", message: "No call was made to the server", code: 400, }; export const successfulServerResponse: ServerResponse = { status: "success", message: "Device added successfully", code: 200, }; const baseURL = process.env.REACT_APP_BASE_URL || window.location.origin; const defaultGlobalData = { tvShown: false, toggleTvShown: (nVal?: boolean) => null, presets: defaultPresets, devices: [], modes: [], getModes: async () => null, deleteDevice: async (i: number) => defaultServerResponse, addDevice: async (device: Devices) => defaultServerResponse, updateDevice: async (i: number, nDevice: Devices) => defaultServerResponse, updateDevicePreset: async (i: number, presetName: string) => defaultServerResponse, addNewPreset: async (i: number, name: string) => defaultServerResponse, ...defaultTVSettingsHook, tv_mappings: defaultTVMappings, }; export const GlobalContext = createContext<GlobalProps>(defaultGlobalData); export const GlobalContextProvider: React.FC<GlobalContextProviderProps> = ({ children, }) => { const tv = useTVSettings(); const tvToggler = useTVLightToggle({}); const deviceManager = useGlobalDevice({}); const { tv_mappings } = useTVMappings({}); const [modes, setModes] = useState<string[]>([]); const getModes = useCallback(async () => { const options = { method: "GET", url: baseURL + "/modes", }; let response = serverNotFoundResponse; try { response = await axios(options); response = response.data; } catch (e) { console.error(e); } if (response.status === "success") { setModes(response.data); } }, [setModes]); useEffect(() => { deviceManager.getDevices(); deviceManager.getPresets(); getModes(); tv.getTVSettings(); }, []); const value: GlobalProps = useMemo(() => { return { modes, getModes, ...tv, ...deviceManager, ...tvToggler, tv_mappings, }; }, [modes, getModes, deviceManager, tv, tv_mappings]); return ( <GlobalContext.Provider value={value}>{children}</GlobalContext.Provider> ); };
/* eslint-disable @typescript-eslint/no-explicit-any */ import { IconButton, Flex, Button } from '@chakra-ui/react' import { useState } from 'react' import { FaPlus, FaMinus } from 'react-icons/fa' import CustomInput from '../../components/CustomInput' import ModalContainer from '../../components/ModalContainer' import { formatYupError } from '../../utils/helpers' import { useCustomToast } from '../../utils/toast' import { transferMoneySchema } from '../../utils/validations' import { useGetTransactions } from '../Dashboard/api' import { useTransferMoney } from './api' const MakePayment = ({ isOpen, onClose, }: { isOpen: boolean onClose: () => void }) => { const { successToast, errorToast } = useCustomToast() const { mutate, isPending: isTransferingMoney } = useTransferMoney() const [customErrors, setCustomErrors] = useState<Record<string, any>>({}) const initialTransferValues = [ { email: '', phone: '', valueInUSD: '', }, ] const [payeeLists, setPayeeLists] = useState(initialTransferValues) const handleRemovePayee = (idx: number) => { const updatedPayeeLists = payeeLists.filter( (_el, index) => index !== idx, ) setPayeeLists(updatedPayeeLists) } const { refetch: refetchTransactions } = useGetTransactions() const handleTransferMoneySubmit = () => { transferMoneySchema .validate(payeeLists, { abortEarly: false }) .then((res: any) => { const payload = res.map((el: any) => ({ ...el, valueInUSD: Number(el.valueInUSD), })) mutate(payload, { onSuccess: () => { onClose() successToast('Transfer successful') setPayeeLists(initialTransferValues) refetchTransactions() }, onError: () => { errorToast('Transfer failed') }, }) setCustomErrors({}) }) .catch(err => { const errLists = formatYupError(err) setCustomErrors(errLists) }) } return ( <ModalContainer title='Payment Transfer' isOpen={isOpen} onClose={onClose} > <IconButton variant={'secondary'} icon={<FaPlus />} maxW='fit-content' aria-label='add' onClick={() => setPayeeLists((prev: any) => [ ...prev, { email: '', phone: '', valueInUSD: '' }, ]) } /> {payeeLists.map((payee, idx) => ( <Flex key={idx} flexDirection={'column'} gap='18px' py='24px'> <CustomInput name={`email`} value={payee.email} onChange={e => { const updatedLists = payeeLists.map((el, index) => idx === index ? { ...el, email: e.target.value } : el, ) setPayeeLists(updatedLists) }} error={customErrors[`[${idx}].email`]} placeholder='Email of the payee' /> <CustomInput name={`phone`} value={payee.phone} onChange={e => { const updatedLists = payeeLists.map((el, index) => idx === index ? { ...el, phone: e.target.value } : el, ) setPayeeLists(updatedLists) }} error={customErrors[`[${idx}].phone`]} placeholder={'Phone e.g +234...'} /> <CustomInput name={`valueInUSD`} value={payee.valueInUSD} onChange={e => { const updatedLists = payeeLists.map((el, index) => idx === index ? { ...el, valueInUSD: e.target.value, } : el, ) setPayeeLists(updatedLists) }} error={customErrors[`[${idx}].valueInUSD`]} placeholder={'Amount in USD'} /> <IconButton hidden={payeeLists.length === 1} variant={'danger'} maxW='fit-content' icon={<FaMinus />} aria-label='add' onClick={() => handleRemovePayee(idx)} /> </Flex> ))} <Button w='full' onClick={handleTransferMoneySubmit} _hover={{ bgColor: 'secColor', }} isLoading={isTransferingMoney} > Transfer Money </Button> </ModalContainer> ) } export default MakePayment /* eslint-disable @typescript-eslint/no-explicit-any */
import { makeStyles, createStyles } from "@material-ui/core/styles"; import React from "react"; export type IconProps = { width?: number; height?: number; color?: string; href?: string; className?: string; }; export default function MinusCircleIcon(props: IconProps) { const { width, height, color } = props; const useStyles = makeStyles((theme) => createStyles({ root: { stroke: color, "&:hover": { stroke: "#ffff", cursor: "pointer", }, }, }) ); const classes = useStyles(); return ( <svg width={width} height={height} viewBox={`0 0 32 32`} fill="none" xmlns="http://www.w3.org/2000/svg" className={classes.root} > <path d="M16 28C22.6274 28 28 22.6274 28 16C28 9.37258 22.6274 4 16 4C9.37258 4 4 9.37258 4 16C4 22.6274 9.37258 28 16 28Z" stroke={classes.root} stroke-linecap="round" stroke-linejoin="round" /> <path d="M11 16H21" stroke={classes.root} stroke-linecap="round" stroke-linejoin="round" /> </svg> ); } MinusCircleIcon.defaultProps = { width: 32, height: 32, color: "#26213f", };
function out = CO_Embed2_Dist(y,tau) % CO_Embed2_Dist Analyzes distances in a 2-d embedding space of a time series. % % Returns statistics on the sequence of successive Euclidean distances between % points in a two-dimensional time-delay embedding space with a given % time-delay, tau. % % Outputs include the autocorrelation of distances, the mean distance, the % spread of distances, and statistics from an exponential fit to the % distribution of distances. % %---INPUTS: % y, a z-scored column vector representing the input time series. % tau, the time delay. % ------------------------------------------------------------------------------ % Copyright (C) 2015, Ben D. Fulcher <[email protected]>, % <http://www.benfulcher.com> % % If you use this code for your research, please cite: % B. D. Fulcher, M. A. Little, N. S. Jones, "Highly comparative time-series % analysis: the empirical structure of time series and their methods", % J. Roy. Soc. Interface 10(83) 20130048 (2013). DOI: 10.1098/rsif.2013.0048 % % This function is free software: you can redistribute it and/or modify it under % the terms of the GNU General Public License as published by the Free Software % Foundation, either version 3 of the License, or (at your option) any later % version. % % 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/>. % ------------------------------------------------------------------------------ doPlot = 0; % whether to plot results % ------------------------------------------------------------------------------ %% Check inputs: % ------------------------------------------------------------------------------ if nargin < 2 || isempty(tau) tau = 'tau'; % set to the first minimum of autocorrelation function end N = length(y); % time-series length if strcmp(tau,'tau'), tau = CO_FirstZero(y,'ac'); if tau > N/10 tau = floor(N/10); end end % Make sure the time series is a column vector if size(y,2) > size(y,1); y = y'; end % ------------------------------------------------------------------------------ % 2-dimensional time-delay embedding: % ------------------------------------------------------------------------------ m = [y(1:end-tau), y(1+tau:end)]; % ------------------------------------------------------------------------------ % Plot the embedding: % ------------------------------------------------------------------------------ if doPlot figure('color','w'); box('on'); hold on plot(m(:,1),m(:,2),'.'); plot(m(1:min(200,end),1),m(1:min(200,end),2),'k'); end % ------------------------------------------------------------------------------ % Calculate Euclidean distances between successive points in this space, d: % ------------------------------------------------------------------------------ % d = diff(m(:,1)).^2 + diff(m(:,2)).^2; % sum of squared differences d = sqrt(diff(m(:,1)).^2 + diff(m(:,2)).^2); % Euclidean distance % Outputs statistics obtained from ordered set of distances between successive points in the recurrence space out.d_ac1 = CO_AutoCorr(d,1,'Fourier'); % Autocorrelation at lag 1 out.d_ac2 = CO_AutoCorr(d,2,'Fourier'); % Autocorrelation at lag 2 out.d_ac3 = CO_AutoCorr(d,3,'Fourier'); % Autocorrelation at lag 3 out.d_mean = mean(d); % Mean distance out.d_median = median(d); % Median distance out.d_std = std(d); % standard deviation of distances out.d_iqr = iqr(d); % Interquartile range of distances out.d_max = max(d); % Maximum distance out.d_min = min(d); % Minimum distance out.d_cv = mean(d)/std(d); % coefficient of variation of distances % ------------------------------------------------------------------------------ % Empirical distance distribution often fits Exponential distribution quite well % Fit to all values (often some extreme outliers, but oh well) l = expfit(d); nlogL = explike(l,d); out.d_expfit_nlogL = nlogL; % Sum of abs differences between exp fit and observed: % Use a histogram with automatic binning [N,binEdges] = histcounts(d,'BinMethod','auto','Normalization','probability'); binCentres = mean([binEdges(1:end-1); binEdges(2:end)]); expf = exppdf(binCentres,l); % exponential fit in each bin out.d_expfit_meandiff = mean(abs(N - expf)); % mean absolute error of fit end
@extends('layouts.dashboard') @section('content') <div class="card"> <div class="card-header"> <h3 class="card-title">Tabel Pencarian Kos</h3> </div> <!-- /.card-header --> <div class="card-body"> <table id="tableCariKos" class="table table-bordered table-striped"> <thead> <tr> <th>No.</th> <th>Nama</th> <th>Telepon</th> <th>Kampus</th> <th>Fasilitas</th> <th>Tipe</th> <th>Range Harga</th> <th>Waktu</th> <th>Status</th> <th>Keterangan</th> <th>Rating</th> <th>Review</th> <th>Hubungi</th> <th>Action</th> </tr> </thead> <tbody> @foreach ($kosSearches as $key=>$data) <tr> <td>{{ $key+1 }}</td> <td>{{ $data->customer->name }}</td> <td>{{ $data->customer->phone }}</td> <td>{{ $data->college }}</td> <td>{{ $data->facility }}</td> <td>{{ $data->type }}</td> <td>({{ number_format($data->price_min, 0, "", ".")}} - {{ number_format($data->price_max, 0, "", ".")}}) / {{ $data->payment_interval }}</td> <td>{{ $data->created_at->format('d M Y H:i') }}</td> @switch($data->status_id) @case(1) <td><button class="border-0 bg-transparent" type="button" data-bs-toggle="modal" data-bs-target="#modalStatus{{ $data->id }}"><span class="badge bg-warning">{{ $data->status->name }}</span></button></td> @break @case(2) <td><button class="border-0 bg-transparent" type="button" data-bs-toggle="modal" data-bs-target="#modalStatus{{ $data->id }}"><span class="badge bg-primary">{{ $data->status->name }}</span></button></td> @break @case(3) <td><button class="border-0 bg-transparent" type="button" data-bs-toggle="modal" data-bs-target="#modalStatus{{ $data->id }}"><span class="badge bg-success">{{ $data->status->name }}</span></button></td> @break @case(4) <td><button class="border-0 bg-transparent" type="button" data-bs-toggle="modal" data-bs-target="#modalStatus{{ $data->id }}"><span class="badge bg-secondary">{{ $data->status->name }}</span></button></td> @break @case(5) <td><button class="border-0 bg-transparent" type="button" data-bs-toggle="modal" data-bs-target="#modalStatus{{ $data->id }}"><span class="badge bg-danger">{{ $data->status->name }}</span></button></td> @break @default <td><button class="border-0 bg-transparent" type="button" data-bs-toggle="modal" data-bs-target="#modalStatus{{ $data->id }}"><span class="badge bg-danger">Unknown</span></button></td> @break @endswitch <td>{{ $data->description }}</td> @if ($data->review_id) <td> @for ($i = 0; $i < $data->review->rating; $i++) <i class="fas fa-star text-yellow"></i> @endfor </td> <td>{{ $data->review->review }}</td> @else @php $url=route('user.review.create',['service'=>1,'id'=>$data->id]) @endphp <td><a class="review-link pointer" style="cursor: pointer;color:#007bff" onclick='Copy("{{$url}}")'>Minta Rating</a></td> <td><a class="review-link pointer" style="cursor: pointer;color:#007bff" onclick='Copy("{{$url}}")'>Minta Review</a></td> @endif <td><a href="{{ route('admin.contact',$data->customer->phone) }}" target="_blank" rel="noopener noreferrer">Hubungi Customer</a></td> <td> {{-- <a href=""><button class="btn btn-primary">Edit</button></a> --}} <form action="{{ route('admin.cari_kos.destroy',$data->id) }}" method="post"> @method('delete') @csrf <button class="btn btn-danger" type="submit">Delete</button> </form> </td> </tr> <x-change_status_modal id="{{ $data->id }}" desc="{{ $data->description }}" service="cari_kos" value="{{ $data->status_id }}"></x-change_status_modal> @endforeach </tbody> </table> </div> <!-- /.card-body --> </div> @endsection @section('script') <script> $(function () { $("#tableCariKos").DataTable({ "responsive": true, "autoWidth": false, }); }); </script> <script> function Copy(url) { var dummy = document.createElement("input"); // Add it to the document document.body.appendChild(dummy); // Set its ID dummy.setAttribute("id", "dummy_id"); // Output the array into it document.getElementById("dummy_id").value=url; // Select it dummy.select(); // Copy its contents document.execCommand("copy"); // Remove it as its not needed anymore document.body.removeChild(dummy); alert('Berhasil Copy Link') } </script> @endsection
package com.example.topheadlinesappcompose.ui import android.content.Context import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.animation.EnterTransition import androidx.compose.animation.ExitTransition import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CornerSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavArgument import androidx.navigation.NavBackStackEntry import androidx.navigation.NavController import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.navigation.findNavController import androidx.navigation.navArgument import androidx.navigation.navigation import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi import com.bumptech.glide.integration.compose.GlideImage import com.example.topheadlinesappcompose.domain.model.TopHeadlinesItem import com.example.topheadlinesappcompose.presentation.navigation.SharedViewModel import com.example.topheadlinesappcompose.presentation.navigation.TopHeadlinesScreens import com.example.topheadlinesappcompose.presentation.topHeadlinesDetails.TopHeadlinesDetailsScreen import com.example.topheadlinesappcompose.ui.theme.TopHeadlinesAppComposeTheme import com.example.topheadlinesappcompose.ui.theme.nunitoFontFamilyBold import com.example.topheadlinesappcompose.presentation.topHeadlinesList.TopHeadlineViewModel import com.example.topheadlinesappcompose.presentation.topHeadlinesList.TopHeadlinesListScreen import com.example.topheadlinesappcompose.utils.Resource import com.example.topheadlinesappcompose.utils.extensions.formatDate import dagger.hilt.android.AndroidEntryPoint import java.util.Base64 @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { TopHeadlinesAppComposeTheme { val navController = rememberNavController() val backStackEntry by navController.currentBackStackEntryAsState() // A surface container using the 'background' color from the theme //Column(modifier = Modifier.fillMaxSize()) { TopHeadlinesApp() // TopAppBar(navController = navController) // NavHost( // navController = navController, // startDestination = TopHeadlinesScreens.HeadLineList.name, // enterTransition = { // EnterTransition.None // }, // exitTransition = { // ExitTransition.None // }, // popEnterTransition = { // EnterTransition.None // }, // popExitTransition = { // ExitTransition.None // } // ) { // composable(TopHeadlinesScreens.HeadLineList.name) { // TopHeadlinesListScreen( // onItemClicked = { // println("Zibah:::Navigated to next screen") // println("Zibah:::$it") // val encodedContent = Base64.getUrlEncoder().encodeToString(it?.content?.toByteArray()) // navController.navigate( // route = TopHeadlinesScreens.HeadLineDetails.name + // "?${it?.title}" + "?${it?.description}" // + "/$encodedContent" // + "?${it?.imageUrl}", //// argument = listOf( //// navArgument("title") { type = NavType.StringType }, //// navArgument("description") { type = NavType.StringType }, //// navArgument("author") { type = NavType.StringType }, //// //// ) // ) // } // ) // } // composable( // TopHeadlinesScreens.HeadLineDetails.name + "?{title}" + "?{description}" // + "/{content}" // + "?{imageUrl}", // arguments = listOf( // navArgument("title") { // type = NavType.StringType // defaultValue = "" // nullable = true // }, // navArgument("description") { // type = NavType.StringType // defaultValue = "" // nullable = true // }, // navArgument("content") { // type = NavType.StringType // }, // navArgument("imageUrl") { // type = NavType.StringType // defaultValue = "" // nullable = true // } // ) // ) { navArgument -> // val title = navArgument.arguments?.getString("title") // val desc = navArgument.arguments?.getString("description") // val content = navArgument.arguments?.getString("content") // val imgUrl = navArgument.arguments?.getString("imageUrl") // TopHeadlinesDetailsScreen(navController, // title, // desc, // imgUrl, // content // ) // } // } //buttonClick() //getTopHeadlines() // val response = TopHeadlinesItem( // "Birmingham sack Rooney after 15 games in charge", // "Birmingham sack Rooney after 15 games in charge", // "", // "", // "2024-01-02T12:22:23.4088451Z", // "") // val item = arrayListOf<TopHeadlinesItem>() // while (item.size != 10){ // item.add(response) // } // TopHeadLineList(topHeadlinesItem = item) } } } } //} @Composable fun TopHeadlinesApp(navController: NavHostController = rememberNavController()) { // Get current back stack entry val backStackEntry by navController.currentBackStackEntryAsState() // Get the name of the current screen val currentScreen = TopHeadlinesScreens.valueOf( backStackEntry?.destination?.route?: TopHeadlinesScreens.HeadLineList.name ) Scaffold( topBar = { TopAppBar( currentScreen = currentScreen, canNavigateBack = navController.previousBackStackEntry != null, navigateUp = { navController.navigateUp() } ) } ) { innerPadding -> NavHost( navController = navController, startDestination = "topheadlines", enterTransition = { EnterTransition.None }, exitTransition = { ExitTransition.None }, popEnterTransition = { EnterTransition.None }, popExitTransition = { ExitTransition.None }, modifier = Modifier.padding(innerPadding) ) { navigation( startDestination = TopHeadlinesScreens.HeadLineList.name, route = "topheadlines" ) { composable(TopHeadlinesScreens.HeadLineList.name) { backStackEntry -> val getViewModel = backStackEntry.sharedViewModel<SharedViewModel>(navController) TopHeadlinesListScreen(onItemClicked = { getViewModel.getHeadlineDetails(it) navController.navigate( TopHeadlinesScreens.HeadLineDetails.name ) }) } composable(TopHeadlinesScreens.HeadLineDetails.name) {backStackEntry -> val getViewModel = backStackEntry.sharedViewModel<SharedViewModel>(navController) val state by getViewModel.headLineItem.collectAsStateWithLifecycle() TopHeadlinesDetailsScreen( state) } } // composable(TopHeadlinesScreens.HeadLineList.name) { // TopHeadlinesListScreen( // onItemClicked = { // println("Zibah:::Navigated to next screen") // println("Zibah:::$it") // // navController.currentBackStackEntry?.savedStateHandle?.set("data", it) // val encodedContent = Base64.getUrlEncoder().encodeToString(it?.content?.toByteArray()) // navController.navigate( // route = TopHeadlinesScreens.HeadLineDetails.name + // "?${it?.title}" + "?${it?.description}" // + "/$encodedContent" // + "?${it?.imageUrl}", //// argument = listOf( //// navArgument("title") { type = NavType.StringType }, //// navArgument("description") { type = NavType.StringType }, //// navArgument("author") { type = NavType.StringType }, //// //// ) // ) // } // ) // } // composable( // TopHeadlinesScreens.HeadLineDetails.name + "?{title}" + "?{description}" // + "/{content}" // + "?{imageUrl}", // arguments = listOf( // navArgument("title") { // type = NavType.StringType // defaultValue = "" // nullable = true // }, // navArgument("description") { // type = NavType.StringType // defaultValue = "" // nullable = true // }, // navArgument("content") { // type = NavType.StringType // }, // navArgument("imageUrl") { // type = NavType.StringType // defaultValue = "" // nullable = true // } // ) // ) { navArgument -> //// LaunchedEffect(key1 = navArgument){ //// val result = navController.previousBackStackEntry.savedStateHandle.get<TopHeadlinesItem>( //// "data" //// ) //// } // // val title = navArgument.arguments?.getString("title") // val desc = navArgument.arguments?.getString("description") // val content = navArgument.arguments?.getString("content") // val imgUrl = navArgument.arguments?.getString("imageUrl") // TopHeadlinesDetailsScreen(navController, // title, // desc, // imgUrl, // content // ) // } } } } @Composable inline fun <reified T : ViewModel> NavBackStackEntry.sharedViewModel( navController: NavHostController, ): T { val navGraphRoute = destination.parent?.route ?: return hiltViewModel() val parentEntry = remember(this) { navController.getBackStackEntry(navGraphRoute) } return hiltViewModel(parentEntry) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun TopAppBar( currentScreen: TopHeadlinesScreens, canNavigateBack: Boolean, navigateUp: () -> Unit, modifier: Modifier = Modifier ) { CenterAlignedTopAppBar( title = { Text( text = "BBC NEWS", color = Color.White, fontWeight = FontWeight.Bold ) }, colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = Color.Black, titleContentColor = Color.White ), modifier = modifier, navigationIcon = { // val backStackEntry = navController.previousBackStackEntry // println("Zibah:: BACK $backStackEntry") if (canNavigateBack) { IconButton( onClick = navigateUp ) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = "back", tint = Color.White ) } } } ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { TopHeadlinesAppComposeTheme { // TopHeadLinesItemComposable(topHeadlinesItem = TopHeadlinesItem( // "Birmingham sack Rooney after 15 games in charge", // "Birmingham sack Rooney after 15 games in charge", // "", // "", // "2024-01-02T12:22:23.4088451Z", // "") ) } }
import { AvatarConfig, ResponseStatus } from '@/types/main'; import { Prisma, User } from '@prisma/client'; export const apiRoot = !process.env.NODE_ENV || process.env.NODE_ENV === 'development' ? 'http://localhost:3000/api' : 'https://phishingphun.com/api'; export const attemptLoginClient = ( username: string, password: string ): Promise<User | ResponseStatus.NotFound | ResponseStatus.UnknownError> => { return new Promise(async (resolve) => { try { const response = await fetch(`${apiRoot}/users/login`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify({ username, password }), }); if (response.status === 200) { // success const data = await response.json(); if (data.hasOwnProperty('user')) { resolve(data.user as User); } else { resolve(ResponseStatus.UnknownError); } } else if (response.status === 404) { // incorrect username (username not found) resolve(ResponseStatus.NotFound); } else { resolve(ResponseStatus.UnknownError); } } catch { resolve(ResponseStatus.UnknownError); } }); }; export const attemptSignupClient = ( username: string, password: string, email: string ): Promise<User | 'name conflict' | 'email conflict' | ResponseStatus.UnknownError> => { return new Promise(async (resolve) => { try { const response = await fetch(`${apiRoot}/users/signup`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify({ username, password, email }), }); if (response.status === 200) { // success const data = await response.json(); if (data.hasOwnProperty('user')) { resolve(data.user as User); } else { resolve(ResponseStatus.UnknownError); } } else if (response.status === ResponseStatus.Conflict) { const { error } = await response.json(); resolve(error === 'name conflict' || error === 'email conflict' ? error : ResponseStatus.UnknownError); } else { resolve(ResponseStatus.UnknownError); } } catch { resolve(ResponseStatus.UnknownError); } }); }; export const updateAvatarForUser = ( userId: number, config: AvatarConfig ): Promise<User | ResponseStatus.Unauthorized | ResponseStatus.UnknownError> => { return new Promise(async (resolve) => { try { const response = await fetch(`${apiRoot}/users/${userId}/avatar`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify(config), }); if (response.ok || response.status === 200) { const data = await response.json(); if (data.hasOwnProperty('user')) { resolve(data.user); } else { resolve(ResponseStatus.UnknownError); } } else if (response.status === 401) { // incorrect username (username not found) resolve(ResponseStatus.Unauthorized); } else { resolve(ResponseStatus.UnknownError); } } catch { resolve(ResponseStatus.UnknownError); } }); }; export const updateUser = ( userId: number, userData: Prisma.UserUpdateInput ): Promise<User | ResponseStatus.Unauthorized | ResponseStatus.UnknownError> => { return new Promise(async (resolve) => { try { const response = await fetch(`${apiRoot}/users/${userId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify(userData), }); if (response.ok || response.status === 200) { const data = await response.json(); if (data.hasOwnProperty('user')) { resolve(data.user); } else { resolve(ResponseStatus.UnknownError); } } else if (response.status === 401) { resolve(ResponseStatus.Unauthorized); } else { resolve(ResponseStatus.UnknownError); } } catch { resolve(ResponseStatus.UnknownError); } }); };
import React, { useEffect, useState } from "react"; import { StyleSheet, View, TouchableWithoutFeedback, Text, FlatList } from "react-native"; import { Searchbar, ActivityIndicator } from "react-native-paper"; import axios from "axios"; import { AntDesign } from "@expo/vector-icons" import { useNavigation, useRoute } from "@react-navigation/native"; import { baseUrl } from "../../api/const"; import ProductList from "../productList"; const CustomButton = ({ title, onPress }) => { return ( <TouchableWithoutFeedback onPress={onPress}> <View style={styles.buttonContainer}> <View style={styles.buttonContent}> <AntDesign name="left" size={20} color="black" /> <Text style={styles.buttonText}>{title}</Text> </View> </View> </TouchableWithoutFeedback> ); }; const searchUrl = `${baseUrl}/viewProducts?product_name=`; const ProductScreen = () => { const [offset, setOffset] = useState(0); const [loadingMore, setLoadingMore] = useState(false); const [productNames, setProductNames] = useState([]); const [searchQuery, setSearchQuery] = useState(""); const [filteredProducts, setFilteredProducts] = useState([]); const renderLoader = () => { return ( <View style={styles.loaderStyle}> <ActivityIndicator size="large" color="#ffa600" /> </View> ); }; const loadMoreItem = () => { console.log("y first u load : ", loadingMore) if (loadingMore) return; // Prevent multiple calls while loading setLoadingMore(true); setOffset(offset + 1); }; console.log("offset:", offset) const route = useRoute() const contact = route.params?.contact // without ? getting errors const category = route.params?.category; console.log("route---:", route) // const{ contact }=route.params; const numColumns = 2; const navigation = useNavigation(); const productUrl = category ? `${baseUrl}/viewProducts?product_name=${category}` : `${baseUrl}/viewProducts`; useEffect(() => { fetchProducts() }, [offset]) const fetchProducts = () => { axios .get(`${productUrl}?offset=${offset}&limit=20`) .then((res) => { const productNamesArr = res.data.data.map((item) => ({ _id: item._id, productName: item.product_name, imageUrl: item.image_url, productCost: item.cost, })); setProductNames((prevProductNames) => [...prevProductNames, ...productNamesArr]); setLoadingMore(false); }) .catch((err) => console.log(err)); }; useEffect(() => { if (searchQuery !== "") { axios.get(searchUrl + searchQuery) .then((res) => { const filteredSearchResults = res.data.data.map((item) => ({ _id: item._id, productName: item.product_name, productCost: item.cost })); setFilteredProducts(filteredSearchResults); }) .catch(err => console.log(err)); } else { setFilteredProducts(productNames); } }, [searchQuery, productNames]); //on chaging search test const onChangeSearch = (query) => { setSearchQuery(query); }; return ( <View style={styles.container}> <View> <CustomButton title="Products" onPress={() => navigation.goBack()} /> </View> <View style={styles.searchContainer}> <Searchbar placeholder="Search Products" value={searchQuery} onChangeText={onChangeSearch} style={styles.searchBox} /> </View> <View style={styles.productListContainer}> <FlatList data={filteredProducts} keyExtractor={(item) => item._id} renderItem={({ item }) => <ProductList item={item} contact={contact} />} numColumns={numColumns} ListFooterComponent={renderLoader} onEndReached={loadMoreItem} onEndReachedThreshold={0} /> </View> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, }, searchBox: { borderRadius: 12, borderWidth: 1, borderColor: '#ffa600', backgroundColor: "white", marginBottom: 10, }, buttonContainer: { backgroundColor: "#ffa600", }, buttonContent: { flexDirection: "row", marginLeft: 10, marginBottom: 12, alignItems: "center" }, buttonText: { marginLeft: 34, fontSize: 17, color: "white" }, searchContainer: { backgroundColor: "#ffa600", paddingHorizontal: 10, }, productListContainer: { alignItems: "center", flex: 1, }, loaderStyle: { marginVertical: 16, alignItems: "center", justifyContent: "center", } }); export default ProductScreen;
<?php namespace App\Models; use App\Services\MedicalService; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder; use Illuminate\Support\Facades\DB; class ControlPointModel extends Model { use HasFactory; protected $table = 'control_points'; protected $connection = 'mysql'; private MedicalService $medicalService; public function __construct() { $this->medicalService = new MedicalService(); parent::__construct(); } public function createControlPoint(): void { foreach ($this->medicalService->getControlPoints() as $controlPoint) { $this->getTable() ->updateOrInsert( [ 'TherapyID' => $controlPoint['TherapyID'], 'ElapsedTime' => intval($controlPoint['ElapsedTime']), 'UnitMeasurement' => $controlPoint['UnitMeasurement'], 'Symptom' => $controlPoint['Symptom'], ], [ 'ID' => $controlPoint['ID'], 'ValueSymptom' => $controlPoint['ValueSymptom'] ] ); } } public function getNeedCorrection(array $symptoms, int $pastDays, int $pastHours): bool { foreach ($symptoms as $symptom) { $controlSymptoms = $this->getTable() ->where('TherapyID', $symptom['TherapyID']) ->where('Symptom', $symptom['Symptom']) ->get(['ElapsedTime', 'UnitMeasurement', 'ValueSymptom']) ->all(); if (!empty($controlSymptoms)) { $elapsedTime = null; foreach ($controlSymptoms as $controlSymptom) { if ($symptom['TypeValue'] !== 'enumerable') { $isInRange = $symptom['ValueSymptom'] <= $controlSymptom->ValueSymptom[0] && $symptom['ValueSymptom'] >= $controlSymptom->ValueSymptom[1]; if ($controlSymptom->UnitMeasurement === 'час') { if (empty($elapsedTime)) { $elapsedTime = $this->getElapsedTime($controlSymptoms, $pastHours); } } else { if (empty($elapsedTime)) { $elapsedTime = $this->getElapsedTime($controlSymptoms, $pastDays); } } if ($elapsedTime && $controlSymptom->ElapsedTime === $elapsedTime && $isInRange) { return true; } } } } else break; } return false; } private function getElapsedTime(array $controlSymptoms, int $time): int { $timeIntervals = []; foreach ($controlSymptoms as $controlSymptom) { $timeIntervals[] = $controlSymptom->ElapsedTime; } for ($interval = 0; $interval < count($timeIntervals); $interval++) { if (!isset($timeIntervals[$interval + 1])) { if ($time >= $timeIntervals[$interval]) { return $timeIntervals[$interval]; } } else { if ($time >= $timeIntervals[$interval] && $time < $timeIntervals[$interval + 1]) { return $timeIntervals[$interval]; } } } return 0; } public function getTable(): Builder { return DB::table($this->table); } }
import React from "react"; import HourlyForecast from "./HourlyForecast.js"; import WeatherInformation from "./WeatherInformation.js"; import unknown from "./weather-icons/unknown.svg"; import { useState } from "react"; import clear from "./weather-icons/clear.svg"; import cloudy from "./weather-icons/cloudy.svg"; import fog from "./weather-icons/fog.svg"; import rain from "./weather-icons/rain.svg"; import storm from "./weather-icons/storm.svg"; const api = { key: "b3b3d26caa5c057ee0ae12c8707572e4", base: "https://api.openweathermap.org/data/2.5/", }; function App() { const [search, setSearch] = useState(""); const [forecast, setforecast] = useState({}); const searchPressed = (e) => { e.preventDefault(); fetch(`${api.base}forecast?q=${search}&units=metric&APPID=${api.key}`) .then((res) => res.json()) .then((result) => { setforecast(result); console.log(result); }) .catch((error) => { console.error('Error fetching weather data:', error); }); }; const dateBuilder = (d) => { let months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; let days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", ]; let day = days[d.getDay()]; let date = d.getDate(); let month = months[d.getMonth()]; let year = d.getFullYear(); return `${day} ${date} ${month} ${year}`; }; function images(i) { switch (i) { case "Clear": return clear; case "Clouds": return cloudy; case "Rain": return rain; case "Storm": return storm; case "Fog": return fog; default: return unknown; } } return ( <div className="App"> <header> <form className="searching_form"> <img src={clear} className="logo_svg" /> <input type="text" className="searching_box" placeholder="Type a city here..." onChange={(e) => setSearch(e.target.value)} /> <button className="submit_btn" onClick={searchPressed}> Search </button> </form> </header> <hr className="line" /> <div class="container"> {typeof forecast.list!=="undefined" ? ( <div className="main"> <p className="main_title" id="country"> {forecast.city.name} </p> <img src={images(forecast.list[0].weather[0].main)} className="main_svg" alt="weather icon" /> <div className="main_info"> <div className="main_day" id="date"> {dateBuilder(new Date())} </div> <p className="main_visibity"> {forecast.list[0].weather[0].main}</p> <p className="main_temperature">{forecast.list[0].main.temp} &#176;C</p> </div> </div> ) : ( <div> <div className="main"> <p className="main_title" id="country"> Loading... </p> <img src={unknown} className="main_svg" alt="weather icon" /> <div className="main_info"> <div className="main_day" id="date"> Date </div> <p className="main_visibility">Visibility</p> <p className="main_temperature">Degree</p> </div> </div> </div> )} {typeof forecast.list!== "undefined" ? ( <WeatherInformation feelslike={forecast.list[0].main.feels_like} humidity={forecast.list[0].main.humidity} pressure={forecast.list[0].main.pressure} wind={forecast.list[0].wind.speed} /> ) : ( <WeatherInformation feelslike="" humidity="" pressure="" wind="" /> )} </div> {console.log(forecast.main)} <div className="hourly-forecast"> <h2 className="hourly-h2">Hourly Forecast</h2> <div class="hourly-grid"> {forecast.list ? ( forecast.list.slice(0, 8).map((hourlyData, index) => ( <HourlyForecast key={index} time={hourlyData.dt_txt.split(' ')[1]} icon={ images(hourlyData.weather[0].main)} temperature={hourlyData.main.temp} /> )) ) : ( <p>Loading Hourly Forecast...</p> )} </div> </div> </div> ); } export default App;
import 'dart:math'; import 'package:svart/svart.dart'; class RegisterFileUnit extends Module { RegisterFileUnit( Var clock, Var write, Var address, Var inputData, { int actualRegisterAddressSpace = 7, super.instanceName, }) : super(definitionName: 'register_file_unit') { clock = addInput('clock', clock); write = addInput('write', write); address = addInput('address', address, width: 7); inputData = addInput('input_data', inputData, width: 8); outputData = addOutput('output_data', width: 8); final registers = List.generate(pow(2, actualRegisterAddressSpace).toInt(), (index) { return addInternal(name: 'register_$index', width: 8); }); final readIffs = <Iff>[]; final writeIffs = <Iff>[]; for (var i = 0; i < registers.length; ++i) { readIffs.add( Iff( address.eq(Const(i, width: address.width)), then: [outputData.assign(registers[i])], ), ); writeIffs.add( Iff( address.eq(Const(i, width: address.width)), then: [registers[i].assign(inputData)], ), ); } addCombinational([When(readIffs)]); addSyncSequential(PosEdge(clock), [ If(write, then: [When(writeIffs)]), ]); } late final Var outputData; } String main({bool noPrint = false}) { final systemverilog = RegisterFileUnit( Var(), Var(), Var(width: 7), Var(width: 8), actualRegisterAddressSpace: 3, ).emit(); if (!noPrint) { // ignore: avoid_print print(systemverilog); } return systemverilog; }
import requests import xml.etree.ElementTree as ET import csv import pandas as pd import plotly.graph_objects as go from scipy import stats import matplotlib.pyplot as plt import numpy as np url = "https://www.opec.org/basket/basketDayArchives.xml" try: # Odešleme HTTP požadavek GET a získáme odpověď response = requests.get(url) # Zkontrolujeme, zda byl požadavek úspěšný (status code 200 značí úspěch) if response.status_code == 200: # Vytvoříme objekt ElementTree pro analýzu XML root = ET.fromstring(response.content) # Vytvoříme CSV soubor pro zápis dat with open("data.csv", "w", newline="") as csv_file: writer = csv.writer(csv_file) # Zde specifikujte logiku pro extrakci dat z XML a zápis do CSV for basket_list in root.findall(".//{http://tempuri.org/basketDayArchives.xsd}BasketList"): data = basket_list.get("data") val = basket_list.get("val") # Zápis dat do CSV souboru writer.writerow([data, val]) print("Data byla uložena do souboru data.csv.") else: print("Nepodařilo se stáhnout data.") except Exception as e: print("Došlo k chybě při zpracování XML:", str(e)) try: df = pd.read_csv("data.csv", header=None) df.columns = ["data", "val"] # Vytvoření sloupce s procentuálním denním pohybem df["DailyChange"] = df["val"].pct_change() * 100 # Vytvoření sloupce s procentuálním vývojem ceny df["PriceChange"] = (df["val"] - df["val"].iloc[0]) / df["val"].iloc[0] * 100 df.to_csv("data_with_changes.csv", index=False) print("Data byla uložena do souboru data_with_changes.csv.") except Exception as e: print("Došlo k chybě při zpracování dat:", str(e)) fig1 = go.Figure() fig1.add_trace(go.Scatter(x=df['data'], y=df['PriceChange'], mode='lines', name='Price Change')) fig1.update_layout(title='Procentuální vývoj ceny', xaxis_title='Datum', yaxis_title='Procentuální změna ceny') fig1.write_image('price_change.png') # Grafy s procentuálním vývojem ceny po letech years = df['data'].str.split('-').str[0].unique() for year in years: df_year = df[df['data'].str.startswith(year)] fig = go.Figure() fig.add_trace(go.Scatter(x=df_year['data'], y=df_year['PriceChange'], mode='lines', name='Price Change')) fig.update_layout(title=f'Procentuální vývoj ceny - {year}', xaxis_title='Datum', yaxis_title='Procentuální změna ceny') fig.write_image(f'price_change_{year}.png') df = pd.read_csv("data_with_changes.csv") df["data"] = pd.to_datetime(df["data"]) df_result = df.groupby(pd.Grouper(key="data", freq="Y"))["DailyChange"].apply(lambda x: stats.gmean(x.dropna() + 100) - 100).reset_index() df_result.columns = ["Year", "GeometricMean"] df_result["Year"] = df_result["Year"].dt.year df_result.to_csv("average_daily_change.csv", index=False) grouped_df = pd.read_csv("average_daily_change.csv") # Vytvoření sloupcového grafu plt.bar(grouped_df["Year"], grouped_df["GeometricMean"]) # Nastavení popisků os a názvu grafu plt.xlabel("Year") plt.ylabel("Average Daily Change") plt.title("Average Daily Change by Year") plt.show()
import React, { useState } from 'react'; import { Button, TextField } from '@mui/material'; import fetchApi from '../utils/fetchApi'; import { useNavigate } from 'react-router-dom'; import { SubmitHandler, useForm } from 'react-hook-form'; import { LoginInterface } from '../interfaces/login.interface'; import { Cookie } from '../utils/cookies'; import { useDispatch } from 'react-redux'; import { assignUser } from '../reducers/user.reducer'; import SnackbarBox from '../components/SnackbarBox'; function Login() { const { register, formState: { errors }, handleSubmit, } = useForm<LoginInterface>(); const [isError, setIsError] = useState(false); const navigate = useNavigate(); const dispatch = useDispatch(); const onSubmitLogin: SubmitHandler<LoginInterface> = async (data) => { await fetchApi('/auth/login', 'POST', data) .then((response) => { onSuccessCallback(response); }) .catch((error) => { onErrorCallback(); }); }; const onSuccessCallback = (response: any) => { dispatch(assignUser(response)); Cookie.setCookies(response.token); navigate('/'); }; const onErrorCallback = () => { setIsError(true); setTimeout(() => { setIsError(false); }, 1000); }; return ( <div className='login'> <div className='login-card'> <p className='title'>Welcome</p> <p className='sub-title'>Please enter email and password</p> <form className='login-form' onSubmit={handleSubmit(onSubmitLogin)}> <TextField className='text-field' id='email' label='Email' variant='outlined' {...register('email', { required: true })} error={errors?.email && true} helperText={errors?.email && 'This field is required'} /> <TextField className='text-field' id='password' type={'password'} label='Password' variant='outlined' {...register('password', { required: true })} error={errors?.password && true} helperText={errors?.password && 'This field is required'} /> <Button variant='contained' disableElevation type='submit'> Submit </Button> </form> {isError && ( <SnackbarBox show={isError} message='Email and password is not correct.' severity='error' /> )} </div> </div> ); } export default Login;
import { FiAlertCircle } from "react-icons/fi"; import ActionButton from "./ActionButton"; import Modal from "./Modal"; export default function ErrorModal({ title, message, primaryButtonLabel, onPrimaryButtonClick, onClose, }: { title: string; message: string; primaryButtonLabel: string; onPrimaryButtonClick?: () => void; onClose: () => void; }): JSX.Element { return ( <Modal isOpen onClose={onClose}> <div className="flex flex-col items-center mt-6 mb-14"> <FiAlertCircle className="text-8xl text-error ml-1" /> <span className="font-bold text-2xl text-dark-900 mt-12">{title}</span> <div className="w-full text-dark-900 text-center break-word mt-2 px-[29px]"> {message} </div> <span className="pt-12"> <ActionButton label={primaryButtonLabel} customStyle="md:px-6 text-xg lg:!py-3 lg:px-8 xl:px-14" onClick={onPrimaryButtonClick} /> <ActionButton label="Close" variant="secondary" customStyle="mt-2 md:px-2.5 lg:text-xl lg:!py-3 lg:px-8 xl:px-14" onClick={onClose} /> </span> </div> </Modal> ); }
import { memo } from "react"; import { IMessage } from "../../services/ChatService/types"; import "./ChatMessage.scss"; const formatDate = (dateStr: string): string => { const date: Date = new Date(dateStr); return `${String(date.getHours()).padStart(2, "0")}:${String( date.getMinutes(), ).padStart(2, "0")}`; }; // react-virtuoso seems to have problems with vertical margins calculation, so I added spacer // instead of specifing margin-bottom on ChatMessage export const ChatMessage = memo( ({ message, style }: { message: IMessage; style?: object }) => { return ( <> <div className="ChatMessage" {...style}> <div className="ChatMessage__author">{message.user_name}</div> <div className="ChatMessage__text">{message.message}</div> <div className="ChatMessage__date"> {formatDate(message.send_date)} </div> </div> <div className="spacer"></div> </> ); }, );
#include <stdio.h> #include <stdlib.h> #include <math.h> int isPrime(int x); int isGcd1(int x); int is2mod5(int x); int modulo_pow(int base, int exponent, int modulo); void swap(int* a, int* b); int gcd(int a, int b); int main(void){ int x; int p, q, r; /*printf("Hvilket heltal vil du tjekke?\n"); scanf("%d", &x); printf("x er %d\n", x);*/ for (x = 100000; x <= 1000000; x++) { p = isPrime(x); q = isGcd1(x); r = is2mod5(x); if ((p && !r) || !(p || !q || r) || (!p && !q && r)){ printf("Du fandt et x\n"); printf("p er %d, q er %d, and r er %d og x er %d\n", p,q,r,x); } } return 0; } /* Denne funktion skal returnere 1 hvis x er et primtal og 0 ellers */ int isPrime(int x){ int res = 1; int max = (int) sqrt(x); if (x % 2 == 0) { res = 0; } else { int i; for (i = 3; i <= max; i+=2) { if (x % i == 0) res = 0; } } return res; } /* Denne funktion skal returnere 1 hvis gcd(x,2)=1 og 0 ellers */ int isGcd1(int x){ return gcd(x, 2) == 1 ? 1 : 0; } /* swap the values of a and b with pointers */ void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } /* find the gcd of a and b */ int gcd(int a, int b) { int remainder; /* if a is bigger than b then swap their values */ if (a > b) { swap(&a, &b); } /* run the algorithm to find gcd */ while (a > 0){ remainder = b % a; b = a; a = remainder; } /* return gcd */ return b; } /* Denne funktion skal returnere 1 hvis 9^x-2 mod 5 = 2 og 0 ellers */ int is2mod5(int x){ return (modulo_pow(9, x, 5) == 4) ? 1 : 0; } int modulo_pow(int base, int exponent, int modulo) { if (modulo == 1) return 0; int c = 1; int e_prime = 0; for (;;) { e_prime++; c = (base * c) % modulo; if (e_prime >= exponent) return c; } }
--- *mini.extra* Extra 'mini.nvim' functionality --- *MiniExtra* --- --- MIT License Copyright (c) 2023 Evgeni Chasnovski --- --- --- Extra useful functionality which is not essential enough for other 'mini.nvim' --- modules to include directly. --- --- Features: --- --- - Various pickers for 'mini.pick': --- - Built-in diagnostic (|MiniExtra.pickers.diagnostic()|). --- - File explorer (|MiniExtra.pickers.explorer()|). --- - Git branches/commits/files/hunks (|MiniExtra.pickers.git_hunks()|, etc.). --- - Command/search/input history (|MiniExtra.pickers.history()|). --- - LSP references/symbols/etc. (|MiniExtra.pickers.lsp()|). --- - Tree-sitter nodes (|MiniExtra.pickers.treesitter()|). --- - And much more. --- See |MiniExtra.pickers| for more. --- --- - Various textobject specifications for 'mini.ai'. See |MiniExtra.gen_ai_spec|. --- --- - Various highlighters for 'mini.hipatterns'. See |MiniExtra.gen_highlighter|. --- --- Notes: --- - This module requires only those 'mini.nvim' modules which are needed for --- a particular functionality: 'mini.pick' for pickers, etc. --- --- # Setup ~ --- --- This module needs a setup with `require('mini.extra').setup({})` (replace --- `{}` with your `config` table). It will create global Lua table `MiniExtra` --- which you can use for scripting or manually (with `:lua MiniExtra.*`). --- --- See |MiniExtra.config| for `config` structure and default values. --- --- This module doesn't have runtime options, so using `vim.b.miniextra_config` --- will have no effect here. --- --- # Comparisons ~ --- --- - 'nvim-telescope/telescope.nvim': --- - With |MiniExtra.pickers|, 'mini.pick' is reasonably on par when it comes --- to built-in pickers. --- --- - 'ibhagwan/fzf-lua': --- - Same as 'nvim-telescope/telescope.nvim'. ---@diagnostic disable:undefined-field ---@diagnostic disable:discard-returns ---@diagnostic disable:unused-local ---@diagnostic disable:cast-local-type ---@diagnostic disable:undefined-doc-name ---@diagnostic disable:luadoc-miss-type-name ---@alias __extra_ai_spec_return function Function implementing |MiniAi-textobject-specification|. ---@alias __extra_pickers_local_opts table|nil Options defining behavior of this particular picker. ---@alias __extra_pickers_opts table|nil Options forwarded to |MiniPick.start()|. ---@alias __extra_pickers_return any Output of the called picker. ---@alias __extra_pickers_git_notes Notes: --- - Requires executable `git`. --- - Requires target path to be part of git repository. --- - Present for exploration and navigation purposes. Doing any Git operations --- is suggested to be done in a dedicated Git client and is not planned. ---@alias __extra_pickers_git_path - <path> `(string|nil)` - target path for Git operation (if required). Also --- used to find Git repository inside which to construct items. --- Default: `nil` for root of Git repository containing |current-directory|. local MiniExtra = {} local H = {} --- Module setup --- ---@param config table|nil Module config table. See |MiniExtra.config|. --- ---@usage `require('mini.extra').setup({})` (replace `{}` with your `config` table). MiniExtra.setup = function(config) -- Export module _G.MiniExtra = MiniExtra -- Setup config config = H.setup_config(config) -- Apply config H.apply_config(config) end --stylua: ignore --- Module config --- --- Default values: ---@eval return MiniDoc.afterlines_to_code(MiniDoc.current.eval_section) MiniExtra.config = {} --minidoc_afterlines_end --- 'mini.ai' textobject specification generators --- --- This is a table with function elements. Call to actually get specification. --- --- Assumed to be used as part of |MiniAi.setup()|. Example: > --- --- local gen_ai_spec = require('mini.extra').gen_ai_spec --- require('mini.ai').setup({ --- custom_textobjects = { --- B = gen_ai_spec.buffer(), --- D = gen_ai_spec.diagnostic(), --- I = gen_ai_spec.indent(), --- L = gen_ai_spec.line(), --- N = gen_ai_spec.number(), --- }, --- }) MiniExtra.gen_ai_spec = {} --- Current buffer textobject --- --- Notes: --- - `a` textobject selects all lines in a buffer. --- - `i` textobject selects all lines except blank lines at start and end. --- ---@return __extra_ai_spec_return MiniExtra.gen_ai_spec.buffer = function() return function(ai_type) local start_line, end_line = 1, vim.fn.line('$') if ai_type == 'i' then -- Skip first and last blank lines for `i` textobject local first_nonblank, last_nonblank = vim.fn.nextnonblank(start_line), vim.fn.prevnonblank(end_line) -- Do nothing for buffer with all blanks if first_nonblank == 0 or last_nonblank == 0 then return { from = { line = start_line, col = 1 } } end start_line, end_line = first_nonblank, last_nonblank end local to_col = math.max(vim.fn.getline(end_line):len(), 1) return { from = { line = start_line, col = 1 }, to = { line = end_line, col = to_col } } end end --- Current buffer diagnostic textobject --- --- Notes: --- - Both `a` and `i` textobjects return |vim.diagnostic.get()| output for the --- current buffer. It is modified to fit |MiniAi-textobject-specification|. --- ---@param severity any Which severity to use. Forwarded to |vim.diagnostic.get()|. --- Default: `nil` to use all diagnostic entries. --- ---@return __extra_ai_spec_return MiniExtra.gen_ai_spec.diagnostic = function(severity) return function(ai_type) local cur_diag = vim.diagnostic.get(0, { severity = severity }) local regions = {} for _, diag in ipairs(cur_diag) do local from = { line = diag.lnum + 1, col = diag.col + 1 } local to = { line = diag.end_lnum + 1, col = diag.end_col } if to.line == nil or to.col == nil then to = { line = diag.lnum + 1, col = diag.col + 1 } end table.insert(regions, { from = from, to = to }) end return regions end end --- Current buffer indent scopes textobject --- --- Indent scope is a set of consecutive lines with the following properties: --- - Lines above first and below last are non-blank. They are called borders. --- - There is at least one non-blank line in a set. --- - All non-blank lines between borders have strictly greater indent --- (perceived leading space respecting |tabstop|) than either of borders. --- --- Notes: --- - `a` textobject selects scope including borders. --- - `i` textobject selects the scope charwise. --- - Differences with |MiniIndentscope.textobject|: --- - This textobject always treats blank lines on top and bottom of `i` --- textobject as part of it, while 'mini.indentscope' can configure that. --- - This textobject can select non-covering scopes, while 'mini.indentscope' --- can not (by design). --- - In this textobject scope computation is done only by "casting rays" from --- top to bottom and not in both ways as in 'mini.indentscope'. --- This works in most common scenarios and doesn't work only if indent of --- of the bottom border is expected to be larger than the top. --- ---@return function Function implementing |MiniAi-textobject-specification|. --- It returns array of regions representing all indent scopes in the buffer --- ordered increasingly by the start line. MiniExtra.gen_ai_spec.indent = function() return H.ai_indent_spec end --- Current line textobject --- --- Notes: --- - `a` textobject selects whole line. --- - `i` textobject selects line after initial indent. --- ---@return __extra_ai_spec_return MiniExtra.gen_ai_spec.line = function() return function(ai_type) local line_num = vim.fn.line('.') local line = vim.fn.getline(line_num) -- Ignore indentation for `i` textobject local from_col = ai_type == 'a' and 1 or (line:match('^(%s*)'):len() + 1) -- Don't select `\n` past the line to operate within a line local to_col = line:len() return { from = { line = line_num, col = from_col }, to = { line = line_num, col = to_col } } end end --- Number textobject --- --- Notes: --- - `a` textobject selects a whole number possibly preceded with "-" and --- possibly followed by decimal part (dot and digits). --- - `i` textobject selects consecutive digits. --- ---@return __extra_ai_spec_return MiniExtra.gen_ai_spec.number = function() local digits_pattern = '%f[%d]%d+%f[%D]' local find_a_number = function(line, init) -- First find consecutive digits local from, to = line:find(digits_pattern, init) if from == nil then return nil, nil end -- Make sure that these digits were not processed before. This can happen -- because 'miin.ai' does next with `init = from + 1`, meaning that -- "-12.34" was already matched, then it would try to match starting from -- "1": we want to avoid matching that right away and avoid matching "34" -- from this number. if from == init and line:sub(from - 1, from - 1) == '-' then init = to + 1 from, to = line:find(digits_pattern, init) end if from == nil then return nil, nil end if line:sub(from - 2):find('^%d%.') ~= nil then init = to + 1 from, to = line:find(digits_pattern, init) end if from == nil then return nil, nil end -- Match the whole number with minus and decimal part if line:sub(from - 1, from - 1) == '-' then from = from - 1 end local dec_part = line:sub(to + 1):match('^%.%d+()') if dec_part ~= nil then to = to + dec_part - 1 end return from, to end return function(ai_type) if ai_type == 'i' then return { digits_pattern } end return { find_a_number, { '^().*()$' } } end end --- 'mini.hipatterns' highlighter generators --- --- This is a table with function elements. Call to actually get specification. --- --- Assumed to be used as part of |MiniHipatterns.setup()|. Example: > --- --- local hi_words = require('mini.extra').gen_highlighter.words --- require('mini.hipatterns').setup({ --- highlighters = { --- todo = hi_words({ 'TODO', 'Todo', 'todo' }, 'MiniHipatternsTodo'), --- }, --- }) MiniExtra.gen_highlighter = {} --- Highlight words --- --- Notes: --- - Words should start and end with alphanumeric symbol (latin letter or digit). --- - Words will be highlighted only in full and not if part bigger word, i.e. --- there should not be alphanumeric symbol before and after it. --- ---@param words table Array of words to highlight. Will be matched as is, not --- as Lua pattern. ---@param group string|function Proper `group` field for `highlighter`. --- See |MiniHipatterns.config|. ---@param extmark_opts any Proper `extmark_opts` field for `highlighter`. --- See |MiniHipatterns.config|. MiniExtra.gen_highlighter.words = function(words, group, extmark_opts) if not vim.tbl_islist(words) then H.error('`words` should be an array.') end if not (type(group) == 'string' or vim.is_callable(group)) then H.error('`group` should be string or callable.') end local pattern = vim.tbl_map(function(x) if type(x) ~= 'string' then H.error('All elements of `words` should be strings.') end return '%f[%w]()' .. vim.pesc(x) .. '()%f[%W]' end, words) return { pattern = pattern, group = group, extmark_opts = extmark_opts } end --- 'mini.pick' pickers --- --- A table with |MiniPick| pickers (which is a hard dependency). --- Notes: --- - All have the same signature: --- - <local_opts> - optional table with options local to picker. --- - <opts> - optional table with options forwarded to |MiniPick.start()|. --- - All of them are automatically registered in |MiniPick.registry|. --- - All use default versions of |MiniPick-source.preview|, |MiniPick-source.choose|, --- and |MiniPick-source.choose_marked| if not stated otherwise. --- Shown text and |MiniPick-source.show| are targeted to the picked items. --- --- Examples of usage: --- - As Lua code: `MiniExtra.pickers.buf_lines()`. --- - With |:Pick| command: `:Pick buf_lines scope='current'` --- Note: this requires calling |MiniExtra.setup()|. MiniExtra.pickers = {} --- Buffer lines picker --- --- Pick from buffer lines. Notes: --- - Loads all target buffers which are currently unloaded. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <scope> `(string)` - one of "all" (normal listed buffers) or "current". --- Default: "all". ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.buf_lines = function(local_opts, opts) local pick = H.validate_pick('buf_lines') local_opts = vim.tbl_deep_extend('force', { scope = 'all' }, local_opts or {}) local scope = H.pick_validate_scope(local_opts, { 'all', 'current' }, 'buf_lines') local is_scope_all = scope == 'all' -- Define non-blocking callable `items` because getting all lines from all -- buffers (plus loading them) may take visibly long time local buffers = {} if is_scope_all then for _, buf_id in ipairs(vim.api.nvim_list_bufs()) do if vim.bo[buf_id].buflisted and vim.bo[buf_id].buftype == '' then table.insert(buffers, buf_id) end end else buffers = { vim.api.nvim_get_current_buf() } end local poke_picker = pick.poke_is_picker_active local f = function() local items = {} for _, buf_id in ipairs(buffers) do if not poke_picker() then return end H.buf_ensure_loaded(buf_id) local buf_name = H.buf_get_name(buf_id) or '' for lnum, l in ipairs(vim.api.nvim_buf_get_lines(buf_id, 0, -1, false)) do local prefix = is_scope_all and string.format('%s:', buf_name) or '' table.insert(items, { text = string.format('%s%s:%s', prefix, lnum, l), bufnr = buf_id, lnum = lnum }) end end pick.set_picker_items(items) end local items = vim.schedule_wrap(coroutine.wrap(f)) local show = H.pick_get_config().source.show if is_scope_all and show == nil then show = H.show_with_icons end return H.pick_start(items, { source = { name = string.format('Buffer lines (%s)', scope), show = show } }, opts) end --- Neovim commands picker --- --- Pick from Neovim built-in (|ex-commands|) and |user-commands|. --- Notes: --- - Preview shows information about the command (if available). --- - Choosing either executes command (if reliably known that it doesn't need --- arguments) or populates Command line with the command. --- ---@param local_opts __extra_pickers_local_opts --- Not used at the moment. ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.commands = function(local_opts, opts) local pick = H.validate_pick('commands') local commands = vim.tbl_deep_extend('force', vim.api.nvim_get_commands({}), vim.api.nvim_buf_get_commands(0, {})) local preview = function(buf_id, item) local data = commands[item] local lines = data == nil and { string.format('No command data for `%s` is yet available.', item) } or vim.split(vim.inspect(data), '\n') H.set_buflines(buf_id, lines) end local choose = function(item) local data = commands[item] or {} -- If no arguments needed, execute immediately local keys = string.format(':%s%s', item, data.nargs == '0' and '\r' or ' ') vim.schedule(function() vim.fn.feedkeys(keys) end) end local items = vim.fn.getcompletion('', 'command') local default_opts = { source = { name = 'Commands', preview = preview, choose = choose } } return H.pick_start(items, default_opts, opts) end --- Built-in diagnostic picker --- --- Pick from |vim.diagnostic| using |vim.diagnostic.get()|. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <get_opts> `(table)` - options for |vim.diagnostic.get()|. Can be used --- to limit severity or namespace. Default: `{}`. --- - <scope> `(string)` - one of "all" (available) or "current" (buffer). --- Default: "all". --- - <sort_by> `(string)` - sort priority. One of "severity", "path", "none". --- Default: "severity". ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.diagnostic = function(local_opts, opts) local pick = H.validate_pick('diagnostic') local_opts = vim.tbl_deep_extend('force', { get_opts = {}, scope = 'all', sort_by = 'severity' }, local_opts or {}) local scope = H.pick_validate_scope(local_opts, { 'all', 'current' }, 'diagnostic') local sort_by = H.pick_validate_one_of('sort_by', local_opts, { 'severity', 'path', 'none' }, 'diagnostic') local plus_one = function(x) if x == nil then return nil end return x + 1 end local diag_buf_id if scope == 'current' then diag_buf_id = vim.api.nvim_get_current_buf() end local items = vim.deepcopy(vim.diagnostic.get(diag_buf_id, local_opts.get_opts)) -- Compute final path width local path_width = 0 for _, item in ipairs(items) do item.path = H.buf_get_name(item.bufnr) or '' item.severity = item.severity or 0 path_width = math.max(path_width, vim.fn.strchars(item.path)) end -- Sort local compare = H.diagnostic_make_compare(sort_by) if vim.is_callable(compare) then table.sort(items, compare) end -- Update items for _, item in ipairs(items) do local severity = vim.diagnostic.severity[item.severity] or ' ' local text = item.message:gsub('\n', ' ') item.text = string.format('%s │ %s │ %s', severity:sub(1, 1), H.ensure_text_width(item.path, path_width), text) item.lnum, item.col, item.end_lnum, item.end_col = plus_one(item.lnum), plus_one(item.col), plus_one(item.end_lnum), plus_one(item.end_col) end local hl_groups_ref = { [vim.diagnostic.severity.ERROR] = 'DiagnosticFloatingError', [vim.diagnostic.severity.WARN] = 'DiagnosticFloatingWarn', [vim.diagnostic.severity.INFO] = 'DiagnosticFloatingInfo', [vim.diagnostic.severity.HINT] = 'DiagnosticFloatingHint', } -- Define source local show = function(buf_id, items_to_show, query) pick.default_show(buf_id, items_to_show, query) H.pick_clear_namespace(buf_id, H.ns_id.pickers) for i, item in ipairs(items_to_show) do H.pick_highlight_line(buf_id, i, hl_groups_ref[item.severity], 199) end end local name = string.format('Diagnostic (%s)', scope) return H.pick_start(items, { source = { name = name, choose = H.choose_with_buflisted, show = show } }, opts) end --- File explorer picker --- --- Explore file system and open file. --- Notes: --- - Choosing a directory navigates inside it, changing picker's items and --- current working directory. --- - Query and preview work as usual (not only `move_next`/`move_prev` can be used). --- - Preview works for any item. --- --- Examples ~ --- --- - `MiniExtra.pickers.explorer()` --- - `:Pick explorer cwd='..'` - open explorer in parent directory. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <cwd> `(string)` - initial directory to explore. Should be a valid --- directory path. Default: `nil` for |current-directory|. --- - <filter> `(function)` - callable predicate to filter items to show. --- Will be called for every item and should return `true` if it should be --- shown. Each item is a table with the following fields: --- - <fs_type> `(string)` - path type. One of "directory" or "file". --- - <path> `(string)` - item path. --- - <text> `(string)` - shown text (path's basename). --- - <sort> `(function)` - callable item sorter. Will be called with array --- of items (each element with structure as described above) and should --- return sorted array of items. ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.explorer = function(local_opts, opts) local pick = H.validate_pick('explorer') local_opts = vim.tbl_deep_extend('force', { cwd = nil, filter = nil, sort = nil }, local_opts or {}) local cwd = local_opts.cwd or vim.fn.getcwd() if vim.fn.isdirectory(cwd) == 0 then H.error('`local_opts.cwd` should be valid directory path.') end -- - Call twice "full path" to make sure that possible '..' are collapsed cwd = H.full_path(vim.fn.fnamemodify(cwd, ':p')) local filter = local_opts.filter or function() return true end if not vim.is_callable(filter) then H.error('`local_opts.filter` should be callable.') end local sort = local_opts.sort or H.explorer_default_sort if not vim.is_callable(sort) then H.error('`local_opts.sort` should be callable.') end -- Define source local choose = function(item) local path = item.path if vim.fn.filereadable(path) == 1 then return pick.default_choose(path) end if vim.fn.isdirectory(path) == 0 then return false end pick.set_picker_items(H.explorer_make_items(path, filter, sort)) pick.set_picker_opts({ source = { cwd = path } }) pick.set_picker_query({}) return true end local show = H.pick_get_config().source.show or H.show_with_icons local items = H.explorer_make_items(cwd, filter, sort) local source = { items = items, name = 'File explorer', cwd = cwd, show = show, choose = choose } opts = vim.tbl_deep_extend('force', { source = source }, opts or {}) return pick.start(opts) end --- Git branches picker --- --- Pick from Git branches using `git branch`. --- __extra_pickers_git_notes --- - On choose opens scratch buffer with branch's history. --- --- Examples ~ --- --- - `MiniExtra.pickers.git_branches({ scope = 'local' })` - local branches of --- the |current-directory| parent Git repository. --- - `:Pick git_branches path='%'` - all branches of the current file parent --- Git repository. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- __extra_pickers_git_path --- - <scope> `(string)` - branch scope to show. One of "all", "local", "remotes". --- Default: "all". ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.git_branches = function(local_opts, opts) local pick = H.validate_pick('git_branches') H.validate_git('git_branches') local_opts = vim.tbl_deep_extend('force', { path = nil, scope = 'all' }, local_opts or {}) local scope = H.pick_validate_scope(local_opts, { 'all', 'local', 'remotes' }, 'git_branches') -- Compute path to repo with target path (as it might differ from current) local path, path_type = H.git_normalize_path(local_opts.path, 'git_branches') local repo_dir = H.git_get_repo_dir(path, path_type, 'git_branches') -- Define source local show_history = function(buf_id, item) local branch = item:match('^%*?%s*(%S+)') local cmd = { 'git', '-C', repo_dir, 'log', branch, '--format=format:%h %s' } H.cli_show_output(buf_id, cmd) end local preview = show_history local choose = H.make_show_in_target_win('git_branches', show_history) local command = { 'git', 'branch', '-v', '--no-color', '--list' } if scope == 'all' or scope == 'remotes' then table.insert(command, 3, '--' .. scope) end local name = string.format('Git branches (%s)', scope) local default_source = { name = name, cwd = repo_dir, preview = preview, choose = choose } opts = vim.tbl_deep_extend('force', { source = default_source }, opts or {}) return pick.builtin.cli({ command = command }, opts) end --- Git commits picker --- --- Pick from Git commits using `git log`. --- __extra_pickers_git_notes --- - On choose opens scratch buffer with commit's diff. --- --- Examples ~ --- --- - `MiniExtra.pickers.git_commits()` - all commits from parent Git --- repository of |current-directory|. --- - `MiniExtra.pickers.git_commits({ path = 'subdir' })` - commits affecting --- files from 'subdir' subdirectory. --- - `:Pick git_commits path='%'` commits affecting current file. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- __extra_pickers_git_path ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.git_commits = function(local_opts, opts) local pick = H.validate_pick('git_commits') H.validate_git('git_commits') local_opts = vim.tbl_deep_extend('force', { path = nil }, local_opts or {}) -- Compute path to repo with target path (as it might differ from current) local path, path_type = H.git_normalize_path(local_opts.path, 'git_commits') local repo_dir = H.git_get_repo_dir(path, path_type, 'git_commits') if local_opts.path == nil then path = repo_dir end -- Define source local show_patch = function(buf_id, item) if type(item) ~= 'string' then return end vim.bo[buf_id].syntax = 'git' H.cli_show_output(buf_id, { 'git', '-C', repo_dir, '--no-pager', 'show', item:match('^(%S+)') }) end local preview = show_patch local choose = H.make_show_in_target_win('git_commits', show_patch) local command = { 'git', 'log', [[--format=format:%h %s]], '--', path } local name = string.format('Git commits (%s)', local_opts.path == nil and 'all' or 'for path') local default_source = { name = name, cwd = repo_dir, preview = preview, choose = choose } opts = vim.tbl_deep_extend('force', { source = default_source }, opts or {}) return pick.builtin.cli({ command = command }, opts) end --- Git files picker --- --- Pick from Git files using `git ls-files`. --- __extra_pickers_git_notes --- --- Examples ~ --- --- - `MiniExtra.pickers.git_files({ scope = 'ignored' })` - ignored files from --- parent Git repository of |current-directory|. --- - `:Pick git_files path='subdir' scope='modified'` - files from 'subdir' --- subdirectory which are ignored by Git. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- __extra_pickers_git_path --- - <scope> `(string)` - files scope to show. One of --- - "tracked" (`--cached` Git flag). --- - "modified" (`--modified` Git flag). --- - "untracked" (`--others` Git flag). --- - "ignored" (`--ignored` Git flag). --- - "deleted" (`--deleted` Git flag). --- Default: "tracked". ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.git_files = function(local_opts, opts) local pick = H.validate_pick('git_files') H.validate_git('git_files') local_opts = vim.tbl_deep_extend('force', { path = nil, scope = 'tracked' }, local_opts or {}) local allowed_scope = { 'tracked', 'modified', 'untracked', 'ignored', 'deleted' } local scope = H.pick_validate_scope(local_opts, allowed_scope, 'git_files') -- Compute path to repo with target path (as it might differ from current) local path, path_type = H.git_normalize_path(local_opts.path, 'git_files') H.git_get_repo_dir(path, path_type, 'git_files') local path_dir = path_type == 'directory' and path or vim.fn.fnamemodify(path, ':h') -- Define source local show = H.pick_get_config().source.show or H.show_with_icons --stylua: ignore local command = ({ tracked = { 'git', '-C', path_dir, 'ls-files', '--cached' }, modified = { 'git', '-C', path_dir, 'ls-files', '--modified' }, untracked = { 'git', '-C', path_dir, 'ls-files', '--others' }, ignored = { 'git', '-C', path_dir, 'ls-files', '--others', '--ignored', '--exclude-standard' }, deleted = { 'git', '-C', path_dir, 'ls-files', '--deleted' }, })[local_opts.scope] local name = string.format('Git files (%s)', local_opts.scope) local default_source = { name = name, cwd = path_dir, show = show } opts = vim.tbl_deep_extend('force', { source = default_source }, opts or {}) return pick.builtin.cli({ command = command }, opts) end --- Git hunks picker --- --- Pick from Git hunks using `git diff`. --- __extra_pickers_git_notes --- - On choose navigates to hunk's first change. --- --- Examples ~ --- --- - `MiniExtra.pickers.git_hunks({ scope = 'staged' })` - staged hunks from --- parent Git repository of |current-directory|. --- - `:Pick git_hunks path='%' n_context=0` - hunks from current file computed --- with no context. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <n_context> `(number)` - number of context lines to show in hunk's preview. --- Default: 3. --- __extra_pickers_git_path --- - <scope> `(string)` - hunks scope to show. One of "unstaged" or "staged". --- Default: "unstaged". ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.git_hunks = function(local_opts, opts) local pick = H.validate_pick('git_hunks') H.validate_git('git_hunks') local default_local_opts = { n_context = 3, path = nil, scope = 'unstaged' } local_opts = vim.tbl_deep_extend('force', default_local_opts, local_opts or {}) if not (type(local_opts.n_context) == 'number' and local_opts.n_context >= 0) then H.error('`n_context` option in `pickers.git_hunks` picker should be non-negative number.') end local n_context = math.floor(local_opts.n_context) local scope = H.pick_validate_scope(local_opts, { 'unstaged', 'staged' }, 'git_hunks') -- Compute path to repo with target path (as it might differ from current) local path, path_type = H.git_normalize_path(local_opts.path, 'git_hunks') local repo_dir = H.git_get_repo_dir(path, path_type, 'git_hunks') if local_opts.path == nil then path = repo_dir end -- Define source local preview = function(buf_id, item) vim.bo[buf_id].syntax = 'diff' local lines = vim.deepcopy(item.header) vim.list_extend(lines, item.hunk) H.set_buflines(buf_id, lines) end local command = { 'git', 'diff', '--patch', '--unified=' .. n_context, '--color=never', '--', path } if scope == 'staged' then table.insert(command, 4, '--cached') end local postprocess = function(lines) return H.git_difflines_to_hunkitems(lines, n_context) end local name = string.format('Git hunks (%s %s)', scope, local_opts.path == nil and 'all' or 'for path') local default_source = { name = name, cwd = repo_dir, preview = preview } opts = vim.tbl_deep_extend('force', { source = default_source }, opts or {}) return pick.builtin.cli({ command = command, postprocess = postprocess }, opts) end --- Matches from 'mini.hipatterns' picker --- --- Pick from |MiniHipatterns| matches using |MiniHipatterns.get_matches()|. --- Notes: --- - Requires 'mini.hipatterns'. --- - Highlighter identifier is highlighted with its highlight group. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <scope> `(string)` - one of "all" (buffers with enabled 'mini.hipatterns') --- or "current" (buffer). Default: "all". --- - <highlighters> `(table|nil)` - highlighters for which to find matches. --- Forwarded to |MiniHipatterns.get_matches()|. Default: `nil`. ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.hipatterns = function(local_opts, opts) local pick = H.validate_pick('hipatterns') local has_hipatterns, hipatterns = pcall(require, 'mini.hipatterns') if not has_hipatterns then H.error([[`pickers.hipatterns` requires 'mini.hipatterns' which can not be found.]]) end local_opts = vim.tbl_deep_extend('force', { highlighters = nil, scope = 'all' }, local_opts or {}) if local_opts.highlighters ~= nil and not vim.tbl_islist(local_opts.highlighters) then H.error('`local_opts.highlighters` should be an array of highlighter identifiers.') end local highlighters = local_opts.highlighters local scope = H.pick_validate_scope(local_opts, { 'all', 'current' }, 'hipatterns') -- Get items local buffers = scope == 'all' and hipatterns.get_enabled_buffers() or { vim.api.nvim_get_current_buf() } local items, highlighter_width = {}, 0 for _, buf_id in ipairs(buffers) do local lines = vim.api.nvim_buf_get_lines(buf_id, 0, -1, false) local buf_name = H.buf_get_name(buf_id) if buf_name == '' then buf_name = 'Buffer_' .. buf_id end for _, match in ipairs(hipatterns.get_matches(buf_id, highlighters)) do match.highlighter = tostring(match.highlighter) match.buf_name, match.line = buf_name, lines[match.lnum] table.insert(items, match) highlighter_width = math.max(highlighter_width, vim.fn.strchars(match.highlighter)) end end for _, item in ipairs(items) do --stylua: ignore item.text = string.format( '%s │ %s:%d:%d:%s', H.ensure_text_width(item.highlighter, highlighter_width), item.buf_name, item.lnum, item.col, item.line ) item.buf_name, item.line = nil, nil end local show = function(buf_id, items_to_show, query) pick.default_show(buf_id, items_to_show, query) H.pick_clear_namespace(buf_id, H.ns_id.pickers) for i, item in ipairs(items_to_show) do local end_col = string.len(item.highlighter) local extmark_opts = { hl_group = item.hl_group, end_row = i - 1, end_col = end_col, priority = 1 } vim.api.nvim_buf_set_extmark(buf_id, H.ns_id.pickers, i - 1, 0, extmark_opts) end end local name = string.format('Mini.hipatterns matches (%s)', scope) return H.pick_start(items, { source = { name = name, show = show } }, opts) end --- Neovim history picker --- --- Pick from output of |:history|. --- Notes: --- - Has no preview. --- - Choosing action depends on scope: --- - For "cmd" / ":" scopes, the command is executed. --- - For "search" / "/" / "?" scopes, search is redone. --- - For other scopes nothing is done (but chosen item is still returned). --- --- Examples ~ --- --- - Command history: `MiniExtra.pickers.history({ scope = ':' })` --- - Search history: `:Pick history scope='/'` --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <scope> `(string)` - any allowed {name} flag of |:history| command. --- Note: word abbreviations are not allowed. Default: "all". ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.history = function(local_opts, opts) local pick = H.validate_pick('history') local_opts = vim.tbl_deep_extend('force', { scope = 'all' }, local_opts or {}) local allowed_scope = { 'all', 'cmd', 'search', 'expr', 'input', 'debug', ':', '/', '?', '=', '@', '>' } local scope = H.pick_validate_scope(local_opts, allowed_scope, 'history') --stylua: ignore local type_ids = { cmd = ':', search = '/', expr = '=', input = '@', debug = '>', [':'] = ':', ['/'] = '/', ['='] = '=', ['@'] = '@', ['>'] = '>', ['?'] = '?', } -- Construct items local items = {} local names = scope == 'all' and { 'cmd', 'search', 'expr', 'input', 'debug' } or { scope } for _, cur_name in ipairs(names) do local cmd_output = vim.api.nvim_exec(':history ' .. cur_name, true) local lines = vim.split(cmd_output, '\n') local id = type_ids[cur_name] -- Output of `:history` is sorted from oldest to newest for i = #lines, 2, -1 do local hist_entry = lines[i]:match('^.-%-?%d+%s+(.*)$') table.insert(items, string.format('%s %s', id, hist_entry)) end end -- Define source local preview = H.pick_make_no_preview('history') local choose = function(item) if not (type(item) == 'string' and vim.fn.mode() == 'n') then return end local id, entry = item:match('^(.) (.*)$') if id == ':' or id == '/' or id == '?' then vim.schedule(function() vim.fn.feedkeys(id .. entry .. '\r', 'nx') end) end end local default_source = { name = string.format('History (%s)', scope), preview = preview, choose = choose } return H.pick_start(items, { source = default_source }, opts) end --- Highlight groups picker --- --- Pick and preview highlight groups. --- Notes: --- - Item line is colored with same highlight group it represents. --- - Preview shows highlight's definition (as in |:highlight| with {group-name}). --- - Choosing places highlight definition in Command line to update and apply. --- ---@param local_opts __extra_pickers_local_opts --- Not used at the moment. ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.hl_groups = function(local_opts, opts) local pick = H.validate_pick('hl_groups') -- Construct items local group_data = vim.split(vim.api.nvim_exec('highlight', true), '\n') local items = {} for _, l in ipairs(group_data) do local group = l:match('^(%S+)') if group ~= nil then table.insert(items, group) end end local show = function(buf_id, items_to_show, query) H.set_buflines(buf_id, items_to_show) H.pick_clear_namespace(buf_id, H.ns_id.pickers) -- Highlight line with highlight group of its item for i = 1, #items_to_show do H.pick_highlight_line(buf_id, i, items_to_show[i], 300) end end -- Define source local preview = function(buf_id, item) local lines = vim.split(vim.api.nvim_exec('hi ' .. item, true), '\n') H.set_buflines(buf_id, lines) end local choose = function(item) local hl_def = vim.split(vim.api.nvim_exec('hi ' .. item, true), '\n')[1] hl_def = hl_def:gsub('^(%S+)%s+xxx%s+', '%1 ') vim.schedule(function() vim.fn.feedkeys(':hi ' .. hl_def, 'n') end) end local default_source = { name = 'Highlight groups', show = show, preview = preview, choose = choose } return H.pick_start(items, { source = default_source }, opts) end --- Neovim keymaps picker --- --- Pick and preview data about Neovim keymaps. --- Notes: --- - Item line contains data about keymap mode, whether it is buffer local, its --- left hand side, and inferred description. --- - Preview shows keymap data or callback source (if present and reachable). --- - Choosing emulates pressing the left hand side of the keymap. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <mode> `(string)` - modes to show. One of "all" or appropriate mode --- for |nvim_set_keymap()|. Default: "all". --- - <scope> `(string)` - scope to show. One of "all", "global", "buf". --- Default: "all". ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.keymaps = function(local_opts, opts) local pick = H.validate_pick('keymaps') local_opts = vim.tbl_deep_extend('force', { mode = 'all', scope = 'all' }, local_opts or {}) local mode = H.pick_validate_one_of('mode', local_opts, { 'all', 'n', 'x', 's', 'o', 'i', 'l', 'c', 't' }, 'keymaps') local scope = H.pick_validate_scope(local_opts, { 'all', 'global', 'buf' }, 'keymaps') -- Create items local keytrans = vim.fn.has('nvim-0.8') == 1 and vim.fn.keytrans or function(x) return x end local items = {} local populate_modes = mode == 'all' and { 'n', 'x', 's', 'o', 'i', 'l', 'c', 't' } or { mode } local max_lhs_width = 0 local populate_items = function(source) for _, m in ipairs(populate_modes) do for _, maparg in ipairs(source(m)) do local desc = maparg.desc ~= nil and vim.inspect(maparg.desc) or maparg.rhs local lhs = keytrans(maparg.lhsraw or maparg.lhs) max_lhs_width = math.max(vim.fn.strchars(lhs), max_lhs_width) table.insert(items, { lhs = lhs, desc = desc, maparg = maparg }) end end end if scope == 'all' or scope == 'buf' then populate_items(function(m) return vim.api.nvim_buf_get_keymap(0, m) end) end if scope == 'all' or scope == 'global' then populate_items(vim.api.nvim_get_keymap) end for _, item in ipairs(items) do local buf_map_indicator = item.maparg.buffer == 0 and ' ' or '@' local lhs_text = H.ensure_text_width(item.lhs, max_lhs_width) item.text = string.format('%s %s │ %s │ %s', item.maparg.mode, buf_map_indicator, lhs_text, item.desc or '') end -- Define source local get_callback_pos = function(maparg) if type(maparg.callback) ~= 'function' then return nil, nil end local info = debug.getinfo(maparg.callback) local path = info.source:gsub('^@', '') if vim.fn.filereadable(path) == 0 then return nil, nil end return path, info.linedefined end local preview = function(buf_id, item) local path, lnum = get_callback_pos(item.maparg) if path ~= nil then item.path, item.lnum = path, lnum return pick.default_preview(buf_id, item) end local lines = vim.split(vim.inspect(item.maparg), '\n') H.set_buflines(buf_id, lines) end local choose = function(item) local keys = vim.api.nvim_replace_termcodes(item.maparg.lhs, true, true, true) -- Restore Visual mode (should be active previously at least once) if item.maparg.mode == 'x' then keys = 'gv' .. keys end vim.schedule(function() vim.fn.feedkeys(keys) end) end local default_opts = { source = { name = string.format('Keymaps (%s)', scope), preview = preview, choose = choose } } return H.pick_start(items, default_opts, opts) end --- Neovim lists picker --- --- Pick and navigate to elements of the following Neovim lists: --- - |quickfix| list. --- - |location-list| of current window. --- - |jumplist|. --- - |changelist|. --- --- Note: it requires explicit `scope`. --- --- Examples ~ --- --- - `MiniExtra.pickers.list({ scope = 'quickfix' })` - quickfix list. --- - `:Pick list scope='jump'` - jump list. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <scope> `(string)` - type of list to show. One of "quickfix", "location", --- "jump", "change". Default: `nil` which means explicit scope is needed. ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.list = function(local_opts, opts) local pick = H.validate_pick('list') local_opts = vim.tbl_deep_extend('force', { scope = nil }, local_opts or {}) if local_opts.scope == nil then H.error('`pickers.list` needs an explicit scope.') end local allowed_scopes = { 'quickfix', 'location', 'jump', 'change' } local scope = H.pick_validate_scope(local_opts, allowed_scopes, 'list') local has_items, items = pcall(H.list_get[scope]) if not has_items then items = {} end items = vim.tbl_filter(function(x) return H.is_valid_buf(x.bufnr) end, items) items = vim.tbl_map(H.list_enhance_item, items) local name = string.format('List (%s)', scope) return H.pick_start(items, { source = { name = name, choose = H.choose_with_buflisted } }, opts) end --- LSP picker --- --- Pick and navigate with LSP methods. --- Notes: --- - Needs an explicit scope from a list of supported ones: --- - "declaration". --- - "definition". --- - "document_symbol". --- - "implementation". --- - "references". --- - "type_definition". --- - "workspace_symbol". --- - Requires Neovim>=0.8. --- - Directly relies on `vim.lsp.buf` methods which support |lsp-on-list-handler|. --- In particular, it means that picker is started only if LSP server returns --- list of locations and not a single location. --- - Doesn't return anything due to async nature of `vim.lsp.buf` methods. --- --- Examples ~ --- --- - `MiniExtra.pickers.lsp({ scope = 'references' })` - references of the symbol --- under cursor. --- - `:Pick lsp scope='document_symbol'` - symbols in current file. --- ---@param local_opts table Options defining behavior of this particular picker. --- Possible fields: --- - <scope> `(string)` - LSP method to use. One of the supported ones (see --- list above). Default: `nil` which means explicit scope is needed. --- - <symbol_query> `(string)` - query for |vim.lsp.buf.workspace_symbol()|. --- Default: empty string for all symbols (according to LSP specification). ---@param opts __extra_pickers_opts --- ---@return nil Nothing is returned. MiniExtra.pickers.lsp = function(local_opts, opts) if vim.fn.has('nvim-0.8') == 0 then H.error('`pickers.lsp` requires Neovim>=0.8.') end local pick = H.validate_pick('lsp') local_opts = vim.tbl_deep_extend('force', { scope = nil, symbol_query = '' }, local_opts or {}) if local_opts.scope == nil then H.error('`pickers.lsp` needs an explicit scope.') end --stylua: ignore local allowed_scopes = { 'declaration', 'definition', 'document_symbol', 'implementation', 'references', 'type_definition', 'workspace_symbol', } local scope = H.pick_validate_scope(local_opts, allowed_scopes, 'lsp') if scope == 'references' then return vim.lsp.buf[scope](nil, { on_list = H.lsp_make_on_list(scope, opts) }) end if scope == 'workspace_symbol' then local query = tostring(local_opts.symbol_query) return vim.lsp.buf[scope](query, { on_list = H.lsp_make_on_list(scope, opts) }) end vim.lsp.buf[scope]({ on_list = H.lsp_make_on_list(scope, opts) }) end --- Neovim marks picker --- --- Pick and preview position of Neovim |mark|s. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <scope> `(string)` - scope to show. One of "all", "global", "buf". --- Default: "all". ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.marks = function(local_opts, opts) local pick = H.validate_pick('marks') local_opts = vim.tbl_deep_extend('force', { scope = 'all' }, local_opts or {}) local scope = H.pick_validate_scope(local_opts, { 'all', 'global', 'buf' }, 'marks') -- Create items local items = {} local populate_items = function(mark_list) for _, info in ipairs(mark_list) do local path if type(info.file) == 'string' then path = vim.fn.fnamemodify(info.file, ':.') end local buf_id if path == nil then buf_id = info.pos[1] end local line, col = info.pos[2], math.abs(info.pos[3]) local text = string.format('%s │ %s%s:%s', info.mark:sub(2), path == nil and '' or (path .. ':'), line, col) table.insert(items, { text = text, bufnr = buf_id, path = path, lnum = line, col = col }) end end if scope == 'all' or scope == 'buf' then populate_items(vim.fn.getmarklist(vim.api.nvim_get_current_buf())) end if scope == 'all' or scope == 'global' then populate_items(vim.fn.getmarklist()) end local default_opts = { source = { name = string.format('Marks (%s)', scope) } } return H.pick_start(items, default_opts, opts) end --- Old files picker --- --- Pick from |v:oldfiles| entries representing readable files. --- ---@param local_opts __extra_pickers_local_opts --- Not used at the moment. ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.oldfiles = function(local_opts, opts) local pick = H.validate_pick('oldfiles') local oldfiles = vim.v.oldfiles if not vim.tbl_islist(oldfiles) then H.error('`pickers.oldfiles` picker needs valid `v:oldfiles`.') end local items = vim.schedule_wrap(function() local cwd = pick.get_picker_opts().source.cwd local res = {} for _, path in ipairs(oldfiles) do if vim.fn.filereadable(path) == 1 then table.insert(res, H.short_path(path, cwd)) end end pick.set_picker_items(res) end) local show = H.pick_get_config().source.show or H.show_with_icons return H.pick_start(items, { source = { name = 'Old files', show = show } }, opts) end --- Neovim options picker --- --- Pick and preview data about Neovim options. --- Notes: --- - Item line is colored based on whether it was set (dimmed if wasn't). --- - Preview shows option value in target window and its general information. --- - Choosing places option name in Command line to update and apply. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <scope> `(string)` - options to show. One of "all", "global", "win", "buf". --- Default: "all". ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.options = function(local_opts, opts) local pick = H.validate_pick('options') local_opts = vim.tbl_deep_extend('force', { scope = 'all' }, local_opts or {}) local scope = H.pick_validate_scope(local_opts, { 'all', 'global', 'win', 'buf' }, 'options') local items = {} for name, info in pairs(vim.api.nvim_get_all_options_info()) do if scope == 'all' or scope == info.scope then table.insert(items, { text = name, info = info }) end end table.sort(items, function(a, b) return a.text < b.text end) local show = function(buf_id, items_to_show, query) pick.default_show(buf_id, items_to_show, query) H.pick_clear_namespace(buf_id, H.ns_id.pickers) for i, item in ipairs(items_to_show) do if not item.info.was_set then H.pick_highlight_line(buf_id, i, 'Comment', 199) end end end local preview = function(buf_id, item) local pick_windows = pick.get_picker_state().windows local target_win_id = pick_windows.target if not H.is_valid_win(target_win_id) then target_win_id = pick_windows.main end local value_source = ({ global = 'o', win = 'wo', buf = 'bo' })[item.info.scope] local has_value, value = pcall(function() return vim.api.nvim_win_call(target_win_id, function() return vim[value_source][item.info.name] end) end) if not has_value then value = '<Option is deprecated (will be removed in later Neovim versions)>' end local lines = { 'Value:', unpack(vim.split(vim.inspect(value), '\n')), '', 'Info:' } local hl_lines = { 1, #lines } lines = vim.list_extend(lines, vim.split(vim.inspect(item.info), '\n')) H.set_buflines(buf_id, lines) H.pick_highlight_line(buf_id, hl_lines[1], 'MiniPickHeader', 200) H.pick_highlight_line(buf_id, hl_lines[2], 'MiniPickHeader', 200) end local choose = function(item) local keys = string.format(':set %s%s', item.info.name, item.info.type == 'boolean' and '' or '=') vim.schedule(function() vim.fn.feedkeys(keys) end) end local name = string.format('Options (%s)', scope) local default_source = { name = name, show = show, preview = preview, choose = choose } return H.pick_start(items, { source = default_source }, opts) end --- Neovim registers picker --- --- Pick from Neovim |registers|. --- Notes: --- - There is no preview (all information is in the item's text). --- - Choosing pastes content of a register: with |i_CTRL-R| in Insert mode, --- |c_CTRL-R| in Command-line mode, and |P| otherwise. --- Expression register |quote=| is reevaluated (if present) and pasted. --- ---@param local_opts __extra_pickers_local_opts --- Not used at the moment. ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.registers = function(local_opts, opts) local pick = H.validate_pick('registers') local describe_register = function(regname) local ok, value = pcall(vim.fn.getreg, regname, 1) if not ok then return '' end return value end local all_registers = vim.split('"*+:.%/#=-0123456789abcdefghijklmnopqrstuvwxyz', '') local items = {} for _, regname in ipairs(all_registers) do local regcontents = describe_register(regname) local text = string.format('%s │ %s', regname, regcontents) table.insert(items, { regname = regname, regcontents = regcontents, text = text }) end local choose = vim.schedule_wrap(function(item) local reg, regcontents, mode = item.regname, item.regcontents, vim.fn.mode() if reg == '=' and regcontents ~= '' then reg = reg .. item.regcontents .. '\r' end local keys = string.format('"%s%s', reg, reg == '=' and '' or 'P') -- In Insert and Command-line modes use `<C-r><regname>` if mode == 'i' or mode == 'c' then keys = '\18' .. reg end vim.fn.feedkeys(keys) end) local preview = function(buf_id, item) H.set_buflines(buf_id, vim.split(item.regcontents, '\n')) end return H.pick_start(items, { source = { name = 'Registers', preview = preview, choose = choose } }, opts) end --- Neovim spell suggestions picker --- --- Pick and apply spell suggestions. --- Notes: --- - No preview is available. --- - Choosing replaces current word (|<cword>|) with suggestion. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <n_suggestions> `(number)` - number of spell suggestions. Default: 25. --- ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.spellsuggest = function(local_opts, opts) local pick = H.validate_pick('spellsuggest') local_opts = vim.tbl_deep_extend('force', { n_suggestions = 25 }, local_opts or {}) local n_suggestions = local_opts.n_suggestions if not (type(n_suggestions) == 'number' and n_suggestions > 0) then H.error('`local_opts.n_suggestions` should be a positive number.') end local word = vim.fn.expand('<cword>') local suggestions = vim.fn.spellsuggest(word, n_suggestions) local items = {} for i, sugg in ipairs(suggestions) do table.insert(items, { text = sugg, index = i }) end -- Define scope local preview = H.pick_make_no_preview('spellsuggest') local choose = vim.schedule_wrap(function(item) vim.cmd('normal! ' .. item.index .. 'z=') end) local name = 'Spell suggestions for ' .. vim.inspect(word) return H.pick_start(items, { source = { name = name, preview = preview, choose = choose } }, opts) end --- Tree-sitter nodes picker --- --- Pick and navigate to |treesitter| nodes of current buffer. --- Notes: --- - Requires Neovim>=0.8. --- - Requires active tree-sitter parser in the current buffer. --- ---@param local_opts __extra_pickers_local_opts --- Not used at the moment. ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.treesitter = function(local_opts, opts) if vim.fn.has('nvim-0.8') == 0 then H.error('`pickers.treesitter` requires Neovim>=0.8.') end local pick = H.validate_pick('treesitter') local buf_id = vim.api.nvim_get_current_buf() local has_parser, parser = pcall(vim.treesitter.get_parser, buf_id) if not has_parser or parser == nil then H.error('`pickers.treesitter` requires active tree-sitter parser.') end -- Make items by traversing roots of all trees (including injections) local items, traverse = {}, nil traverse = function(node, depth) if depth >= 1000 then return end for child in node:iter_children() do if child:named() then local lnum, col, end_lnum, end_col = child:range() lnum, col, end_lnum, end_col = lnum + 1, col + 1, end_lnum + 1, end_col + 1 local indent = string.rep(' ', depth) local text = string.format('%s%s (%s:%s - %s:%s)', indent, child:type() or '', lnum, col, end_lnum, end_col) local item = { text = text, bufnr = buf_id, lnum = lnum, col = col, end_lnum = end_lnum, end_col = end_col } table.insert(items, item) traverse(child, depth + 1) end end end parser:for_each_tree(function(ts_tree, _) traverse(ts_tree:root(), 0) end) return H.pick_start(items, { source = { name = 'Tree-sitter nodes' } }, opts) end --- Visit paths from 'mini.visits' picker --- --- Pick paths from |MiniVisits| using |MiniVisits.list_paths()|. --- Notes: --- - Requires 'mini.visits'. --- --- Examples ~ --- --- - `MiniExtra.pickers.visit_paths()` - visits registered for |current-directory| --- and ordered by "robust frecency". --- - `:Pick visit_paths cwd='' recency_weight=1 filter='core'` - all visits with --- "core" label ordered from most to least recent. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <cwd> `(string)` - forwarded to |MiniVisits.list_paths()|. --- Default: `nil` to get paths registered for |current-directory|. --- - <filter> `(function|string)` - forwarded to |MiniVisits.list_paths()|. --- Default: `nil` to use all paths. --- - <preserve_order> `(boolean)` - whether to preserve original order --- during query. Default: `false`. --- - <recency_weight> `(number)` - forwarded to |MiniVisits.gen_sort.default()|. --- Default: 0.5 to use "robust frecency" sorting. --- - <sort> `(function)` - forwarded to |MiniVisits.list_paths()|. --- Default: `nil` to use "robust frecency". --- Note: if supplied, has precedence over `recency_weight`. ---@param opts __extra_pickers_opts --- ---@return __extra_pickers_return MiniExtra.pickers.visit_paths = function(local_opts, opts) local pick = H.validate_pick('visit_paths') local has_visits, visits = pcall(require, 'mini.visits') if not has_visits then H.error([[`pickers.visit_paths` requires 'mini.visits' which can not be found.]]) end local default_local_opts = { cwd = nil, filter = nil, preserve_order = false, recency_weight = 0.5, sort = nil } local_opts = vim.tbl_deep_extend('force', default_local_opts, local_opts or {}) local cwd = local_opts.cwd or vim.fn.getcwd() -- NOTE: Use separate cwd to allow `cwd = ''` to not mean "current directory" local is_for_cwd = cwd ~= '' local picker_cwd = cwd == '' and vim.fn.getcwd() or H.full_path(cwd) -- Define source local filter = local_opts.filter or visits.gen_filter.default() local sort = local_opts.sort or visits.gen_sort.default({ recency_weight = local_opts.recency_weight }) local items = vim.schedule_wrap(function() local paths = visits.list_paths(cwd, { filter = filter, sort = sort }) paths = vim.tbl_map(function(x) return H.short_path(x, picker_cwd) end, paths) pick.set_picker_items(paths) end) local show = H.pick_get_config().source.show or H.show_with_icons local match if local_opts.preserve_order then match = function(stritems, inds, query) -- Return makes call synchronous, but it shouldn't be too big problem local res = pick.default_match(stritems, inds, query, true) or {} table.sort(res) return res end end local name = string.format('Visit paths (%s)', is_for_cwd and 'cwd' or 'all') local default_source = { name = name, cwd = picker_cwd, match = match, show = show } opts = vim.tbl_deep_extend('force', { source = default_source }, opts or {}, { source = { items = items } }) return pick.start(opts) end --- Visit labels from 'mini.visits' picker --- --- Pick labels from |MiniVisits| using |MiniVisits.list_labels()| --- and |MiniVisits.list_paths()|. --- Notes: --- - Requires 'mini.visits'. --- - Preview shows target visit paths filtered to those having previewed label. --- - Choosing essentially starts |MiniExtra.pickers.visit_paths()| for paths --- with the chosen label. --- --- Examples ~ --- --- - `MiniExtra.pickers.visit_labels()` - labels from visits registered --- for |current-directory|. --- - `:Pick visit_labels cwd=''` - labels from all visits. --- ---@param local_opts __extra_pickers_local_opts --- Possible fields: --- - <cwd> `(string)` - forwarded to |MiniVisits.list_labels()|. --- Default: `nil` to get labels from visits registered for |current-directory|. --- - <filter> `(function|string)` - forwarded to |MiniVisits.list_labels()|. --- Default: `nil` to use all visits. --- - <path> `(string)` - forwarded to |MiniVisits.list_labels()|. --- Default: `""` to get labels from all visits for target `cwd`. --- - <sort> `(function)` - forwarded to |MiniVisits.list_paths()| for --- preview and choose. Default: `nil` to use "robust frecency". ---@param opts __extra_pickers_opts --- ---@return Chosen path. MiniExtra.pickers.visit_labels = function(local_opts, opts) local pick = H.validate_pick('visit_labels') local has_visits, visits = pcall(require, 'mini.visits') if not has_visits then H.error([[`pickers.visit_labels` requires 'mini.visits' which can not be found.]]) end local default_local_opts = { cwd = nil, filter = nil, path = '', sort = nil } local_opts = vim.tbl_deep_extend('force', default_local_opts, local_opts or {}) local cwd = local_opts.cwd or vim.fn.getcwd() -- NOTE: Use separate cwd to allow `cwd = ''` to not mean "current directory" local is_for_cwd = cwd ~= '' local picker_cwd = cwd == '' and vim.fn.getcwd() or H.full_path(cwd) local filter = local_opts.filter or visits.gen_filter.default() local items = visits.list_labels(local_opts.path, local_opts.cwd, { filter = filter }) -- Define source local list_label_paths = function(label) local new_filter = function(path_data) return filter(path_data) and type(path_data.labels) == 'table' and path_data.labels[label] end local all_paths = visits.list_paths(local_opts.cwd, { filter = new_filter, sort = local_opts.sort }) return vim.tbl_map(function(path) return H.short_path(path, picker_cwd) end, all_paths) end local preview = function(buf_id, label) vim.api.nvim_buf_set_lines(buf_id, 0, -1, false, list_label_paths(label)) end local choose = function(label) if label == nil then return end pick.set_picker_items(list_label_paths(label), { do_match = false }) pick.set_picker_query({}) local name = string.format('Paths for %s label', vim.inspect(label)) local show = H.pick_get_config().source.show or H.show_with_icons pick.set_picker_opts({ source = { name = name, show = show, choose = pick.default_choose } }) return true end local name = string.format('Visit labels (%s)', is_for_cwd and 'cwd' or 'all') local default_source = { name = name, cwd = picker_cwd, preview = preview, choose = choose } opts = vim.tbl_deep_extend('force', { source = default_source }, opts or {}, { source = { items = items } }) return pick.start(opts) end -- Register in 'mini.pick' if type(_G.MiniPick) == 'table' then for name, f in pairs(MiniExtra.pickers) do _G.MiniPick.registry[name] = function(local_opts) return f(local_opts) end end end -- Module default config H.default_config = MiniExtra.config -- Namespaces H.ns_id = { pickers = vim.api.nvim_create_namespace('MiniExtraPickers'), } -- Various cache H.cache = {} -- Settings ------------------------------------------------------------------- H.setup_config = function(config) end H.apply_config = function(config) MiniExtra.config = config end -- Mini.ai specifications ----------------------------------------------------- H.ai_indent_spec = function(ai_type) -- Compute buffer data local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false) local tab_spaces = string.rep(' ', vim.bo.tabstop) -- Traverse lines from top to bottom casting rays local indents, rays, rays_final = {}, {}, {} for i, l in ipairs(lines) do indents[i] = l:match('^([ \t]*)') -- Ray can be updated only on non-blank line local is_blank = indents[i]:len() ~= l:len() if is_blank then H.ai_indent_update_rays(i, indents[i]:gsub('\t', tab_spaces):len(), rays, rays_final) end end -- The `rays` stack can be not empty at this point which means that there are -- non-empty lines at buffer end without "closing". Ignore them. -- Sort for better output table.sort(rays_final, function(a, b) return a.from_line < b.from_line end) -- Compute regions: -- - `a` is as if linewise from start to end. -- - `i` is as if charwise not including edge whitespace on start and end. local from_offset, to_offset, to_col_offset = 0, 0, 1 if ai_type == 'i' then from_offset, to_offset, to_col_offset = 1, -1, 0 end local res = {} for i, ray in ipairs(rays_final) do local from_line, to_line = ray.from_line + from_offset, ray.to_line + to_offset local from_col = ai_type == 'a' and 1 or (indents[from_line]:len() + 1) local to_col = lines[to_line]:len() + to_col_offset res[i] = { from = { line = from_line, col = from_col }, to = { line = to_line, col = to_col } } end return res end H.ai_indent_update_rays = function(line_num, indent, rays, rays_final) -- Update rays with finite indent -- `rays` is a stack of cast rays (sorted by increasing start indent). -- Each ray has `from_line` and `to_line` indicating start of `a` textobject. for i = #rays, 1, -1 do local ray = rays[i] -- If current indent is bigger, then ray is cast over non-blank region. -- This assumes that line at `line_num` is not blank. if ray.indent < indent then ray.is_empty = false -- All previously cast rays are already marked as non-blank if they are break end -- If ray was cast from bigger indent then current and spans over -- non-empty region, finalize it as it has hit its limit if not ray.is_empty then ray.to_line = line_num table.insert(rays_final, ray) end rays[i] = nil end -- Start new ray table.insert(rays, { indent = indent, from_line = line_num, is_empty = true }) end -- Pickers -------------------------------------------------------------------- H.validate_pick = function(fun_name) local has_pick, pick = pcall(require, 'mini.pick') if not has_pick then H.error(string.format([[`pickers.%s()` requires 'mini.pick' which can not be found.]], fun_name)) end return pick end H.pick_start = function(items, default_opts, opts) local pick = H.validate_pick() local fallback = { source = { preview = pick.default_preview, choose = pick.default_choose, choose_marked = pick.default_choose_marked, }, } local opts_final = vim.tbl_deep_extend('force', fallback, default_opts, opts or {}, { source = { items = items } }) return pick.start(opts_final) end H.pick_highlight_line = function(buf_id, line, hl_group, priority) local opts = { end_row = line, end_col = 0, hl_mode = 'blend', hl_group = hl_group, priority = priority } vim.api.nvim_buf_set_extmark(buf_id, H.ns_id.pickers, line - 1, 0, opts) end H.pick_prepend_position = function(item) local path if item.path ~= nil then path = item.path elseif H.is_valid_buf(item.bufnr) then local name = vim.api.nvim_buf_get_name(item.bufnr) path = name == '' and ('Buffer_' .. item.bufnr) or name end if path == nil then return item end path = vim.fn.fnamemodify(path, ':p:.') local text = item.text or '' local suffix = text == '' and '' or (': ' .. text) item.text = string.format('%s:%s:%s%s', path, item.lnum or 1, item.col or 1, suffix) return item end H.pick_clear_namespace = function(buf_id, ns_id) pcall(vim.api.nvim_buf_clear_namespace, buf_id, ns_id, 0, -1) end H.pick_make_no_preview = function(picker_name) local lines = { string.format('No preview available for `%s` picker', picker_name) } return function(buf_id, _) H.set_buflines(buf_id, lines) end end H.pick_validate_one_of = function(target, opts, values, picker_name) if vim.tbl_contains(values, opts[target]) then return opts[target] end local msg = string.format( '`pickers.%s` has wrong "%s" local option (%s). Should be one of %s.', picker_name, target, vim.inspect(opts[target]), table.concat(vim.tbl_map(vim.inspect, values), ', ') ) H.error(msg) end H.pick_validate_scope = function(...) return H.pick_validate_one_of('scope', ...) end H.pick_get_config = function() return vim.tbl_deep_extend('force', (require('mini.pick') or {}).config or {}, vim.b.minipick_config or {}) end H.make_show_in_target_win = function(fun_name, show_fun) local pick = H.validate_pick(fun_name) return function(item) local win_target = (pick.get_picker_state().windows or {}).target if win_target == nil or not H.is_valid_win(win_target) then return end local buf_id = vim.api.nvim_create_buf(true, true) show_fun(buf_id, item) vim.api.nvim_win_set_buf(win_target, buf_id) end end H.show_with_icons = function(buf_id, items, query) require('mini.pick').default_show(buf_id, items, query, { show_icons = true }) end H.choose_with_buflisted = function(item) local pick = require('mini.pick') pick.default_choose(item) -- Force 'buflisted' on opened item local win_target = pick.get_picker_state().windows.target local buf_id = vim.api.nvim_win_get_buf(win_target) vim.bo[buf_id].buflisted = true end -- Diagnostic picker ---------------------------------------------------------- H.diagnostic_make_compare = function(sort_by) if sort_by == 'severity' then return function(a, b) if a.severity < b.severity then return true end if a.severity > b.severity then return false end if a.path < b.path then return true end if a.path > b.path then return false end if a.lnum < b.lnum then return true end if a.lnum > b.lnum then return false end return a.col < b.col end end if sort_by == 'path' then return function(a, b) if a.path < b.path then return true end if a.path > b.path then return false end if a.severity < b.severity then return true end if a.severity > b.severity then return false end if a.lnum < b.lnum then return true end if a.lnum > b.lnum then return false end return a.col < b.col end end return nil end -- Git pickers ---------------------------------------------------------------- H.validate_git = function(picker_name) if vim.fn.executable('git') == 1 then return true end local msg = string.format('`pickers.%s` requires executable `git`.', picker_name) H.error(msg) end H.git_normalize_path = function(path, picker_name) path = type(path) == 'string' and path or vim.fn.getcwd() if path == '' then H.error(string.format('Path in `%s` is empty.', picker_name)) end path = H.full_path(path) local path_is_dir, path_is_file = vim.fn.isdirectory(path) == 1, vim.fn.filereadable(path) == 1 if not (path_is_dir or path_is_file) then H.error('Path ' .. path .. ' is not a valid path.') end return path, path_is_dir and 'directory' or 'file' end H.git_get_repo_dir = function(path, path_type, picker_name) local path_dir = path_type == 'directory' and path or vim.fn.fnamemodify(path, ':h') local repo_dir = vim.fn.systemlist({ 'git', '-C', path_dir, 'rev-parse', '--show-toplevel' })[1] if vim.v.shell_error ~= 0 then local msg = string.format('`pickers.%s` could not find Git repo for %s.', picker_name, path) H.error(msg) end return repo_dir end H.git_difflines_to_hunkitems = function(lines, n_context) local header_pattern = '^diff %-%-git' local hunk_pattern = '^@@ %-%d+,?%d* %+(%d+),?%d* @@' local to_path_pattern = '^%+%+%+ b/(.*)$' -- Parse diff lines local cur_header, cur_path, is_in_hunk = {}, nil, false local items = {} for _, l in ipairs(lines) do -- Separate path header and hunk for better granularity if l:find(header_pattern) ~= nil then is_in_hunk = false cur_header = {} end local path_match = l:match(to_path_pattern) if path_match ~= nil and not is_in_hunk then cur_path = path_match end local hunk_start = l:match(hunk_pattern) if hunk_start ~= nil then is_in_hunk = true local item = { path = cur_path, lnum = tonumber(hunk_start), header = vim.deepcopy(cur_header), hunk = {} } table.insert(items, item) end if is_in_hunk then table.insert(items[#items].hunk, l) else table.insert(cur_header, l) end end -- Correct line number to point at the first change local try_correct_lnum = function(item, i) if item.hunk[i]:find('^[+-]') == nil then return false end item.lnum = item.lnum + i - 2 return true end for _, item in ipairs(items) do for i = 2, #item.hunk do if try_correct_lnum(item, i) then break end end end -- Construct aligned text from path and hunk header local text_parts, path_width, coords_width = {}, 0, 0 for i, item in ipairs(items) do local coords, title = item.hunk[1]:match('@@ (.-) @@ ?(.*)$') coords, title = coords or '', title or '' text_parts[i] = { item.path, coords, title } path_width = math.max(path_width, vim.fn.strchars(item.path)) coords_width = math.max(coords_width, vim.fn.strchars(coords)) end for i, item in ipairs(items) do local parts = text_parts[i] local path, coords = H.ensure_text_width(parts[1], path_width), H.ensure_text_width(parts[2], coords_width) item.text = string.format('%s │ %s │ %s', path, coords, parts[3]) end return items end -- LSP picker ----------------------------------------------------------------- H.lsp_make_on_list = function(source, opts) -- Prepend file position info to item and sort local process = function(items) if source ~= 'document_symbol' then items = vim.tbl_map(H.pick_prepend_position, items) end table.sort(items, H.lsp_items_compare) return items end -- Highlight items with highlight group corresponding to the symbol kind. -- Note: `@type` groups were introduced in Neovim 0.8 which is minimal -- version for `pickers.lsp` to work. local show if source == 'document_symbol' or source == 'workspace_symbol' then local pick = H.validate_pick() show = function(buf_id, items_to_show, query) pick.default_show(buf_id, items_to_show, query) H.pick_clear_namespace(buf_id, H.ns_id.pickers) for i, item in ipairs(items_to_show) do -- Highlight using '@...' style highlight group with similar name local hl_group = string.format('@%s', string.lower(item.kind or 'unknown')) H.pick_highlight_line(buf_id, i, hl_group, 199) end end end return function(data) local items = data.items for _, item in ipairs(data.items) do item.text, item.path = item.text or '', item.filename or nil end items = process(items) return H.pick_start(items, { source = { name = string.format('LSP (%s)', source), show = show } }, opts) end end H.lsp_items_compare = function(a, b) local a_path, b_path = a.path or '', b.path or '' if a_path < b_path then return true end if a_path > b_path then return false end local a_lnum, b_lnum = a.lnum or 1, b.lnum or 1 if a_lnum < b_lnum then return true end if a_lnum > b_lnum then return false end local a_col, b_col = a.col or 1, b.col or 1 if a_col < b_col then return true end if a_col > b_col then return false end return tostring(a) < tostring(b) end -- List picker ---------------------------------------------------------------- H.list_get = { quickfix = function() return vim.tbl_map(H.list_enhance_qf_loc, vim.fn.getqflist()) end, location = function() return vim.tbl_map(H.list_enhance_qf_loc, vim.fn.getloclist(0)) end, jump = function() local raw = vim.fn.getjumplist()[1] -- Tweak output: reverse for more relevance; make 1-based column local res, n = {}, #raw for i, x in ipairs(raw) do x.col = x.col + 1 res[n - i + 1] = x end return res end, change = function() local cur_buf = vim.api.nvim_get_current_buf() local res = vim.fn.getchangelist(cur_buf)[1] for _, x in ipairs(res) do x.bufnr = cur_buf end return res end, } H.list_enhance_qf_loc = function(item) if item.end_lnum == 0 then item.end_lnum = nil end if item.end_col == 0 then item.end_col = nil end if H.is_valid_buf(item.bufnr) then local filename = vim.api.nvim_buf_get_name(item.bufnr) if filename ~= '' then item.filename = filename end end return item end H.list_enhance_item = function(item) if vim.fn.filereadable(item.filename) == 1 then item.path = item.filename end return H.pick_prepend_position(item) end -- Explorer picker ------------------------------------------------------------ H.explorer_make_items = function(path, filter, sort) if vim.fn.isdirectory(path) == 0 then return {} end local res = { { fs_type = 'directory', path = vim.fn.fnamemodify(path, ':h'), text = '..' } } for _, basename in ipairs(vim.fn.readdir(path)) do local subpath = string.format('%s/%s', path, basename) local fs_type = vim.fn.isdirectory(subpath) == 1 and 'directory' or 'file' table.insert(res, { fs_type = fs_type, path = subpath, text = basename .. (fs_type == 'directory' and '/' or '') }) end return sort(vim.tbl_filter(filter, res)) end H.explorer_default_sort = function(items) -- Sort ignoring case local res = vim.tbl_map(function(x) --stylua: ignore return { fs_type = x.fs_type, path = x.path, text = x.text, is_dir = x.fs_type == 'directory', lower_name = x.text:lower(), } end, items) local compare = function(a, b) -- Put directory first if a.is_dir and not b.is_dir then return true end if not a.is_dir and b.is_dir then return false end -- Otherwise order alphabetically ignoring case return a.lower_name < b.lower_name end table.sort(res, compare) return vim.tbl_map(function(x) return { fs_type = x.fs_type, path = x.path, text = x.text } end, res) end -- CLI ------------------------------------------------------------------------ H.cli_run = function(command, stdout_hook) stdout_hook = stdout_hook or function() end local executable, args = command[1], vim.list_slice(command, 2, #command) local process, stdout, stderr = nil, vim.loop.new_pipe(), vim.loop.new_pipe() local spawn_opts = { args = args, stdio = { nil, stdout, stderr } } process = vim.loop.spawn(executable, spawn_opts, function() process:close() end) H.cli_read_stream(stdout, stdout_hook) H.cli_read_stream(stderr, function(lines) local msg = table.concat(lines, '\n') if msg == '' then return end H.error(msg) end) end H.cli_show_output = function(buf_id, command) local stdout_hook = vim.schedule_wrap(function(lines) if not H.is_valid_buf(buf_id) then return end H.set_buflines(buf_id, lines) end) H.cli_run(command, stdout_hook) end H.cli_read_stream = function(stream, post_hook) local data_feed = {} local callback = function(err, data) assert(not err, err) if data ~= nil then return table.insert(data_feed, data) end local lines = vim.split(table.concat(data_feed), '\n') data_feed = nil stream:close() post_hook(lines) end stream:read_start(callback) end -- Buffers -------------------------------------------------------------------- H.is_valid_buf = function(buf_id) return type(buf_id) == 'number' and vim.api.nvim_buf_is_valid(buf_id) end H.buf_ensure_loaded = function(buf_id) if type(buf_id) ~= 'number' or vim.api.nvim_buf_is_loaded(buf_id) then return end local cache_eventignore = vim.o.eventignore vim.o.eventignore = 'BufEnter' pcall(vim.fn.bufload, buf_id) vim.o.eventignore = cache_eventignore end H.buf_get_name = function(buf_id) if not H.is_valid_buf(buf_id) then return nil end local buf_name = vim.api.nvim_buf_get_name(buf_id) if buf_name ~= '' then buf_name = vim.fn.fnamemodify(buf_name, ':~:.') end return buf_name end H.set_buflines = function(buf_id, lines) vim.api.nvim_buf_set_lines(buf_id, 0, -1, false, lines) end -- Utilities ------------------------------------------------------------------ H.error = function(msg) error(string.format('(mini.extra) %s', msg), 0) end H.is_valid_win = function(win_id) return type(win_id) == 'number' and vim.api.nvim_win_is_valid(win_id) end H.ensure_text_width = function(text, width) local text_width = vim.fn.strchars(text) if text_width <= width then return text .. string.rep(' ', width - text_width) end return '…' .. vim.fn.strcharpart(text, text_width - width + 1, width - 1) end H.full_path = function(path) return (vim.fn.fnamemodify(path, ':p'):gsub('(.)/$', '%1')) end H.short_path = function(path, cwd) cwd = cwd or vim.fn.getcwd() if not vim.startswith(path, cwd) then return vim.fn.fnamemodify(path, ':~') end local res = path:sub(cwd:len() + 1):gsub('^/+', ''):gsub('/+$', '') return res end return MiniExtra
import { CursorMessage, TextMessage, messageSchema } from "@/party/schema" import { Button, TextField } from "@kobalte/core" import { useParams, useSearchParams } from "@solidjs/router" import PartySocket from "partysocket" import { HiSolidPaperAirplane } from "solid-icons/hi" import { For, createEffect, createSignal, on, onCleanup, onMount, } from "solid-js" export default function Room() { const { roomId } = useParams() const [{ user: userId }] = useSearchParams() if (!userId) throw new Error("No `user` in search params") const { texts, sendText, cursors } = createChatRoom({ roomId, userId }) const [draft, setDraft] = createSignal("") let chatRef: HTMLDivElement | undefined createEffect( on([texts], () => { chatRef?.scrollTo({ top: chatRef?.scrollHeight }) }), ) return ( <> <For each={cursors()}> {(cursor) => ( <div class="absolute rounded-2xl rounded-tl-none bg-teal-800 px-3 py-1" style={{ top: cursor.y + "%", left: cursor.x + "%", }} > {cursor.user} </div> )} </For> <div class="mx-auto flex h-screen max-w-2xl flex-col gap-6 p-10"> <div class="flex-1 overflow-auto" ref={chatRef}> <For each={texts()} fallback={<div>No messages</div>}> {(text) => ( <div> {text.user}: {text.content} </div> )} </For> </div> <form class="relative" onSubmit={(e) => { e.preventDefault() const draftToSend = draft().trim() if (draftToSend === "") return sendText(draftToSend) setDraft("") }} > <TextField.Root value={draft()} onChange={setDraft}> <TextField.TextArea class="w-full resize-none rounded-md border border-gray-700 bg-gray-800 py-2 pl-3 pr-11 align-bottom text-white outline-none ring-offset-2 ring-offset-gray-950 placeholder:text-gray-500 focus:ring-2 focus:ring-teal-400" placeholder="Type a message..." autoResize submitOnEnter /> </TextField.Root> <Button.Root class="absolute bottom-2 right-2 rounded-sm bg-teal-700 px-1 py-1 text-white outline-none ring-offset-2 ring-offset-gray-950 hover:bg-teal-600 focus:ring-2 focus:ring-teal-400 kb-disabled:bg-transparent kb-disabled:text-gray-500" type="submit" disabled={!draft()} > <HiSolidPaperAirplane /> </Button.Root> </form> </div> </> ) } function createChatRoom({ roomId, userId, }: { roomId: string userId: string }) { const [texts, setTexts] = createSignal<TextMessage[]>([]) const [cursors, setCursors] = createSignal<CursorMessage[]>([]) const ws = new PartySocket({ host: "localhost:1999", room: roomId, party: "main", }) createEffect(() => { ws.onmessage = (event) => { const message = messageSchema.parse(JSON.parse(event.data)) if (message.type === "join") { setTexts(message.texts) return } if (message.type === "text") { setTexts([...texts(), message]) return } if (message.type === "cursor") { setCursors([ ...cursors().filter((c) => c.user !== message.user), message, ]) return } } }) const sendCursor = (e: MouseEvent) => { const cursorMessage = { type: "cursor", user: userId, x: (e.clientX / window.innerWidth) * 100, y: (e.clientY / window.innerHeight) * 100, } satisfies CursorMessage ws.send(JSON.stringify(cursorMessage)) } onMount(() => window.addEventListener("mousemove", sendCursor)) onCleanup(() => window.removeEventListener("mousemove", sendCursor)) const sendText = (content: string) => { const message = { type: "text", user: userId, content, } satisfies TextMessage setTexts((prevTexts) => [...prevTexts, message]) ws.send(JSON.stringify(message)) } return { texts, sendText, cursors } }