text
stringlengths
184
4.48M
#' Descriptive: Table descritive analysis #' @description Function for generating a data.frame with averages or other descriptive measures grouped by a categorical variable #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param data data.frame containing the first column with the categorical variable and the remaining response columns #' @param fun Function of descriptive statistics (default is mean) #' @return Returns a data.frame with a measure of dispersion or position from a dataset and separated by a factor #' @keywords descriptive #' @export #' @examples #' data(pomegranate) #' tabledesc(pomegranate) #' library(knitr) #' kable(tabledesc(pomegranate)) tabledesc=function(data, fun=mean){ dados=data[,-1] trat=as.vector(unlist(data[,1])) n=nlevels(as.factor(trat)) nr=ncol(dados)-1 medias=data.frame(matrix(1:(n*nr),ncol = nr)) for(i in 1:ncol(dados)){ medias[,i]=tapply(as.vector(unlist(dados[,i])), trat, fun, na.rm=TRUE)[unique(trat)]} colnames(medias)=colnames(dados) rownames(medias)=unique(trat) print(medias)}
package com.example.luckynumapp import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast import org.w3c.dom.Text import kotlin.random.Random class LuckyNumberActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_lucky_number) val text1:TextView = findViewById(R.id.text1) val luckyText:TextView = findViewById(R.id.luckyNumTxt) val shareBtn:Button = findViewById(R.id.sharebtn) var username = receiveUserName() Toast.makeText(this,""+username,Toast.LENGTH_LONG).show() var random_num = generateRanNum() luckyText.setText(""+random_num) shareBtn.setOnClickListener(){ shareData(username,random_num) } } fun receiveUserName():String{ var bundle:Bundle?= intent.extras var username = bundle?.get("name").toString() return username } fun generateRanNum():Int{ val random = Random.nextInt(1000) return random } //sharing username and number fun shareData(username:String,num:Int){ //implicit intent var i = Intent(Intent.ACTION_SEND) i.setType("text/plain") i.putExtra(Intent.EXTRA_SUBJECT,"$username is lucky today") i.putExtra(Intent.EXTRA_TEXT, "His lucky number is $num") startActivity(i) } }
/* trait field @aliasing does not work when Maps are traited */ package openehr.test; import java.util.*; import org.drools.factmodel.traits.Alias global java.util.List list; declare org.drools.factmodel.MapCore //what is this for end declare trait Citizen @traitable citizenship : String = "Unknown" end declare trait Student extends Citizen @propertyReactive ID : String = "412314" @Alias("personID") GPA : Double = 3.99 end declare Person @Traitable personID : String isStudent : boolean end declare trait Worker @propertyReactive //customer : Citizen hasBenefits : Boolean = true end declare trait StudentWorker extends Worker @propertyReactive //currentStudent : Citizen @Alias("customer") tuitionWaiver : Boolean @Alias("hasBenefits") end rule "1" salience 1 no-loop when then Person p = new Person("1020",true); Map map = new HashMap(); map.put("isEmpty",true); insert(p); insert(map); list.add("initialized"); end rule "2" salience 1 no-loop when $stu : Person(isStudent == true) $map : Map(this["isEmpty"] == true) then Student s = don( $stu , Student.class ); $map.put("worker" , s); $map.put("isEmpty" , false); $map.put("hasBenefits",null); update($map); System.out.println("don: Person -> Student "); list.add("student is donned"); end rule "3" salience 1 no-loop when $map : Map($stu : this["worker"]) Map($stu isA Student.class, this == $map) then Object obj = don( $map , Worker.class ); System.out.println("don: Map -> Worker : "+obj); list.add("worker is donned"); end rule "4" salience 1 no-loop when $stu : Student() then Object obj = don( $stu , StudentWorker.class ); System.out.println("don: Map -> StudentWorker : "+obj); list.add("studentworker is donned"); end rule "5" salience 1 no-loop when StudentWorker(tuitionWaiver == true) then System.out.println("tuitionWaiver == true"); list.add("tuitionWaiver is true"); end
<template> <div class="text-selection-demo"> <h2>TextSelection Test</h2> <h3>基本使用</h3> <m-text-selection ref="textRef1" :text="text" :defaultList="defaultList" :optionList="optionList" @selected="onSelected" @onBlurContent="onBlurContent" @onFocusContent="onFocusContent" theme="light" ></m-text-selection> <br /> <p>选择的文本标签:</p> <ul> <li v-for="item in selectedList" :class="item.focus ? 'text-selection-demo-focus' : ''"> {{ item.start }} - {{ item.end }} , {{ item.text }}: {{ extractTagName(item.tagList) }} </li> </ul> </div> </template> <script lang="ts" setup> import { ref, onBeforeUnmount } from 'vue' import { registerSelection } from '@wxp-ui/utils' function extractTagName(list) { return list.map(o => o.attrName).join('') } // 业务数据 const defaultList = [] || [ { start: 0, end: 11, text: 'Hello World', tagList: [1], }, { start: 0, end: 5, text: 'Hello', tagList: [2], }, { start: 27, end: 32, text: '明月,对影', tagList: [2], }, { start: 22, end: 35, text: '亲;举杯邀明月,对影成三人', tagList: [1], }, ] const tag = ['使用场景', '产品名称', '颜色', '口味', '净含量', '优惠信息'] const optionList = new Array(tag.length).fill('').map((o, idx) => { return { attrId: idx, attrName: tag[idx], } }) // case 1 const selectedList = ref('') const text = ref( 'Hello World 花间一壶酒,独酌无相亲;举杯邀明月,对影成三人,月既不解饮,影徒随我身; 暂伴月将影,行乐须及春;我歌月徘徊,我舞影零乱; 醒时相交欢,醉后各分散,永结无情游,相期邈云汉' ) function onSelected(val, str) { selectedList.value = val console.log('onSelected', str) } function onBlurContent(v) { console.log(v) } function onFocusContent() { console.log('测试focus事件') } // 使用 const textRef1 = ref() const textRefList = [textRef1] // 注册全局 registerSelection(textRefList) </script> <style lang="less"> section { border: 1px solid; } .text-selection-demo-focus { background: pink; } </style>
import { ElasticsearchService } from '@nestjs/elasticsearch'; import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; import { CreateProductInput } from './dto/createProduct.input'; import { UpdateProductInput } from './dto/updateProduct.input'; import { Product } from './entities/product.entity'; import { ProductService } from './product.service'; @Resolver() export class ProductResolver { constructor( private readonly productService: ProductService, // private readonly elasticsearchService: ElasticsearchService, ) {} // // 상품 등록 API @Mutation(() => Product) // 리턴 타입 지정 createProduct( @Args('createProductInput') createProductInput: CreateProductInput, ) { // // 엘라스틱서치 등록 연습 // this.elasticsearchService.create({ // id: 'myid', // index: 'myproduct03', // document: { // ...createProductInput, // }, // }); // // 엘라스틱서치에 등록해보기 위한 주석 return this.productService.create({ createProductInput }); } // // 상품 조회 API @Query(() => Product) fetchProduct( @Args('productId') productId: string, // ) { return this.productService.find({ productId }); } // // 상품 모두 조회 API @Query(() => [Product]) async fetchProducts( @Args({ name: 'search', nullable: true, }) search: string, ) { // // 엘라스틱서치에서 조회하기 연습 const result = await this.elasticsearchService.search({ index: 'myproduct0333', query: { bool: { should: [{ prefix: { name: search } }], }, }, }); console.log(JSON.stringify(result, null, ' ')); // // 엘라스틱서치에서 조회하기 위한 주석 // return this.productService.findAll(); } // // 상품 수정 API @Mutation(() => Product) async updateProduct( @Args('productId') productId: string, @Args('updateProductInput') updateProductInput: UpdateProductInput, ) { // 수정 조건 // 판매 완료 상품인지 확인 await this.productService.checkSoldout({ productId }); // 수정 완료 return await this.productService.update({ productId, updateProductInput }); } @Mutation(() => Boolean) deleteProduct(@Args('productId') productId: string) { return this.productService.delete({ productId }); } }
==== QUnit Test Suite for CiviCRM ==== QUnit is a JavaScript-based unit-testing framework. It is ideally suited to testing pure-JavaScript modules -- for example, jQuery, Backbone, and many of their plugins test with QUnit. For more details about, see: http://qunitjs.com/ http://qunitjs.com/cookbook/ CiviCRM is a large application and may include some pure-Javascript components -- one should use QUnit to test these components. Note: CiviCRM also includes many non-Javascript components (MySQL, PHP, etc). For integration-testing that encompasses all of CiviCRM's different technologies, see the CiviCRM WebTest suite. QUnit is *only* appropriate unit-testing of pure JS. Note: When making a new JS component, consider designing a package which doesn't depend on CivCRM at all -- put it in its own repo and handle the testing yourself. This is ideal for collaborating with developers on other projects (beside CiviCRM). When the package is stable, you can import your package into CiviCRM's codebase (by way of "packages/" or "vendors/"). Note: The primary benefit of using this system -- rather than a vanilla QUnit deployment -- is that you can include dependencies based on Civi's conventions. The primary drawback is that the test will require CiviCRM to execute. However, if you really need to write a Javascript component in CiviCRM core (or in a CiviCRM extension), then proceed with testing it... ==== QUICKSTART ==== To see an example test-suite: 1. Inspect the example code "civicrm/tests/qunit/example" 2. Run the example code by logging into CiviCRM as administrator and visiting: http://localhost/civicrm/dev/qunit/civicrm/example (Modify "localhost" to match your CiviCRM installation.) To create a new test-suite: 1. Determine a name for the new test-suite, such as "my-stuff". 2. Copy "civicrm/tests/qunit/example" to "civicrm/tests/qunit/my-stuff" 3. Edit the "civicrm/tests/qunit/my-stuff/test.php" to load your JS file (my-stuff.js) as well as any special dependencies (jQuery plugins, Backbone, etc). 4. Edit the "civcrm/tests/qunit/my-stuff/test.js" 5. To run the test-suite, login to CiviCRM as administrator and visit: http://${base_url}/civicrm/dev/qunit/${extension}/${suite} For example, suppose the base_url is "localhost", and suppose the qunit test is part of the core codebase (aka extension="civicrm"), and suppose the suite is "my-stuff". Then navigate to: http://localhost/civicrm/dev/qunit/civicrm/my-stuff ==== CONVENTIONS ==== The following is a quick draft of coding conventions. If there's a problem with it, we can change it -- but please communicate any problems/issues (e.g. via IRC, mailing-list, or forum). * CiviCRM includes multiple test-suites. One test-suite should be created for each logically distinct JavaScript component. Rationale: CiviCRM is a large application with a diverse mix of components written by diverse authors. Each component may present different requirements for testing -- e.g. HTML fixtures, CSS fixtures, third-party JS dependencies, etc. Note: As a rule-of-thumb, if you add a new js file to CiviCRM ("civicrm/js/foo.js"), and if that file is useful on its own, then you might create a new test-suite for it ("civicrm/tests/qunit/foo"). * Each QUnit test-suite for CiviCRM lives in a subdirectory of "tests/qunit/". Rationale: Following a predictable naming convention will help us automate testing/loading across all suites, and it will make the code more recognizable to other developers. * Each QUnit test-suite *may* include the file "test.php" to specify loading of resource files or bundles (such as CSS/JS). The file will be recognized automatically. Rationale: CiviCRM has its own resource-loading conventions. When preparing a test environment, one needs to load JS/CSS dependencies. Since there is no autoloader, this is most easily done with CiviCRM's resource-loader. * Each QUnit test-suite *may* include the file "test.tpl" to specify any HTML or CSS fixtures. The file will be recognized automatically. * Each QUnit test-suite *may* include the file "test.js" to specify assertions. The file will be recognized automatically. If one wants to split the tests into multiple JS files, then each file should registered as a resource in "test.php". ==== TODO ==== * GUI Testing -- Display a browsable list of all tests. * Automatic Testing -- Add an item to the WebTest suite (e.g. WebTest_Core_QUnitTestCase) which iteratively executes each QUnit test-suite and verifies that they pass.
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User, Patient, Doctor, Medication, Staff class CustomUserAdmin(UserAdmin): # Add user_type to the list display in the Django admin list_display = ('username', 'email', 'user_type') # Include user_type in the fieldsets to make it editable in the admin form fieldsets = UserAdmin.fieldsets + ( (None, {'fields': ('user_type',)}), ) class PatientAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name', 'date_of_birth', 'gender', 'address', 'phone_number', 'email') search_fields = ('first_name', 'last_name', 'email') class DoctorAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name', 'specialization', 'phone_number', 'email', 'department') search_fields = ('first_name', 'last_name', 'email', 'specialization') # Registering the models admin.site.register(User, CustomUserAdmin) admin.site.register(Patient, PatientAdmin) admin.site.register(Doctor, DoctorAdmin) admin.site.register(Medication) admin.site.register(Staff)
package data; import java.util.ArrayList; import java.util.List; import java.util.Map; import models.Place; import org.jpl7.Query; import org.jpl7.Term; /** * * @author Nelson Navarro */ public class ExtractData { private final String prologFile; public ExtractData(String prologFile) { this.prologFile = prologFile; } private Query getQuery(String query) { Query consultQuery = new Query("consult('" + prologFile + "')"); if (!consultQuery.hasSolution()) { System.out.println("Error de carga en datos."); return null; } return new Query(query); } public List<String> getPlaces() { List<String> places = new ArrayList<>(); Query getPlacesQuery = getQuery("place(Place,Lat,Lon)"); while (getPlacesQuery != null && getPlacesQuery.hasMoreSolutions()) { java.util.Map<String, Term> solution = getPlacesQuery.nextSolution(); Term placeTerm = solution.get("Place"); if (placeTerm != null) { places.add(placeTerm.toString()); } } return places; } public List<String> getRoute(String start, String end) { List<String> route = new ArrayList<>(); Query query = new Query("find_route(" + start + "," + end + ", Route)"); if (query.hasSolution()) { Map<String, Term> solution = query.oneSolution(); Term routeTerm = solution.get("Route"); if (routeTerm != null && routeTerm.isList()) { Term currentTerm = routeTerm; while (currentTerm.arity() == 2) { Term term = currentTerm.arg(1); String place = term.toString(); route.add(place); currentTerm = currentTerm.arg(2); } } } return route; } public Place getPlace(String placeName) { Query getPlacesQuery = getQuery("place("+placeName+", Lat, Lon)"); if (getPlacesQuery != null && getPlacesQuery.hasSolution()) { java.util.Map<String, Term> solution = getPlacesQuery.oneSolution(); Term latTerm = solution.get("Lat"); Term lonTerm = solution.get("Lon"); if (latTerm != null && lonTerm != null) { double latitude = latTerm.doubleValue(); double longitude = lonTerm.doubleValue(); return new Place(placeName, latitude, longitude); } } return null; } }
/** * Created by Pragma Labs * SPDX-License-Identifier: BUSL-1.1 */ pragma solidity 0.8.22; import { OracleModule } from "./abstracts/AbstractOM.sol"; import { IChainLinkData } from "../interfaces/IChainLinkData.sol"; import { IRegistry } from "./interfaces/IRegistry.sol"; /** * @title Abstract Oracle Module * @author Pragma Labs * @notice Oracle Module for Chainlink Oracles. */ contract ChainlinkOM is OracleModule { STORAGE // Map oracle => flag. mapping(address => bool) internal inOracleModule; // Map oracle => oracle identifier. mapping(address => uint256) public oracleToOracleId; // Map oracle identifier => oracle information. mapping(uint256 => OracleInformation) public oracleInformation; struct OracleInformation { // The cutoff time after which an oracle is considered stale. uint32 cutOffTime; // The correction with which the oracle-rate has to be multiplied to get a precision of 18 decimals. uint64 unitCorrection; // The contract address of the oracle. address oracle; } ERRORS error Max18Decimals(); CONSTRUCTOR /** * @param registry_ The contract address of the Registry. */ constructor(address registry_) OracleModule(registry_) { } ORACLE MANAGEMENT /** * @notice Adds a new oracle to this Oracle Module. * @param oracle The contract address of the oracle. * @param baseAsset Label for the base asset. * @param quoteAsset Label for the quote asset. * @return oracleId Unique identifier of the oracle. */ function addOracle(address oracle, bytes16 baseAsset, bytes16 quoteAsset, uint32 cutOffTime) external onlyOwner returns (uint256 oracleId) { if (inOracleModule[oracle]) revert OracleAlreadyAdded(); uint256 decimals = IChainLinkData(oracle).decimals(); if (decimals > 18) revert Max18Decimals(); inOracleModule[oracle] = true; oracleId = IRegistry(REGISTRY).addOracle(); oracleToOracleId[oracle] = oracleId; assetPair[oracleId] = AssetPair({ baseAsset: baseAsset, quoteAsset: quoteAsset }); oracleInformation[oracleId] = OracleInformation({ cutOffTime: cutOffTime, unitCorrection: uint64(10 ** (18 - decimals)), oracle: oracle }); } ORACLE INFORMATION /** * @notice Returns the state of an oracle. * @param oracleId The identifier of the oracle to be checked. * @return oracleIsActive Boolean indicating if the oracle is active or not. */ function isActive(uint256 oracleId) external view override returns (bool oracleIsActive) { (oracleIsActive,) = _getLatestAnswer(oracleInformation[oracleId]); } PRICING LOGIC /** * @notice Retrieves answer from oracle and does sanity and staleness checks (BaseAsset/QuoteAsset). * @param oracleInformation_ Struct will all the necessary information of the oracle. * @return success Bool indicating is the oracle is still active and performing as expected. * @return answer The latest oracle value. * @dev The following checks are done: * - A call to the oracle contract does not revert. * - The roundId is not zero. * - The answer is not negative. * - The oracle is not stale (last update was longer than the cutoff time ago). * - The oracle update was not done in the future. */ function _getLatestAnswer(OracleInformation memory oracleInformation_) internal view returns (bool success, uint256 answer) { try IChainLinkData(oracleInformation_.oracle).latestRoundData() returns ( uint80 roundId, int256 answer_, uint256, uint256 updatedAt, uint80 ) { if ( roundId > 0 && answer_ >= 0 && updatedAt > block.timestamp - oracleInformation_.cutOffTime && updatedAt <= block.timestamp ) { success = true; answer = uint256(answer_); } } catch { } } /** * @notice Returns the rate of the BaseAsset in units of QuoteAsset (BaseAsset/QuoteAsset). * @param oracleId The identifier of the oracle. * @return oracleRate The rate of the BaseAsset in units of QuoteAsset, with 18 decimals precision. * @dev The oracle rate expresses how much tokens of the QuoteAsset are required * to buy 1 token of the BaseAsset, with 18 decimals precision. * Example: If you have an oracle (WBTC/USDC) and assume an exchange rate from Bitcoin to USD of $30 000. * -> You need 30 000 tokens of USDC to buy one token of WBTC. * -> Since we use 18 decimals precision, the oracleRate will be 30 000 * 10**18. */ function getRate(uint256 oracleId) external view override returns (uint256 oracleRate) { OracleInformation memory oracleInformation_ = oracleInformation[oracleId]; (bool success, uint256 answer) = _getLatestAnswer(oracleInformation_); // If the oracle is not active, the transactions revert. // This implies that no new credit can be taken against assets that use the decommissioned oracle, // but at the same time positions with these assets cannot be liquidated. // A new oracleSequence for these assets must be set ASAP in their Asset Modules by the protocol owner. if (!success) revert InactiveOracle(); // Only overflows at absurdly large rates, when rate > type(uint256).max / 10 ** (18 - decimals). // This is 1.1579209e+59 for an oracle with 0 decimals. unchecked { oracleRate = answer * oracleInformation_.unitCorrection; } } }
import styled from '@emotion/styled' import { FC } from 'react' import scroll from 'assets/icons/icon_scroll.svg' import scrollActive from 'assets/icons/icon_scroll_active.svg' const Wrapper = styled.footer({ width: '100%', backgroundColor: '#414141', padding: '56px 16px', boxSizing: 'border-box', position: 'relative', }) const Nav = styled.ul({ maxWidth: 960, margin: 'auto', display: 'flex', columnGap: 16, }) const NavItem = styled.li({ fontSize: 11, fontWeight: '16px', color: '#fff', cursor: 'pointer', }) const ScrollToTop = styled.div({ position: 'absolute', right: 76, bottom: 'calc(100% + 16px)', width: 48, height: 48, cursor: 'pointer', background: `url(${scroll}) center center no-repeat`, transition: 'background 0.3s', '&:hover': { background: `url(${scrollActive}) center center no-repeat`, }, }) const Footer: FC = () => { const onScrollToTop = () => { window.scrollTo({ top: 0, behavior: 'smooth' }) } return ( <Wrapper> <Nav> <NavItem>会員登録</NavItem> <NavItem>運営会社</NavItem> <NavItem>利用規約</NavItem> <NavItem>個人情報の取扱について</NavItem> <NavItem>特定商取引法に基づく表記</NavItem> <NavItem>お問い合わせ</NavItem> </Nav> <ScrollToTop onClick={onScrollToTop} /> </Wrapper> ) } export default Footer
'''Auction program which adds items into the database, and updates values''' #Setting the connection# import sqlite3 DATABASE = "../DB Browser/auction.db" connection = sqlite3.connect(DATABASE) cursor = connection.cursor() #Variables# ask = True status = "Unsold" num = 0 '''~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Start of program~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~''' #Adding items into database# print("Welcome to the auction program!") print("Enter quit to stop entering items") #Loop# while ask == True: #Item name# item = input("Enter the item name: ") #Check whether value = quit if item.strip().lower() == "quit": #End loop ask = False #Check whether value is blank elif item.strip() == "": #Error message print("Please do not enter blanks") else: #Reserve price# reserve = input("Enter the reserve price: ") #Check value is integer try: reserve = float(reserve) #Insert values cursor.execute("INSERT INTO item (name, reserve, purchaser, salePrice) VALUES (?, ?, ?, ?)", (item, reserve, status, num)) connection.commit() #Value is string except ValueError: #Check whether value = quit if reserve.lower().strip() == "quit": #End loop ask = False else: #Error message print("Please enter a integer") #Fetch all information about all items# cursor.execute("SELECT * FROM item") results = cursor.fetchall() #Print information print(f"{'Item ID':8} {'Item':25} {'Reserve price':13} {'Purchaser':10} {'Sold price':10}") for item in results: if item[4] == 0: print(f"{item[0]:8} {item[1]:25} {item[2]:13} {item[3]:10} {'None':10}") else: print(f"{item[0]:8} {item[1]:25} {item[2]:13} {item[3]:10} {item[4]:10}") #Entering values for updating# print("Enter quit to stop") #Loop# while ask == False: #Item ID# ID = input("Enter the item ID: ") #Check whether value is integer try: ID = int(ID) #Find all values with same ID cursor.execute("SELECT purchaser, reserve FROM item WHERE itemID = ?", (ID, )) results = cursor.fetchall() #Check whether results were found if len(results) == 0: #Error message print("No results found") else: #Purchaser# purchaser = input("Enter purchaser name: ") #Check whether the value = quit if purchaser.lower().strip() == "quit": #End loop ask = True #Check whether value is blank elif purchaser.strip() == "": #Error message print("Blanks are not accepted") else: #Sold price# sold = input("Enter the price which it was sold: ") #Check whether value is integer try: sold = float(sold) #Check whether item has been sold if results[0][0] == "Unsold": #Check whether sold price is under reserve if int(results[0][1]) > sold: print("This price is below the reserve") else: #Update the purchaser value and sale price value for the result with matching ID# cursor.execute("UPDATE item SET salePrice = ? AND purchaser = ? WHERE itemID = ?", (sold, purchaser, ID)) connection.commit() else: #Unavailable# print(results[0][0]) print("This item has already been sold") except ValueError: #Check whether value = quit if sold.lower().strip() == "quit": #End loop ask = True else: #Error message print("Please enter a integer") except ValueError: #Check whether value = quit if ID.lower().strip() == "quit": #End loop ask = True else: #Error message print("Please enter a integer") print("Thanks for using our program") print("Goodbye!") '''~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~End program~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'''
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>FCC: Survey Form</title> <link rel="stylesheet" href="styles.css"> </head> <body> <main> <h1 id="title">freeCodeCamp Survey Form</h1> <p id="description">Thank you for taking the time to help us improve the platform</p> <form id="survey-form"> <label id="name-label" for="name">Name:</label><br> <input type="text" id="name" name="name" placeholder="Enter your Name"><br> <label id="email-label" for="email">Email</label><br> <input type="email" placeholder="Enter your Email" id="email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" /><br> <label id="number-label" for="number"> Age:</label><br> <input type="number" placeholder="Enter your Age" id="number" min="18" max="123"><br> <label id="dropdown-dropdown" for="dropdown">Which option best describes your current role?</label><br> <select id="dropdown" name="dropdown"> <option value="student">Student</option> <option value="job">Full-time job</option> <option value="learner">Full-time learner</option> <option value="hidden">Prefer not to say</option> </select> <br> <label for="recommend">Would you recommend freeCodeCamp to a friend?</label> <fieldset id="group1"> <input id="definitely" type="radio" value="definitely" name="group1"> <label for="definitely">Definitely</label><br> <input id="maybe" type="radio" value="maybe" name="group1"> <label for="maybe">Maybe</label><br> <input id="not-sure" type="radio" value="not-sure" name="group1"> <label for="not-sure">Not sure</label><br> </fieldset> <label for="recommend">What would you like to see improved? <span>(Check all that apply)</span></label> <fieldset id="checkboxes-group"> <input id="front-end" type="checkbox" value="front-end" name="checkboxes-group"> <label for="front-end">Front-end Projects</label><br> <input id="back-end" type="checkbox" value="back-end" name="checkboxes-group"> <label for="back-end">Back-end Projects</label><br> <input id="data-viz" type="checkbox" value="data-viz" name="checkboxes-group"> <label for="data-viz">Data Visualization</label><br> <input id="challenges" type="checkbox" value="challenges" name="checkboxes-group"> <label for="challenges">Challenges</label><br> <input id="open-source" type="checkbox" value="open-source" name="checkboxes-group"> <label for="open-source">Open Source Community</label><br> <input id="gitter" type="checkbox" value="gitter" name="checkboxes-group"> <label for="gitter">Gitter help rooms</label><br> <input id="videos" type="checkbox" value="videos" name="checkboxes-group"> <label for="videos">Videos</label><br> <input id="city-meetups" type="checkbox" value="city-meetups" name="checkboxes-group"> <label for="city-meetups">City Meetups</label><br> <input id="wiki" type="checkbox" value="wiki" name="checkboxes-group"> <label for="wiki">Wiki</label><br> <input id="forum" type="checkbox" value="forum" name="checkboxes-group"> <label for="forum">Forum</label><br> <input id="additional-courses" type="checkbox" value="additional-courses" name="checkboxes-group"> <label for="additional-courses">Additional Courses</label><br> </fieldset> <textarea name="comments" form="comment" placeholder="Enter your comment here...."></textarea><br><br> <input type="submit" value="Submit"> </form> </main> </body> </html>
import { NextRequest, NextResponse } from "next/server"; // From: https://nextjs.org/docs/app/building-your-application/routing/internationalization export const middleware = async (request: NextRequest) => { const pathname = request.nextUrl.pathname; if (pathname.startsWith("/uploads")) { const destination = new URL( process.env.STRAPI_URL || "http://localhost:1337", ); const url = request.nextUrl.clone(); url.host = destination.host; url.port = destination.port; url.pathname = pathname; return NextResponse.rewrite(url); } const locales = ["fi", "en"]; const defaultLocale = "fi"; const pathnameHasLocale = locales.some( (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`, ); if (pathnameHasLocale) { return; } return NextResponse.redirect( new URL(`/${defaultLocale}/${pathname}`, request.url), ); }; export const config = { matcher: [ // Skip all internal paths (_next) "/((?!api|_next|favicon.ico).*)", // Optional: only run on root (/) URL // '/' ], };
"use client" import { useEffect, useRef, useState } from "react"; import Container from "../components/Container"; import Navbar from "../components/navbar/Navbar"; import Paragraph from "../components/pages/Paragraph"; import { AnimatePresence } from "framer-motion"; import StaticLoader from '../components/reusable/Loaders/StaticLoader' import Timeline from '../components/reusable/Timeline/Timeline' const About = () => { const [isLoading, setIsLoading] = useState(true); const containerRef = useRef(null); const options = { getDirection: true, }; useEffect(() => { setTimeout(() => { setIsLoading(false); document.body.style.cursor = 'default'; }, 1000) }, []) useEffect(() => { let scroll; // Import the Locomotive Scroll module dynamically import("locomotive-scroll").then((locomotiveModule) => { scroll = new locomotiveModule.default({ smooth: true, smoothMobile: false, resetNativeScroll: true }); }); return () => { if (scroll) { scroll.destroy(); } }; }, []); const primary = <div className='font-regular leading-tight'><span className="text-[#ff2257]">I am an interactive developer</span> based in India. I like <span className='text-[#ff2257]'>creating visually appealing experiences.</span> My goal is to inspire and connect with people through development and design.</div>; const secondary = <p className='font-regular leading-tight'>The main component of my design is<span className="text-[#ff2257]"> aesthetics.</span> I try to craft the perfect balance between <span className="text-[#ff2257]">aesthetics</span> and <span className="text-[#ff2257]">user experience.</span></p>; return ( <> <div className="font-gilroy"> <Container full={true}> <Navbar/> <div className=" bg-black h-full flex justify-center "> <AnimatePresence> { isLoading && <StaticLoader title='About'/> } </AnimatePresence> <div className={` bg-black transition duration-300 `}> <div className='flex h-full flex-col'> <Paragraph tag='Little bit about me' content={primary}/> {/* <Paragraph tag='Background' content={primary}/> */} <Timeline/> <Paragraph tag='Little bit about me' content={primary}/> </div> </div> </div> </Container> </div> </> ); } export default About;
<?php class Ecommerceguys_Inventorymanager_Block_Adminhtml_Vendor_Grid extends Mage_Adminhtml_Block_Widget_Grid { public function __construct() { parent::__construct(); $this->setId('vendorGrid'); $this->setDefaultSort('vendor_id'); $this->setDefaultDir('ASC'); $this->setSaveParametersInSession(true); } protected function _prepareCollection() { $collection = Mage::getModel('inventorymanager/vendor')->getCollection(); $this->setCollection($collection); return parent::_prepareCollection(); } protected function _prepareColumns() { $this->addColumn('vendor_id', array( 'header' => Mage::helper('inventorymanager')->__('ID'), 'align' =>'right', 'width' => '50px', 'index' => 'vendor_id', )); $this->addColumn('name', array( 'header' => Mage::helper('inventorymanager')->__('Name'), 'align' =>'left', 'index' => 'name', )); $this->addColumn('email', array( 'header' => Mage::helper('inventorymanager')->__('Email'), 'align' =>'left', 'index' => 'email', )); /*$this->addColumn('status', array( 'header' => Mage::helper('inventorymanager')->__('Status'), 'align' => 'left', 'width' => '80px', 'index' => 'status', 'type' => 'options', 'options' => array( 1 => 'Enabled', 2 => 'Disabled', ), ));*/ $this->addColumn('action', array( 'header' => Mage::helper('inventorymanager')->__('Action'), 'width' => '100', 'type' => 'action', 'getter' => 'getId', 'actions' => array( array( 'caption' => Mage::helper('inventorymanager')->__('Edit'), 'url' => array('base'=> '*/*/edit'), 'field' => 'id' ) ), 'filter' => false, 'sortable' => false, 'index' => 'stores', 'is_system' => true, )); //$this->addExportType('*/*/exportCsv', Mage::helper('inventorymanager')->__('CSV')); //$this->addExportType('*/*/exportXml', Mage::helper('inventorymanager')->__('XML')); return parent::_prepareColumns(); } protected function _prepareMassaction() { $this->setMassactionIdField('vendor_id'); $this->getMassactionBlock()->setFormFieldName('inventorymanager'); $this->getMassactionBlock()->addItem('delete', array( 'label' => Mage::helper('inventorymanager')->__('Delete'), 'url' => $this->getUrl('*/*/massDelete'), 'confirm' => Mage::helper('inventorymanager')->__('Are you sure?') )); return $this; } public function getRowUrl($row) { return $this->getUrl('*/*/edit', array('id' => $row->getId())); } }
/* * Created on Feb 26, 2006 * * Copyright (c) 2005 Peter Johan Salomonsen (http://www.petersalomonsen.com) * * http://www.frinika.com * * This file is part of Frinika. * * Frinika 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. * Frinika 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 Frinika; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.frinika.clipboard; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; /** * Methods for getting access to a clipboard instance * * Why shouldn't you call the getSystemClipboard() method * directly? Because this method requires clipboardAccess priveleges, and in case * you want to make an applet of Frinika, you could modify this getClipboard method * to return a local clipboard rather than the system clipboard (In case you want to use * an unsigned applet) * * @author Peter Johan Salomonsen */ public class ClipboardAccess { static Clipboard defaultClipboard = new Clipboard("Frinika"); /** * Returns the currently active clipboard. * @return */ public static Clipboard getClipboard() { // Problem using systemClipboard on windows? // return Toolkit.getDefaultToolkit().getSystemClipboard(); return defaultClipboard; } /** * A simple test of putting an object on the clipboard and getting it back again. * @param args * @throws Exception */ public static void main(String[] args) throws Exception { getClipboard().setContents(new Transferable() { public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { DataFlavor.stringFlavor }; } public boolean isDataFlavorSupported(DataFlavor flavor) { return true; } public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { return "Hello world"; }},new ClipboardOwner() { public void lostOwnership(Clipboard clipboard, Transferable contents) { System.out.println("Lost ownership"); }}); System.out.println(getClipboard().getContents(null).getTransferData(DataFlavor.stringFlavor)); } }
import React, { FC } from 'react'; import { Box, Divider, Grid, Typography } from '@mui/material'; import { useTranslation } from 'react-i18next'; import KeyboardBackspaceIcon from '@mui/icons-material/KeyboardBackspace'; import { useNavigate } from 'react-router'; import { AuthPageImgGridItem } from '../../../../shared/styles/AuthPageImgGridItem'; import { WelcomeHubmeeSocialNetworkBox } from '../WelcomeToHubmee/WelcomeToHubmee.style'; import HubmeeLogoContainer from '../HubmeeLogoContainer'; import theme from '../../../../theme/theme'; import AuthBtn from '../../../../components/buttons/AuthBtn'; import SocialNetworkContainer from '../SocialNetworkContainer'; import MuiButton from '../../../../components/buttons/MuiButton'; import { Container, ContantBox, BottomBoxContainer } from '../Auth.style'; type Props = { title: string; description: string; handleSubmit: any; onSubmit: any; img: any; isShowConfirmLoader: boolean; children: React.ReactNode; goBackPath: string; }; const AuthContainer: FC<Props> = ({ title, description, handleSubmit, onSubmit, img, children, isShowConfirmLoader, goBackPath, }) => { const { t } = useTranslation(); const navigate = useNavigate(); return ( <Grid container> <AuthPageImgGridItem xl={6} item> <img loading="lazy" src={img} alt="mainAuth" /> </AuthPageImgGridItem> <Container> <HubmeeLogoContainer /> <ContantBox> <form style={{ width: '100%' }} noValidate onSubmit={handleSubmit(onSubmit)}> <Typography sx={{ color: theme.palette.case.neutral.n900, textAlign: 'center' }} variant="h1"> {title} </Typography> <Box sx={{ mt: '24px' }}> {children} <Typography sx={{ color: theme.palette.case.neutral.n700 }} variant="default"> {description} </Typography> <Box sx={{ width: '200px', margin: '24px auto 0 auto' }}> <AuthBtn type="submit" label={t('auth.links.continue')} loading={isShowConfirmLoader} isStopPropagation={false} /> </Box> <WelcomeHubmeeSocialNetworkBox> <Divider sx={{ width: '100%', mt: '24px', color: theme.palette.case.neutral.n200, }} > <Typography sx={{ color: theme.palette.case.neutral.n500, }} variant="badge" > {t('auth.text.or')} </Typography> </Divider> <SocialNetworkContainer /> </WelcomeHubmeeSocialNetworkBox> </Box> </form> <Box sx={{ mt: '24px', textAlign: 'center' }}> <MuiButton size="large" variant="text" label={t('general.buttons.back')} onClick={() => { navigate(goBackPath); }} startIcon={<KeyboardBackspaceIcon />} /> </Box> </ContantBox> <BottomBoxContainer /> </Container> </Grid> ); }; export default AuthContainer;
package com.jpa.hibernate.controller; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import com.jpa.hibernate.dao.MotoristaDAO; import com.jpa.hibernate.model.Motorista; import com.jpa.hibernate.service.NegocioException; import com.jpa.hibernate.util.jsf.FacesUtil; @Named @ViewScoped public class PesquisaMotoristaBean implements Serializable { private static final long serialVersionUID = 1L; @Inject private MotoristaDAO motoristaDAO; private List<Motorista> motoristas = new ArrayList<>(); private Motorista motoristaSelecionado; @PostConstruct public void inicializar(){ motoristas = motoristaDAO.buscarTodos(); } public void excluir(){ try { motoristaDAO.excluir(motoristaSelecionado); this.motoristas.remove(motoristaSelecionado); FacesUtil.addSuccessMessage("Motorista: " + motoristaSelecionado.getNome() + " excluído com sucesso!"); } catch (NegocioException e) { FacesUtil.addErrorMessage(e.getMessage()); } } public Motorista getMotoristaSelecionado() { return motoristaSelecionado; } public void setMotoristaSelecionado(Motorista motoristaSelecionado) { this.motoristaSelecionado = motoristaSelecionado; } public List<Motorista> getMotoristas() { return motoristas; } public void setMotoristas(List<Motorista> motoristas) { this.motoristas = motoristas; } }
import { View, Text, TextInput } from 'react-native'; import React from 'react'; import { TextInputProps } from 'react-native'; interface Props extends TextInputProps { title: string; value: string; handleChangeText: (text: string) => void; otherStyles?: string; } const FormField = ({ title, value, handleChangeText, otherStyles, ...rest }: Props) => { return ( <View className='my-2'> <Text className='text-sm text-gray-400 ml-4'>{title}</Text> <TextInput {...rest} className={`min-h-12 mt-1 h-[40px] border border-gray-200 px-[10px] focus:border-secondary rounded-[18px] bg-gray-200 ${otherStyles}`} value={value} onChangeText={handleChangeText} /> </View> ); }; export default FormField;
import { Box, Button, Center, Menu, MenuButton, MenuDivider, MenuList, useColorModeValue, } from "@chakra-ui/react"; import React from "react"; import MyAvatar from "./MyAvatar"; import AppHeader from "../AppHeader"; import MyUsername from "./MyUser"; function MyMenu() { const backgroundColor = useColorModeValue("gray.900", "gray.100"); const textColor = useColorModeValue("white", "black"); return ( <Box bg={backgroundColor}> <Menu> <MenuButton as={Button} rounded={"full"} variant={"link"} cursor={"pointer"} minW={0} > <MyAvatar size="sm" /> </MenuButton> <MenuList alignItems={"center"} bg={backgroundColor} color={textColor}> <br /> <Center> <MyAvatar size="2xl" /> </Center> <br /> <Center> <MyUsername /> </Center> <br /> <MenuDivider /> <Center> <AppHeader /> </Center> </MenuList> </Menu> </Box> ); } export default MyMenu;
import SpeedDial from "@mui/material/SpeedDial"; import SpeedDialAction from "@mui/material/SpeedDialAction"; import SpeedDialIcon from "@mui/material/SpeedDialIcon"; import InviteCodeModal from "@components/InviteCodeModal"; import CreateTagModal from "@components/CreateTagModal"; import CreateTodoModal from "@components/CreateTodoModal"; import AddTaskIcon from "@mui/icons-material/AddTask"; import BookmarkAddIcon from "@mui/icons-material/BookmarkAdd"; import PersonAddIcon from "@mui/icons-material/PersonAdd"; import { useParams } from "react-router-dom"; import { useBoolean } from "react-use"; const TodoListSpeedDial: React.FC = () => { const { projectId } = useParams(); const [inviteModal, toggleInviteModal] = useBoolean(false); const [createTagModal, toggleCreateTagModal] = useBoolean(false); const [createTodoModal, toggleCreateTodoModal] = useBoolean(false); if (!projectId) return <></>; return ( <> <SpeedDial sx={{ position: "fixed", right: [30, "7vw", "9vw", "15vw"], bottom: 40, }} ariaLabel="" direction="up" icon={<SpeedDialIcon />} > <SpeedDialAction icon={<AddTaskIcon />} tooltipTitle={"Create Todo"} tooltipOpen onClick={() => toggleCreateTodoModal(true)} sx={{ whiteSpace: "nowrap", }} /> <SpeedDialAction icon={<BookmarkAddIcon />} tooltipTitle={"Create Tag"} tooltipOpen onClick={() => toggleCreateTagModal(true)} sx={{ whiteSpace: "nowrap", }} /> <SpeedDialAction icon={<PersonAddIcon />} tooltipTitle={"Invite People"} tooltipOpen onClick={() => toggleInviteModal(true)} sx={{ whiteSpace: "nowrap", }} /> </SpeedDial> <InviteCodeModal open={inviteModal} onClose={() => toggleInviteModal(false)} /> <CreateTagModal open={createTagModal} onClose={() => toggleCreateTagModal(false)} /> <CreateTodoModal open={createTodoModal} onClose={() => toggleCreateTodoModal(false)} /> </> ); }; export default TodoListSpeedDial;
import { TestBed, getTestBed } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { WardService } from 'app/entities/ward/ward.service'; import { IWard, Ward } from 'app/shared/model/ward.model'; import { WardClassType } from 'app/shared/model/enumerations/ward-class-type.model'; import { WardLocation } from 'app/shared/model/enumerations/ward-location.model'; describe('Service Tests', () => { describe('Ward Service', () => { let injector: TestBed; let service: WardService; let httpMock: HttpTestingController; let elemDefault: IWard; let expectedResult: IWard | IWard[] | boolean | null; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule] }); expectedResult = null; injector = getTestBed(); service = injector.get(WardService); httpMock = injector.get(HttpTestingController); elemDefault = new Ward(0, 'AAAAAAA', 'AAAAAAA', WardClassType.A, WardLocation.A1); }); describe('Service methods', () => { it('should find an element', () => { const returnedFromService = Object.assign({}, elemDefault); service.find(123).subscribe(resp => (expectedResult = resp.body)); const req = httpMock.expectOne({ method: 'GET' }); req.flush(returnedFromService); expect(expectedResult).toMatchObject(elemDefault); }); it('should create a Ward', () => { const returnedFromService = Object.assign( { id: 0 }, elemDefault ); const expected = Object.assign({}, returnedFromService); service.create(new Ward()).subscribe(resp => (expectedResult = resp.body)); const req = httpMock.expectOne({ method: 'POST' }); req.flush(returnedFromService); expect(expectedResult).toMatchObject(expected); }); it('should update a Ward', () => { const returnedFromService = Object.assign( { wardReferenceId: 'BBBBBB', wardName: 'BBBBBB', wardClassType: 'BBBBBB', wardLocation: 'BBBBBB' }, elemDefault ); const expected = Object.assign({}, returnedFromService); service.update(expected).subscribe(resp => (expectedResult = resp.body)); const req = httpMock.expectOne({ method: 'PUT' }); req.flush(returnedFromService); expect(expectedResult).toMatchObject(expected); }); it('should return a list of Ward', () => { const returnedFromService = Object.assign( { wardReferenceId: 'BBBBBB', wardName: 'BBBBBB', wardClassType: 'BBBBBB', wardLocation: 'BBBBBB' }, elemDefault ); const expected = Object.assign({}, returnedFromService); service.query().subscribe(resp => (expectedResult = resp.body)); const req = httpMock.expectOne({ method: 'GET' }); req.flush([returnedFromService]); httpMock.verify(); expect(expectedResult).toContainEqual(expected); }); it('should delete a Ward', () => { service.delete(123).subscribe(resp => (expectedResult = resp.ok)); const req = httpMock.expectOne({ method: 'DELETE' }); req.flush({ status: 200 }); expect(expectedResult); }); }); afterEach(() => { httpMock.verify(); }); }); });
import { useState } from "react"; function ChildComponent({ parentData, sendDataFromChildToParent, onMessageChange }) { const [count, setCount] = useState(0) // state const handleInputChange = (e) => { const newMessage = e.target.value; onMessageChange(newMessage); // Communicate with the parent }; console.log({parentData}) return ( <div> <h2>Child Component</h2> <p>{count}</p> <button onClick={() => setCount(count+1)}>Add</button> <button onClick={() => setCount(count-1)}>Subtract</button> <button onClick={() => sendDataFromChildToParent(count)}>Send To Parent</button> <input type="text" value={parentData} onChange={handleInputChange} placeholder="Type a message..." /> </div> ); } export default ChildComponent
import { useCallback, useEffect } from 'react'; import { Text, TouchableOpacity, View } from 'react-native' import { styles } from '../theme/appTheme' interface Props { texto:string, color?:string, ancho?: boolean, accion: (numeroTexto: string) => void, } export const BotonCalc = ({texto, color = '#2D2D2D', ancho = false, accion }: Props) => { return ( <TouchableOpacity onPress={ () => accion(texto) } > <View style={{ ...styles.boton, backgroundColor:color, width: (ancho) ? 170 : 80 }}> <Text style={{...styles.botonTexto, color: (color === '#9B9B9B') ? 'black': 'white'}}>{texto}</Text> </View> </TouchableOpacity> ) }
/* * Copyright (C) 2021-2023 Intel Corporation * SPDX-License-Identifier: MIT */ import { forwardRef, ReactNode, useImperativeHandle, useRef, useState } from 'react'; import { Box, Card, CardActions, CardContent, Divider } from '@mui/material'; import LargeCardHeader from '../LargeCardHeader'; import { Formik, FormikProps } from 'formik'; import FullWidthAutoComplete from '../FullWidthAutoComplete'; import { DEVICE_AOTA_APP_OPTIONS, DEVICE_AOTA_COMMAND_OPTIONS, DEVICE_AOTA_FIELDS_HIDDEN_STATES, DEVICE_AOTA_INITIAL_FIELDS_HIDDEN_STATE, DEVICE_AOTA_REBOOT_OPTIONS } from '../../data/deviceAota/options'; import FullWidthTextField from '../FullWidthTextField'; import { DeviceAotaAppOptionValue, DeviceAotaCommandOptionValue, DeviceAotaFormFormikValues, DeviceAotaPayload } from '../../types/deviceAota'; import { BaseOption } from '../../types/option'; import deviceAotaValidationSchema from '../../validationSchemas/deviceAota/deviceAotaValidationSchema'; import CardActionsLoadingButton from '../CardActionsLoadingButton'; import { sanitizeFormValues } from '../../utils/utils'; import isFunction from 'lodash/isFunction'; import { FormFormikActions } from '../../types/formik'; interface DeviceAotaFormCardProps { submitButtonChildren?: ReactNode; onSubmit: (data: DeviceAotaPayload, formFormikActions: FormFormikActions<DeviceAotaFormFormikValues>) => void; } const DeviceAotaFormCard = forwardRef(({ submitButtonChildren, onSubmit }: DeviceAotaFormCardProps, ref) => { const formRef = useRef<FormikProps<DeviceAotaFormFormikValues>>(null); useImperativeHandle(ref, () => formRef.current); const [fieldsHidden, setFieldsHidden] = useState(DEVICE_AOTA_INITIAL_FIELDS_HIDDEN_STATE); const resetForm = () => { setFieldsHidden(DEVICE_AOTA_INITIAL_FIELDS_HIDDEN_STATE); if (formRef.current) { formRef.current.resetForm(); } }; const updateFormFields = (name: string, selectedOption: BaseOption) => { if (name === 'app' && selectedOption) { // We reset the form so that all form fields will be cleared and set the 'app' input field to the selected option // after the reset so that the value is not lost. resetForm(); formRef?.current?.setFieldValue('app', selectedOption); setFieldsHidden({ ...DEVICE_AOTA_INITIAL_FIELDS_HIDDEN_STATE, cmd: false }); } else if (name === 'app' && !selectedOption) { resetForm(); } else if (name === 'cmd' && selectedOption) { // @ts-ignore setFieldsHidden(DEVICE_AOTA_FIELDS_HIDDEN_STATES[formRef.current.values.app.value as DeviceAotaAppOptionValue][selectedOption.value as DeviceAotaCommandOptionValue]); } }; const validationSchema = deviceAotaValidationSchema(DEVICE_AOTA_COMMAND_OPTIONS[formRef.current?.values.app?.value as DeviceAotaAppOptionValue ?? 'docker'], fieldsHidden); return ( <Card> <LargeCardHeader title="Application OTA update" subheader="Trigger application OTA update for device" /> <Divider/> <Formik innerRef={formRef} enableReinitialize={true} initialValues={{ app: null, cmd: null, containerTag: '', deviceReboot: null, fetch: '', signature: '', version: '', username: '', password: '', dockerRegistry: '', dockerUsername: '', dockerPassword: '', file: '', }} validationSchema={validationSchema} onSubmit={(values, { setSubmitting }) => { if (isFunction(onSubmit)) { onSubmit(sanitizeFormValues(values), { setSubmitting }); } }} > {({ handleSubmit, isSubmitting }: FormikProps<DeviceAotaFormFormikValues>) => ( <> <CardContent> <Box component="form" sx={{ p: 1 }} noValidate autoComplete="off" > <FullWidthAutoComplete required id="app" name="app" label="Application" placeholder="Choose your application" options={DEVICE_AOTA_APP_OPTIONS} optionChangeCallback={updateFormFields} hidden={fieldsHidden.app} /> <FullWidthAutoComplete required id="cmd" name="cmd" label="Command" placeholder="Enter your command" options={DEVICE_AOTA_COMMAND_OPTIONS[formRef.current?.values.app?.value as DeviceAotaAppOptionValue ?? 'docker']} optionChangeCallback={updateFormFields} hidden={fieldsHidden.cmd} /> <FullWidthTextField required id="containerTag" name="containerTag" label="Container tag" placeholder="Enter container tag" hidden={fieldsHidden.containerTag} /> <FullWidthAutoComplete required id="deviceReboot" name="deviceReboot" label="Device reboot" placeholder="Choose device reboot" options={DEVICE_AOTA_REBOOT_OPTIONS} hidden={fieldsHidden.deviceReboot} /> <FullWidthTextField required id="fetch" name="fetch" label="Fetch link" placeholder="Enter fetch link" hidden={fieldsHidden.fetch} /> <FullWidthTextField required id="signature" name="signature" label="Signature" placeholder="Enter signature" hidden={fieldsHidden.signature} /> <FullWidthTextField {...((formRef.current?.values.app?.value === 'docker' && formRef.current?.values.cmd?.value === 'remove') && { required: true }) } id="version" name="version" label="Version" placeholder="Enter version" hidden={fieldsHidden.version} /> <FullWidthTextField id="username" name="username" label="Server username" placeholder="Enter server username" hidden={fieldsHidden.username} /> <FullWidthTextField id="password" name="password" label="Server password" placeholder="Enter server password" hidden={fieldsHidden.password} /> <FullWidthTextField id="dockerRegistry" name="dockerRegistry" label="Docker registry" placeholder="Enter Docker registry" hidden={fieldsHidden.dockerRegistry} /> <FullWidthTextField id="dockerUsername" name="dockerUsername" label="Docker username" placeholder="Enter Docker username" hidden={fieldsHidden.dockerUsername} /> <FullWidthTextField id="dockerPassword" name="dockerPassword" label="Docker password" placeholder="Enter Docker password" hidden={fieldsHidden.dockerPassword} /> <FullWidthTextField id="file" name="file" label="Docker compose file" placeholder="Enter Docker Compose file" hidden={fieldsHidden.file} /> </Box> </CardContent> <Divider/> <CardActions> <CardActionsLoadingButton loading={isSubmitting} onClick={() => handleSubmit()} > {submitButtonChildren ?? 'Submit'} </CardActionsLoadingButton> </CardActions> </> )} </Formik> </Card> ); }); export default DeviceAotaFormCard;
let scoreBlock, // отбражнение очков score = 0; // сами очки const config = { // настройки игры step: 0, // пропускать игровой цикл maxStep: 6, // пропускать игровой цикл sizeCell: 16, // размер одной ячейки sizeBerry: 16 / 4 // размер ягоды } const snake = { // настройки змейки x: 160, // координаты y: 160, // координаты dx: config.sizeCell, // скорость по вертикали dy: 0, // скорость по горизонтали tails: [], // массив ячеек под контролем змейки maxTails: 3 // кол-во ячеек } //координаты ягоды let berry = { x: 0, y: 0 } // Получаем canvas let canvas = document.querySelector('#game-canvas'), context = canvas.getContext('2d'); scoreBlock = document.querySelector('.game-score .score-count'); drawScore(); // __________________________________________________________________________________ // Игрововой цикл function gameLoop() { requestAnimationFrame( gameLoop ); // вызываем requestAnimationFrame > передаем игровой цикл > gameLoop будет вызываться бесконечно if ( ++config.step < config.maxStep) { // проверка > если положительная > пропускаем дальнейшую фунц. // за счет этого мы можем контролировать скорость отрисовки на экране return; } config.step = 0; context.clearRect(0, 0, canvas.width, canvas.height); // каждый кадр необходимо очищать canvas // заново отрисовать все элементы drawBerry(); drawSnake(); } requestAnimationFrame( gameLoop ); // Отображаем змейку на экране function drawSnake() { // меняем координаты змейки согласно скорости snake.x += snake.dx; snake.y += snake.dy; collisionBorder(); // todo бордер // добавляет в начало объект с X и Y координатами snake.tails.unshift( { x: snake.x, y: snake.y } ); // условие: если кол-во доч. элем. у змейки больше чем разрешено > удаляем последний элемент if ( snake.tails.length > snake.maxTails ) { snake.tails.pop(); } // перебираем все дочерние элементы у змейки + отрисовываем их\проверяем на соприкосновение с друг другом и ягодой snake.tails.forEach( function(el, index) { if (index == 0) { context.fillStyle = "#FA0556"; } else { context.fillStyle = "#A00034"; } context.fillRect( el.x, el.y, config.sizeCell, config.sizeCell ); // проверям координаты ягоды и змейки // если совпадают > увел. хвост у змейки if ( el.x === berry.x && el.y === berry.y) { snake.maxTails++; incScore(); randomPositionBerry(); } // проверяем соприкосновение змейки с хвостом // если совпадают > запускаем игру заново for (let i = index + 1; i < snake.tails.length; i++) { if ( el.x == snake.tails[i].x && el.y == snake.tails[i].y ) { refreshGame(); } } }); } // Границы canvas function collisionBorder() { if (snake.x < 0) { snake.x = canvas.width - config.sizeCell; } else if ( snake.x >= canvas.width) { snake.x = 0; } if (snake.y < 0) { snake.y = canvas.height - config.sizeCell; } else if ( snake.y >= canvas.height) { snake.y = 0; } } // Функция переапуска игры function refreshGame() { score = 0; drawScore(); snake.x = 160; snake.y = 160; snake.tails =[]; snake.maxTails = 3; snake.dx = config.sizeCell; snake.dy = 0; randomPositionBerry(); } // Пустая функция drawBerry function drawBerry() { context.beginPath(); context.fillStyle = "#A00034"; context.arc ( berry.x + (config.sizeCell / 2), berry.y + (config.sizeCell / 2), config.sizeBerry, 0, 2 * Math.PI ); context.fill(); } // Функция рандомных значений у ягоды function randomPositionBerry() { berry.x = getRandomInt( 0, canvas.width / config.sizeCell ) * config.sizeCell; berry.y = getRandomInt( 0, canvas.height / config.sizeCell ) * config.sizeCell; } // __________________________________________________________________________________ // Функция обработки очков function incScore() { // увеличивает кол-во очков на ед. score++; drawScore(); } // Функция отображения увел-ия очков function drawScore() { // отображает увел. очков от incScore scoreBlock.innerHTML = score; } function getRandomInt(min, max) { return Math.floor( Math.random() * (max - min) + min ); // принимает диапозон чисел и возвращает рандомное значение в заданном диапозоне } // Назначаем кнопки на клавиатуре document.addEventListener("keydown", function(e) { if ( e.code == "KeyW" ) { snake.dy = -config.sizeCell; snake.dx = 0; } else if ( e.code == "KeyA" ) { snake.dx = -config.sizeCell; snake.dy = 0; } else if ( e.code == "KeyS" ) { snake.dy = config.sizeCell; snake.dx = 0; } else if ( e.code == "KeyD" ) { snake.dx = config.sizeCell; snake.dy = 0; } });
<form class="row" #userNameForm="ngForm" (submit)="onSubmit()" *ngIf="app.isLocalAccountEnabled"> <div class="col"> <div class="row"> <div class="col"> <md-input-container class="w-100" *ngIf="app.emailSettings.isEnabled && app.phoneSettings.isEnabled"> <input autofocus mdInput placeholder="Email or Phone" type="text" name="userName" maxlength="254" required emailOrPhone (input)="validateUserName(userNameForm.form.valid)" [(ngModel)]="im.userName" (input)="searchProvider()" #userName="ngModel"> <md-hint align="end">{{userName.value?.length || 0}} / 254</md-hint> <md-hint *ngIf="userName.errors && (userName.dirty || userName.touched)" style="color: red;"> <span [hidden]="!userName.errors.required"> Email or Phone is required. </span> <span [hidden]="!userName.errors.emailOrPhone || userName.errors.required"> Email or Phone is not valid. </span> </md-hint> <md-hint *ngIf="userNameForm.form.valid && userNameMessage" style="color: red;"><span>{{userNameMessage}}</span></md-hint> <md-spinner mdPostfix class="au-input-spinner" *ngIf="inProgress"></md-spinner> </md-input-container> <md-input-container class="w-100" *ngIf="app.emailSettings.isEnabled && !app.phoneSettings.isEnabled"> <input autofocus mdInput placeholder="Email" type="text" name="userName" maxlength="254" required email [(ngModel)]="im.userName" (input)="validateUserName(userNameForm.form.valid)" (input)="searchProvider()" #userName="ngModel"> <md-hint align="end">{{userName.value?.length || 0}} / 254</md-hint> <md-hint *ngIf="userName.errors && (userName.dirty || userName.touched)" style="color: red;"> <span [hidden]="!userName.errors.required"> Email is required. </span> <span [hidden]="!userName.errors.email || userName.errors.required"> Email is not valid. </span> </md-hint> <md-hint *ngIf="userNameForm.form.valid && userNameMessage" style="color: red;"><span>{{userNameMessage}}</span></md-hint> <md-spinner mdPostfix class="au-input-spinner" *ngIf="inProgress"></md-spinner> </md-input-container> <md-input-container class="w-100" *ngIf="!app.emailSettings.isEnabled && app.phoneSettings.isEnabled"> <input autofocus mdInput placeholder="Phone" type="text" name="userName" maxlength="50" required phone [(ngModel)]="im.userName" (input)="validateUserName(userNameForm.form.valid)" #userName="ngModel"> <md-hint align="end">{{userName.value?.length || 0}} / 50</md-hint> <md-hint *ngIf="userName.errors && (userName.dirty || userName.touched)" style="color: red;"> <span [hidden]="!userName.errors.required"> Phone is required. </span> <span [hidden]="!userName.errors.phone || userName.errors.required"> Phone is not valid. </span> </md-hint> <md-hint *ngIf="userNameForm.form.valid && userNameMessage" style="color: red;"><span>{{userNameMessage}}</span></md-hint> <md-spinner mdPostfix class="au-input-spinner" *ngIf="inProgress"></md-spinner> </md-input-container> </div> </div> <div class="row mt-1"> <div class="col"> <button class="w-100" [disabled]="!userNameForm.form.valid || userNameMessage !== '' || inProgress" md-raised-button color="primary">next</button> </div> </div> <div class="row mt-1" *ngIf="searchResult"> <div class="col"> <au-social-network-button [namePrefix]="'want to use'" [namePostfix]="'account?'" (click)="externalLogIn(searchResult)" [provider]="searchResult"> </au-social-network-button> </div> </div> </div> </form>
import React, { useState, useRef, useEffect } from 'react' import axios from "axios" import { useSelector, useDispatch } from 'react-redux'; import UMCReducer from '../../../redux/umcReducer'; import LoadingScreen from '../../LoadingScreen'; function DeleteChapter() { const [sectionLoading, setSectionLoading] = useState(false) const [formValue, setFormValue] = useState({ course: "", part: "", chapter: "", }) const UMCData = useSelector((state) => state) // Redux Dispatch const dispatch = useDispatch(UMCReducer); const grabAllCourse = () => { axios.get(`${process.env.REACT_APP_API_DOMAIN}/course/view`) .then(response => { dispatch({ type: "populate_all_courses", payload: response.data.result }) }) .catch(error => { // console.log(error) }) } const handleSubmit = (e) => { e.preventDefault() var deleteConfirm = prompt(`Please Type 'DELETE' in the field below.`, ""); if (formValue.course && formValue.part && formValue.chapter && deleteConfirm != null && deleteConfirm == "DELETE") { setSectionLoading(true) axios.delete(`${process.env.REACT_APP_API_DOMAIN}/chapter/delete/${formValue.chapter}`, { headers: { Authorization: "Bearer " + localStorage.getItem("token") } }) .then(function (response) { grabAllCourse() setSectionLoading(false) alert(response.data.msg) }) .catch(function (error) { setSectionLoading(false) // console.log(error); }); } else { alert("Fill Up All The Field Correctly. Double Check Before Submit, please.") } } return ( sectionLoading ? <LoadingScreen /> : ( <form className="px-4 py-8 lg:px-0" method="post" onSubmit={handleSubmit}> <h3 className="text-gray-700 text-xl font-medium text-center mb-4">Delete Chapter</h3> <div className="flex flex-wrap -mx-3 mb-6"> <div className="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" htmlFor="grid-state"> Course Name </label> <div className="relative"> <select className="block appearance-none w-full bg-gray-200 border border-gray-700 text-black py-3 px-4 pr-8 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500" id="grid-state" name="course" onChange={(e) => setFormValue({ ...formValue, course: e.target.value })} value={formValue.course} required> <option key={Math.random()} value="">Select A Course</option> { UMCData.allCourse.map(course => ( <option key={Math.random()} value={course._id}>{course.title}</option> )) } </select> <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700"> <svg className="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" /></svg> </div> </div> </div> <div className="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" htmlFor="grid-state"> Part </label> <div className="relative"> <select className="block appearance-none w-full bg-gray-200 border border-gray-700 text-black py-3 px-4 pr-8 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500" id="grid-state" name="part" onChange={(e) => setFormValue({ ...formValue, part: e.target.value })} value={formValue.part} required > <option key={Math.random()} value="">Select A Part</option> { formValue.course && UMCData.allCourse.find(course => course._id == formValue.course).parts.map(part => ( <option key={Math.random()} value={part._id}>{part.title}</option> )) } </select> <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700"> <svg className="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" /></svg> </div> </div> </div> </div> <div className="flex flex-wrap -mx-3 mb-6"> <div className="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" htmlFor="grid-state"> Chapter Name </label> <div className="relative"> <select className="block appearance-none w-full bg-gray-200 border border-gray-700 text-black py-3 px-4 pr-8 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500" id="grid-state" name="chapter" onChange={(e) => setFormValue({ ...formValue, chapter: e.target.value })} value={formValue.chapter} required > <option key={Math.random()} value="">Select A Chapter</option> { formValue.part && UMCData.allCourse.find(course => course._id == formValue.course).parts.find(part => (part._id == formValue.part)).chapters.map(chapter => ( <option key={Math.random()} value={chapter._id}>{chapter.title}</option> )) } </select> <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700"> <svg className="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" /></svg> </div> </div> </div> </div> <div className="flex flex-wrap -mx-3 my-2 mt-8"> <div className="w-full md:w-full px-3 mb-6 md:mb-0"> <input className="flex cursor-pointer items-center justify-center h-12 px-6 w-full bg-blue-600 rounded font-semibold text-sm text-blue-100 hover:bg-blue-700" id="grid-first-name" type="submit" value="Delete Chapter" /> </div> </div> </form> ) ) } export default DeleteChapter
/* eslint-disable @next/next/no-img-element */ import { ImageResponse } from "next/og"; import { ProductGetItemByIdDocument } from "@/gql/graphql"; import { executeGraphql } from "@/app/api/graphqlApi"; import { formatPrice } from "@/app/components/utils"; export const runtime = "edge"; export const alt = "Best shop ever!"; export const size = { width: 1200, height: 630, }; export const metadata = { metadataBase: new URL("http://localhost:3000"), title: "Title webtsite", description: "this is the desciption", openGraph: { title: "Title webtsite", description: "this is the desciption", image: "url/image.png", }, twitter: { card: "summary_large_image", site: "...", title: "Title webtsite", description: "this is the desciption", image: "url/image.png", }, }; export const contentType = "image/png"; export default async function og({ params }: { params: { id: string } }) { const { product } = await executeGraphql({ query: ProductGetItemByIdDocument, variables: { productId: params.id }, }); if (!product) { return ( <div tw="w-full text-white h-full flex flex-col items-center justify-center text-8xl" style={{ background: ` linear-gradient( 90deg, rgb(6,172,214) 0%, rgb(0,0,0) 20%, rgb(0,0,0) 80%, rgb(6,71,255) 100% )`, }} > <p tw="font-sans uppercase m-0 p-0 text-[101px] leading-4">Fancy image</p> <p tw="font-serif m-0 p-0 font-black">no such product</p> <p tw="m-0 mt-2">Sorry</p> </div> ); } return new ImageResponse( ( <div tw="w-full text-white h-full flex flex-col items-center justify-center text-8xl" style={{ background: ` linear-gradient( 90deg, rgb(6,172,214) 0%, rgb(0,0,0) 20%, rgb(0,0,0) 80%, rgb(6,71,255) 100% )`, }} > {" "} <div tw="h-1/3 w-1/3 flex justify-center items-center"> <img tw="w-full h-full" style={{ objectFit: "contain", }} width={product?.images[0]?.width} height={product.images[0]?.height} src={product.images[0]?.url} alt={product.images[0]?.alt} /> </div> <p tw="font-sans uppercase m-0 mt-4 p-0 text-3xl leading-4">{product?.name}</p> <p tw="font-serif m-0 mt-3 p-0 font-black text-2xl italic">{product.description}</p> <p tw="m-0 mt-2 text-2xl text-green-600">{formatPrice(product.price / 100)}</p> </div> ), ); }
import type { VoidFn, Reacty } from './indeps-lookduck' import { _, injectReact, getInjectedReact } from './indeps-lookduck' import type { Lookable, AnyLookableMap, GottenLookableMapValues } from './lookable' import { getEachInLookableMap } from './lookable' import type { EqualityMode } from './observable' import { makeEqualityFn } from './observable' interface HookOpt { debounce: number | null // no. of ms, or null to disable logRerender: string | null // msg to log on rerender, or null to disable equality: EqualityMode } const DEFAULT_HOOK_OPT: HookOpt = { debounce: null, logRerender: null, equality: 'is' } // Internal helper. Returns a func that forces rerender, if (minimally) req'd. const useForceRerenderMinimally = function ( lkArr: Array<Lookable<unknown>>, opt: HookOpt ): VoidFn { const React = getInjectedReact() const valArrRef = React.useRef(_.map(lkArr, lk => lk.get())) const [, setNum] = React.useState(0) const equalityFn = makeEqualityFn(opt.equality) const forceUpdate = function (): void { if (_.stringIs(opt.logRerender)) { console.log(`Rerendering ${opt.logRerender} ...`) } setNum(n => (n + 1) % 2e9) // 2e9 is some big number (32 bit signed) } const forceUpdateIfChanged = function (): void { const newValArr = _.map(lkArr, lk => lk.get()) // Check equlityFn pairwise, to properly support custom equality functions if (!_.all(valArrRef.current, (val, i) => equalityFn(val, newValArr[i]))) { valArrRef.current = newValArr forceUpdate() } } if (opt.debounce === null) { return forceUpdateIfChanged } return _.debounce(forceUpdateIfChanged, opt.debounce) } // Internal helper. Creates and manages a subscription for force-rerendering. const useSubscription = function ( lkArr: Array<Lookable<unknown>>, forceRerender: VoidFn ): void { const React = getInjectedReact() const phase = React.useRef<'premount' | 'mounted' | 'unmounted'>('premount') const didChangePremount = React.useRef(false) const didSubscribe = React.useRef(false) const phasewiseListenerMap = { premount: () => { didChangePremount.current = true }, mounted: forceRerender, unmounted: () => _.defer(unsubAll) // async-unsub, as we're amid pub-loop } const rootListener = (): void => phasewiseListenerMap[phase.current]() const subAll = (): void => lkArr.forEach(o => o.subscribe(rootListener)) const unsubAll = (): void => lkArr.forEach(o => o.unsubscribe(rootListener)) React.useEffect(function () { phase.current = 'mounted' if (didChangePremount.current) { forceRerender() } return function () { phase.current = 'unmounted' unsubAll() } }, []) if (!didSubscribe.current) { didSubscribe.current = true subAll() // sync-sub, as we aren't amid pub-loop } } // Note: useRef vs useCallback regarding `didSubscribe` // --- --- --- --- --- --- --- --- --- --- --- --- --- // The `didSubscribe` ref ensures that we subscribe at most once. // (It is only relevant in the premount/mounted phases, not when unmounted.) // Alternatively, useCallback-wrapped listener would work too, as subscribeAll() // internally calls pubsubable.subscribe, which uses a Set for subscribers. // Howerever, useCallback(fn, deps) is equivalnt to useMemo(() => fn, deps), // and useMemo may only be used for optimizations, not as a semantic guarantee. // We need a semantic guarantee that we subscribe at most once, so useCallback // alone isn't sufficient. Since we'll need useRef anyway, and since the // callbacks aren't being passed as props, useCallback is unnecessary. const useLookableArray = function <T extends Array<Lookable<unknown>>>( lkArr: T, opts?: Partial<HookOpt> ): void { const opt: HookOpt = { ...DEFAULT_HOOK_OPT, ...opts } const forceRerender = useForceRerenderMinimally(lkArr, opt) useSubscription(lkArr, forceRerender) } const useLookableMap = function <LMap extends AnyLookableMap>( lkMap: LMap, opt?: Partial<HookOpt> ): GottenLookableMapValues<LMap> { useLookableArray(_.values(lkMap), opt) return getEachInLookableMap(lkMap) } const usePickLookables = function < LMap extends AnyLookableMap, K extends keyof LMap >( lkMap: LMap, keys: K[], opt?: Partial<HookOpt> ): GottenLookableMapValues<Pick<LMap, K>> { return useLookableMap(_.pick(lkMap, keys), opt) } type AnyLookables = | Array<Lookable<any>> | AnyLookableMap type UseLookablesOutput<T extends AnyLookables> = T extends Array<Lookable<any>> ? undefined : T extends AnyLookableMap ? GottenLookableMapValues<T> : never const useLookables = function <T extends AnyLookables>( lookables: T, opt?: Partial<HookOpt> ): UseLookablesOutput<T> { if (_.arrayIs(lookables)) { useLookableArray(lookables, opt) return undefined as UseLookablesOutput<T> } else if (_.plainObjectIs(lookables)) { return useLookableMap(lookables, opt) as UseLookablesOutput<T> } else { return _.never(lookables) } } const useLookable = function <T>( lk: Lookable<T>, opt?: Partial<HookOpt> ): T { return useLookableMap({ lk }, opt).lk } // TODO: Consider deprecating in favor of injectReact() and useLookable() const makeUseLookable = function (React: Reacty): (typeof useLookable) { injectReact(React) return useLookable } export type { HookOpt } export { useLookables, usePickLookables, useLookable, makeUseLookable }
package com.app.fruits.tester; import com.app.fruits.*; import java.util.Scanner; public class FruitBasket { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the Size of Basket: "); Fruits[] fruitBasket = new Fruits[sc.nextInt()]; boolean exit = false; int counter = 0; while(!exit) { System.out.println("Options : 1. Add Mango \n" + "2. Add Orange \n" + "3. Add Apple\n" + "4. Display names of all fruits in the basket\n" + "5. Display name,color,weight , taste of all fresh fruits , in the basket\n" + "6. Mark a fruit in a basket , as stale \n" + "7. Mark all sour fruits stale\n" + "8. Invoke fruit specific functionality\n" + "9. Exit"); System.out.println("Choose an option"); switch(sc.nextInt()) { case 1: if(counter < fruitBasket.length) { System.out.println("Enter Mango Details: (color, weight, name)"); fruitBasket[counter] = new Mango(sc.next(), sc.nextDouble(), sc.next()); counter++; System.out.println("Mango Added in basket..."); } else { System.out.println("Basket is Full!"); } break; case 2: if(counter < fruitBasket.length) { System.out.println("Enter Orange Details: (Color, Weight, Name)"); fruitBasket[counter] = new Orange(sc.next(), sc.nextDouble(), sc.next()); counter++; System.out.println("Orange Added in basket..."); } else { System.out.println("Basket is Full!"); } break; case 3: if(counter < fruitBasket.length) { System.out.println("Enter Apple Details: (color, weight, name)"); fruitBasket[counter] = new Apple(sc.next(), sc.nextDouble(), sc.next()); counter++; System.out.println("Apple Added in basket..."); } else { System.out.println("Basket is Full!"); } break; case 4: System.out.println("The Name of All Fruits in Baskets are: "); for(Fruits fruit : fruitBasket) { if(fruit != null) { System.out.println(fruit.getName()); } } break; case 5: System.out.println("The name,color,weight , taste of all fresh fruits: "); for(Fruits fruit : fruitBasket) { if(fruit.isFresh()) { System.out.println(fruit + fruit.taste());} // if(fruit != null) { // System.out.println(fruit); // } } break; case 6: // int ser = 0; System.out.println("Enter the Index of Fruit: "); int idx = sc.nextInt(); // System.out.println("Enter the fruit Name: "); // String fruitName = sc.next(); // if(fruitBasket[idx].getName().equals(fruitName)) { fruitBasket[idx].setFresh(false); System.out.println("Fruit: " + fruitBasket[idx].getName() + " set as stale."); // } // else if(ser > counter){ // System.out.println("Invalid Data..."); // } // else { // System.out.println("Stale."); // } break; case 7: System.out.println("The name,color,weight ,taste of all fresh fruits: "); System.out.println("Enter the Fruit Index: "); for(Fruits fruit : fruitBasket) { if(fruit.taste().equals("Sour")) { fruit.setFresh(false); System.out.println("Fruit is Sour and Stale!"); } else { System.out.println("Fruit is not Stale..."); } } break; case 8: System.out.println("Enter the Serial Number of fruit: "); int index = sc.nextInt()- 1; if (index >= 0 && index < counter) { Fruits fruit = fruitBasket[index]; if(fruit instanceof Mango) ((Mango)fruit).pulp(); else if (fruit instanceof Orange) ((Orange)fruit).juice(); else ((Apple)fruit).jam(); } break; case 9: exit = true; break; } } sc.close(); } }
import openpyxl ######################################################################################## #Cpf existente na planilha para teste de atualização de dados # - 567.890.123-54 # - 456.789.012-43 # - 345.678.901-32 ######################################################################################## class PlanilhaVendedores: def __init__(self, vendedores): self.vendedores = vendedores self.planilha = openpyxl.load_workbook(self.vendedores) self.pagina_vendedor = self.planilha['Vendedores'] def nome_vendedores(self): for linha in self.pagina_vendedor.iter_rows(min_row=2): print(f'Nome: {linha[0].value}, \nCPF: {linha[1].value}, \nData nascimento: {linha[2].value}, \nEstado: {linha[3].value}\n') def alterar_dados(self): cpf = input("Digite o CPF do vendedor que deseja alterar: ") cpf_existe = False for linha in self.pagina_vendedor.iter_rows(min_row=2): if linha[1].value == cpf: cpf_existe = True break if cpf_existe: novo_nome = input("Digite o novo nome: ") nova_data_nascimento = input("Digite a nova data de nascimento: ") novo_estado = input("Digite o novo estado: ") for linha in self.pagina_vendedor.iter_rows(min_row=2): if linha[1].value == cpf: linha[0].value = novo_nome linha[2].value = nova_data_nascimento linha[3].value = novo_estado break self.planilha.save(self.vendedores) print("Dados atualizados com sucesso.") else: print("CPF não encontrado na planilha.") return planilha_vendedores = PlanilhaVendedores('AAWZ_Vendedores.xlsx') planilha_vendedores.alterar_dados() planilha_vendedores.nome_vendedores()
import { parseLambda } from "../../math/lambda/parse.js"; import { richRepr } from "../../math/lambda/repr.js"; import { subs } from "../../math/lambda/subs.js"; import { label } from "../../utils/lang.js"; import { tex } from "../../utils/log.js"; const lb = label({ en : { invalid: 'is not a valid variable', term: 'in term', substitute: 'substitute', for: 'for', }, es : { invalid: 'no es una variable válida', term: 'en el término', substitute: 'sustituye', for: 'por', }, }); const script = { get args() { return [ { name: lb('term'), default: 'λx.xy', }, { name: lb('substitute'), default: 'y', }, { name: lb('for'), default: 'K', }, ]}, suggs: [ { desc: 'x[x := y]', inputs: ['x','x','y'], }, { desc: 'z[x := y]', inputs: ['z','x','y'], }, { desc: '(λx.xy)[y := x]', inputs: ['λx.xy','y','x'], }, ], logic: ([ts,v,bs]) => { if (v.length != 1 || (!v.match(/[a-z]/))) throw new Error(`\`${v}\` ${lb('invalid')}.`) const t = parseLambda(ts); const b = parseLambda(bs); return [ tex((t.isVar() ? richRepr(t) : '(' + richRepr(t) + ')') + '[' + v + '\\, := \\,' + richRepr(b) + '] \\, = \\, ' + richRepr(subs(v,b)(t))).replace(/([IMKSΩY])/g, "\\mathsf{$1}") ]; } }; window.handleScript(script);
# [QA-1] Issue in `mint` Function ## Description The `mint` function in the contract has a comparison operator issue in the `require` statement, where it checks if the total supply plus the minted amount exceeds the maximum supply. ## Error The cause of the issue is the incorrect usage of the comparison operator in the `require` statement. The operator `<` is used instead of `<=`, which results in incorrect validation of the minted amount against the maximum supply. ``` function mint(address to, uint256 amount) public virtual { require(totalSupply() + amount < MAX_SUPPLY, "Trying to mint more than the max supply"); require(hasRole(MINTER_ROLE, msg.sender), "ERC20: must have minter role to mint"); _mint(to, amount); } ``` ## Impact - Actual supply will always be less than the MAX_SUPPLY of the token which can have impact on economic price of the token. ## Correction To address this issue, the comparison operator in the `require` statement should be changed from `<` to `<=` to correctly validate if the total supply plus the minted amount is less than or equal to the maximum supply. # [QA-2]User can never lose stake even if they have very little points ## Instance - This check in RankedBattle::addBalance function make it impossible to lose on their stake if they have very little points which let them perform poorly with some player which will let the opponents to have a high elo and to get high share on Pool. [These opponents can also be their different Id, which will be end up in a win situation for the user] ``` if (points > accumulatedPointsPerFighter[tokenId][roundId]) { points = accumulatedPointsPerFighter[tokenId][roundId]; } ``` # [QA-3] FighterFarm::redeemMintPass in not checking array length on iconsTypes array ## Description The redeemMintPass function in the contract allows users to redeem multiple mint passes in exchange for fighter NFTs. However, there is a potential issue in the function where it doesn't consider the length of the iconsTypes array, leading to a mismatch in the input array lengths. ```diff function redeemMintPass( uint256[] calldata mintpassIdsToBurn, uint8[] calldata fighterTypes, uint8[] calldata iconsTypes, string[] calldata mintPassDnas, string[] calldata modelHashes, string[] calldata modelTypes ) external { require( mintpassIdsToBurn.length == mintPassDnas.length && mintPassDnas.length == fighterTypes.length && fighterTypes.length == modelHashes.length && modelHashes.length == modelTypes.length + && modelTypes.length == iconTypes.length ); for (uint16 i = 0; i < mintpassIdsToBurn.length; i++) { require(msg.sender == _mintpassInstance.ownerOf(mintpassIdsToBurn[i])); _mintpassInstance.burn(mintpassIdsToBurn[i]); _createNewFighter( msg.sender, uint256(keccak256(abi.encode(mintPassDnas[i]))), modelHashes[i], modelTypes[i], fighterTypes[i], iconsTypes[i], [uint256(100), uint256(100)] ); } } ``` ## Recommended Mitigation Steps Include iconsTypes Length Check: Add a length check for the iconsTypes array to ensure consistency with the other input arrays.
import base64 import concurrent import logging import os import tempfile import requests from django.core.files import File from lyrics_extractor import SongLyrics from youtube_search import YoutubeSearch from PaulStudios import settings from base.tasks import increase_progress, update_progress from songdownloader.models import SpotifyPlaylist, SpotifySong from songdownloader.services.downloader import process_image # Replace these with your own Spotify credentials CLIENT_ID = settings.SONGDOWNLOADER_SPOTIFY_CLIENT_ID CLIENT_SECRET = settings.SONGDOWNLOADER_SPOTIFY_CLIENT_SECRET GCS_API_KEY = settings.GCS_API_KEY GCS_ENGINE_ID = settings.GCS_ENGINE_ID logger = logging.getLogger("Services.Spotify") def get_track_details(track): try: track_id = track['id'] track_name = track['name'] artists = ', '.join([artist['name'] for artist in track['artists']]) album_image = track['album']['images'][0]['url'] return track_id, track_name, album_image, artists except Exception as e: logger.warning(e) def parse_songs(track, counter, total_tracks): try: track_id, track_name, album_image, artists = get_track_details(track['track']) logger.info(f"Parsing track: {track_name} ({counter}/{total_tracks})") name = track_name if len(track_name) > 40: name = track_name[:40] song_name = f"{str(counter)}. {name} [{artists.split(', ')[0]}]" track_data = { 'track_id': track_id, "url": search_song(song_name), 'name': song_name, 'track_name': track_name, 'album_image': album_image, 'artists': artists, } return track_data except Exception as e: logger.warning(e) class Spotify: def __init__(self, mode, url): logger.info('Spotify initialized') self.id = self.parse_id(url) self.client_id = CLIENT_ID self.client_secret = CLIENT_SECRET self.access_token = self._get_access_token() self._extract_lyrics = SongLyrics(GCS_API_KEY, GCS_ENGINE_ID) if mode == 'Playlist': self.data = self._SpotifyPlaylist(self.id, self.access_token) elif mode == 'Track': self.data = self._SpotifyTrack(self.id, self.access_token) @staticmethod def parse_id(id): try: return id.split("/")[-1].split("?")[0] except AttributeError as e: return id.split("/")[-1] def _get_access_token(self): auth_url = 'https://accounts.spotify.com/api/token' auth_headers = { 'Authorization': 'Basic ' + base64.b64encode(f"{self.client_id}:{self.client_secret}".encode()).decode() } auth_data = { 'grant_type': 'client_credentials' } response = requests.post(auth_url, headers=auth_headers, data=auth_data) response_data = response.json() return response_data['access_token'] def _get_lyrics(self, track_name): return self._extract_lyrics.get_lyrics(track_name) class _SpotifyTrack: def __init__(self, id: str, token: str): logger.info('Track mode selected') self.track_id = id self.access_token = token def get_track_data(self, playlist_id: str): playlist_url = f"https://api.spotify.com/v1/tracks/{playlist_id}" headers = { 'Authorization': f'Bearer {self.access_token}' } response = requests.get(playlist_url, headers=headers) return response.json() @property def name(self) -> str: return self.get_track_data(self.track_id)['name'] class _SpotifyPlaylist: def __init__(self, id: str, token: str): logger.info('Playlist Mode selected') self.playlist_id = id self.access_token = token self.track_list = [] def get_tracks_list(self): logger.info('Getting list of tracks') playlist_url = f"https://api.spotify.com/v1/playlists/{self.playlist_id}/tracks" headers = { 'Authorization': f'Bearer {self.access_token}' } response = requests.get(playlist_url, headers=headers) res = response.json() items = res['items'] # if res['next'] is None: return items while res['next']: response = requests.get(res['next'], headers=headers) res = response.json() items.extend(res['items']) res = [i for n, i in enumerate(items) if i not in items[:n]] for item in res: try: if not item['track']['name'] == "": self.track_list.append(item) except Exception as e: print(e) return None @property def name(self): playlist_url = f"https://api.spotify.com/v1/playlists/{self.playlist_id}" headers = { 'Authorization': f'Bearer {self.access_token}' } response = requests.get(playlist_url, headers=headers) return response.json()['name'] @property def image(self): playlist_url = f"https://api.spotify.com/v1/playlists/{self.playlist_id}/images" headers = { 'Authorization': f'Bearer {self.access_token}' } response = requests.get(playlist_url, headers=headers) image_url = response.json()[0]['url'] return image_url def search_song(song_name): results = YoutubeSearch(song_name, max_results=1).to_dict() if results: video_id = results[0]['id'] return video_id else: return None def make_playlist(playlist_id, playlist_data, song_list, task_id): song_objects = [] total_tracks = len(song_list) with concurrent.futures.ThreadPoolExecutor() as executor: futures = [executor.submit(process_track, track['track'], counter, total_tracks, playlist_data.name, task_id) for counter, track in enumerate(song_list, 1)] for future in concurrent.futures.as_completed(futures): if future.result(): song_objects.append(future.result()) logger.info(f"Creating Playlist: {playlist_data.name}") increase_progress(task_id) playlist = SpotifyPlaylist.objects.create( id=playlist_id, name=playlist_data.name, ) process_image(playlist, playlist_data.image) playlist.tracks.set(song_objects) def process_track(track, counter, total_tracks, playlist_name, task_id): try: track_id, track_name, album_image, artists = get_track_details(track) logger.info(f"Parsing track: {track_name} ({counter}/{total_tracks}) [{playlist_name}]") name = track_name if len(track_name) > 40: name = track_name[:40] if SpotifySong.objects.filter(id=track_id).exists(): song = SpotifySong.objects.get(id=track_id) else: x = search_song(f"{name}") if not x: return "None" song = SpotifySong.objects.create( id=track_id, name=track_name, artists=artists, youtube_video_id=x ) process_image(song, album_image) update_progress(song.name, task_id, song.image.url) return song except Exception as e: logger.error(e) increase_progress(task_id) return
from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.shortcuts import get_object_or_404, redirect, render from .forms import CommentForm, PostForm from .models import Follow, Group, Post, User POST_NUMBER = 10 def get_page(request, post_list): # Паджинация 10 постов на страницу paginator = Paginator(post_list, POST_NUMBER) page_number = request.GET.get('page') return paginator.get_page(page_number) def index(request): """Функция index передает данные в шаблон index.html.""" template = 'posts/index.html' post_list = Post.objects.all().select_related( 'author', 'group' ).order_by('-pub_date') page_obj = get_page(request, post_list) # Здесь код запроса к модели и создание словаря контекста context = { 'page_obj': page_obj, } return render(request, template, context) def group_posts(request, slug): """Функция group_posts передает данные в шаблон group_list.html.""" template = 'posts/group_list.html' group = get_object_or_404(Group, slug=slug) post_list = group.posts.select_related( 'author' ).order_by('-pub_date') page_obj = get_page(request, post_list) # Здесь код запроса к модели и создание словаря контекста context = { 'group': group, 'page_obj': page_obj } return render(request, template, context) def profile(request, username): """Здесь код запроса к модели и создание словаря контекста.""" template = 'posts/profile.html' # В тело страницы выведен список постов author = get_object_or_404( User.objects.all().prefetch_related( 'posts', 'posts__group' ), username=username) posts_list = author.posts.all() page_obj = get_page(request, posts_list) # Здесь код запроса к модели и создание словаря контекста if request.user.is_authenticated: following = Follow.objects.filter( user=request.user, author=author ).exists() else: following = False profile = author context = { 'author': author, 'page_obj': page_obj, 'following': following, 'profile': profile, } return render(request, template, context) def post_detail(request, post_id): template = 'posts/post_detail.html' """Здесь код запроса к модели и создание словаря контекста.""" post = get_object_or_404(Post, pk=post_id) form = CommentForm(request.POST or None) # В тело страницы выведен один пост, выбранный по pk context = { 'post': post, 'form': form, } return render(request, template, context) @login_required def post_create(request): """Добавлена "Новая запись" для авторизованных пользователей.""" form = PostForm(request.POST or None, files=request.FILES or None) if request.method == "POST" and form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user new_post.save() return redirect('posts:profile', username=request.user) group_list = Group.objects.all() context = { 'form': form, 'group_list': group_list, 'is_edit': False, 'button_name': 'Добавить', } return render(request, 'posts/create_post.html', context) @login_required def post_edit(request, post_id): """Добавлена страница редактирования записи.""" # Права на редактирование должны быть только у автора этого поста # Остальные пользователи должны перенаправляться # На страницу просмотра поста post = get_object_or_404(Post, pk=post_id) if post.author != request.user: return redirect('posts:post_detail', post_id=post_id) form = PostForm( request.POST or None, files=request.FILES or None, instance=post ) if form.is_valid(): form.save() return redirect('posts:post_detail', post_id=post_id) context = { 'post': post, 'form': form, 'is_edit': True, 'button_name': 'Сохранить' } return render(request, 'posts/create_post.html', context) @login_required def add_comment(request, post_id): # Получите пост post = get_object_or_404(Post, id=post_id) form = CommentForm(request.POST or None) context = { 'form': form, } if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.post = post comment.save() return redirect('posts:post_detail', post_id=post_id) return render(request, 'posts/post_detail.html', context) @login_required def follow_index(request): list_of_posts = Post.objects.filter(author__following__user=request.user) paginator = Paginator(list_of_posts, POST_NUMBER) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = {'page_obj': page_obj} return render(request, 'posts/follow.html', context) @login_required def profile_follow(request, username): author = get_object_or_404(User, username=username) if author != request.user: Follow.objects.get_or_create(user=request.user, author=author) return redirect('posts:profile', author) @login_required def profile_unfollow(request, username): author = get_object_or_404(User, username=username) is_follower = Follow.objects.filter(user=request.user, author=author) if is_follower.exists(): is_follower.delete() return redirect('posts:profile', username=author) def page_not_found(request, exception): # Переменная exception содержит отладочную информацию, # выводить её в шаблон пользователской страницы 404 мы не станем return render( request, "misc/404.html", {"path": request.path}, status=404 ) def server_error(request): return render(request, "misc/500.html", status=500)
import 'package:fp_ppb_e8/pages/auth/register_page.dart'; import 'package:fp_ppb_e8/pages/notes/notes_list.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; // import 'package:fp_ppb_e8/components/auth/login_button.dart'; import 'package:fp_ppb_e8/components/auth/text_field.dart'; class LoginPage extends StatefulWidget { const LoginPage({super.key}); @override State<LoginPage> createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { final emailController = TextEditingController(); final passwordController = TextEditingController(); void signUserIn() async { showDialog( context: context, barrierDismissible: false, builder: (context) { return const Center( child: CircularProgressIndicator(), ); }, ); try { await FirebaseAuth.instance.signInWithEmailAndPassword( email: emailController.text, password: passwordController.text, ); if (!mounted) return; Navigator.pop(context); Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => const NotesListPage(), ), ); } on FirebaseAuthException catch (e) { Navigator.pop(context); if (e.code == 'user-not-found') { showMessage('Incorrect Email'); } else if (e.code == 'wrong-password') { showMessage('Incorrect Password'); } else { showMessage('An error occurred. Please try again later.'); } } } void showMessage(String message) { showDialog( context: context, builder: (context) { return AlertDialog( backgroundColor: Colors.deepPurple, title: Center( child: Text( message, style: const TextStyle(color: Colors.white), ), ), ); }, ); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.grey[50], body: SafeArea( child: Center( child: SingleChildScrollView( padding: const EdgeInsets.symmetric(horizontal: 24.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const SizedBox(height: 50), const Icon( Icons.lock_outline, size: 100, color: Colors.deepPurple, ), const SizedBox(height: 50), Text( 'Welcome back, you\'ve been missed!', style: TextStyle( color: Colors.grey[800], fontSize: 24, fontWeight: FontWeight.bold, ), textAlign: TextAlign.center, ), const SizedBox(height: 25), MyTextField( controller: emailController, hintText: 'Email', obscureText: false, ), const SizedBox(height: 15), MyTextField( controller: passwordController, hintText: 'Password', obscureText: true, ), const SizedBox(height: 10), const Padding( padding: EdgeInsets.symmetric(horizontal: 25.0), ), const SizedBox(height: 25), ElevatedButton( onPressed: signUserIn, style: ElevatedButton.styleFrom( backgroundColor: Colors.deepPurple, padding: const EdgeInsets.symmetric( horizontal: 32, vertical: 12), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), ), ), child: const Text( 'Sign In', style: TextStyle(color: Colors.white, fontSize: 16), ), ), const SizedBox(height: 50), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Not a member?', style: TextStyle(color: Colors.grey[800]), ), const SizedBox(width: 4), TextButton( onPressed: () => Navigator.push( context, MaterialPageRoute( builder: (context) => const RegisterPage(), ), ), child: const Text( 'Register now', style: TextStyle( color: Colors.deepPurple, fontWeight: FontWeight.bold, ), ), ), ], ), ], ), ), ), ), ); } }
#!/usr/bin/env node /** * Module dependencies. */ const app = require('../app'); const debug = require('debug')('socket-server:server'); const http = require('http'); const {server: webSocketServer} = require("websocket"); /** * Get port from environment and store in Express. */ const port = normalizePort(process.env.PORT || '3000'); app.set('port', port); /** * Create HTTP server. */ const server = http.createServer(app); /** * Listen on provided port, on all network interfaces. */ // Also mount the app here server.on('request', app); server.listen(port); server.on('error', onError); server.on('listening', onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { const port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening() { const addr = server.address(); const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('Listening on ' + bind); } const clients = []; /** * WebSocket server */ const wsServer = new webSocketServer({ // WebSocket server is tied to a HTTP server. WebSocket // request is just an enhanced HTTP request. For more info // http://tools.ietf.org/html/rfc6455#page-6 httpServer: server, maxReceivedFrameSize: 1000000, maxReceivedMessageSize:1500000 }); // This callback function is called every time someone // tries to connect to the WebSocket server const connectClients = {}; wsServer.on('request', function (request) { console.log((new Date()) + ' Connection from origin ' + request.origin + '.'); // accept connection - you should check 'request.origin' to // make sure that client is connecting from your website // (http://en.wikipedia.org/wiki/Same_origin_policy) const connection = request.accept(null, request.origin); // we need to know client index to remove them on 'close' event clients.push(connection); // let userName = false; // let userColor = false; console.log((new Date()) + ' Connection accepted.'); // send back chat history // user sent some message connection.on('message', function (message) { for (const client of clients) { if (client !== connection) { client.send(JSON.stringify(message)); } } }); // user disconnected connection.on('close', function (connectionId) { const index = clients.indexOf(connection); if (index >= 0) { console.log('Close: ', index) clients.splice(index, 1); } }); });
use quote::quote; use proc_macro::TokenStream; use syn::{parse_macro_input, DeriveInput, DataStruct, FieldsNamed, Data, Fields, Visibility}; use syn::__private::ToTokens; use syn::Data::Struct; use syn::Fields::Named; #[proc_macro_attribute] pub fn public(_attr: TokenStream, item: TokenStream) -> TokenStream { let mut ast = parse_macro_input!(item as DeriveInput); let fields = match ast.data { Struct( DataStruct { fields: Named( FieldsNamed { ref named, .. }), .. } ) => named, _ => unimplemented!( "only works for structs with named fields" ), }; let builder_fields = fields.iter().map(|f| { let name = &f.ident; let ty = &f.ty; quote! { pub #name: #ty } }); let builder_fields_with_braces = quote!( { #(#builder_fields,)* } ); ast.data = Data::Struct(DataStruct { struct_token: Default::default(), fields: Fields::Named( syn::parse2(builder_fields_with_braces).unwrap() ), semi_token: None, }); ast.vis = Visibility::Public(Default::default()); ast.to_token_stream().into() }
<div class="container mt-4"> <div class="row"> <div class="col-12"> <table class="table table-bordered border-danger"> <thead> <tr> <th>STT</th> <th>Tên Pipe</th> <th>Dữ liệu đầu vào</th> <th>Dữ liệu đầu ra</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>UpperCase</td> <td>{{content}}</td> <td>{{content|uppercase}}</td> </tr> <tr> <td>2</td> <td>LowerCase</td> <td>{{content}}</td> <td>{{content|lowercase}}</td> </tr> <tr> <td>3</td> <td>TitleCase</td> <td>{{content}}</td> <td>{{content|titlecase}}</td> </tr> <tr> <td>4</td> <td>Slice chuổi</td> <td>{{title}}</td> <td>{{title|slice:5:9}}</td> </tr> <tr> <td>5</td> <td>Number</td> <td>{{amount}}</td> <td>{{amount|number:'3.0-4'}}</td> </tr> <tr> <td>6</td> <td>Percent</td> <td>{{value}}</td> <td>{{value|percent:'1.3-3'}}</td> </tr> <tr> <td>7</td> <td>Slice mảng</td> <td>{{array}}</td> <td>{{array|slice:1:3}}</td> </tr> <tr> <td>8</td> <td>Currency</td> <td>{{toltal}}</td> <td>{{toltal|currency:'VND':true:'1.0-3'}}</td> </tr> <tr> <td>9</td> <td>Currency</td> <td>{{toltal}}</td> <td>{{toltal|currency:'VND':true:'1.0-3'}}</td> </tr> <tr> <td>10</td> <td>Date</td> <td>{{today}}</td> <td>{{today|date:'dd/MM/yyyy hh:mm:ss a'}}</td> </tr> <tr> <td>11</td> <td>JsonBY</td> <td>{{products}}</td> <td>{{products|json}}</td> </tr> <tr> <td>12</td> <td>Kết hợp nhiều pipe</td> <td>{{products}}</td> <td>{{products|json|uppercase}}</td> </tr> </tbody> </table> </div> </div> </div>
'use strict'; const score0El = document.getElementById('score--0'); const score1El = document.getElementById('score--1'); const current0El = document.getElementById('current--0'); const current1El = document.getElementById('current--1'); const player0El = document.querySelector('.player--0'); const player1El = document.querySelector('.player--1'); const diceEl = document.querySelector('.dice'); const btnNew = document.querySelector('.btn--new'); const btnRoll = document.querySelector('.btn--roll'); const btnHold = document.querySelector('.btn--hold'); let scores, currentScore, activePlayer, playing; startGame(); // User rolls a dice btnRoll.addEventListener('click', function () { if (playing) { // 1. Generate random dice roll const dice = Math.trunc(Math.random() * 6) + 1; // 2. Display dice roll diceEl.classList.remove('hidden'); diceEl.src = `dice-${dice}.png`; if (dice !== 1) { // Add dice roll to current score and display new score currentScore += dice; document.getElementById(`current--${activePlayer}`).textContent = currentScore; } else { // switch player switchPlayer(); } } }); btnHold.addEventListener('click', function () { if (playing) { console.log('Hold button pressed!'); scores[activePlayer] += currentScore; document.getElementById(`score--${activePlayer}`).textContent = scores[activePlayer]; if (scores[activePlayer] >= 100) { playerWon(); } else { switchPlayer(); } } }); btnNew.addEventListener('click', startGame); function startGame() { scores = [0, 0]; currentScore = 0; activePlayer = 0; playing = true; score0El.textContent = 0; score1El.textContent = 0; current0El.textContent = 0; current1El.textContent = 0; diceEl.classList.add('hidden'); player0El.classList.add('player--active'); player1El.classList.remove('player--active'); player0El.classList.remove('player--winner'); player0El.classList.remove('player--winner'); } function switchPlayer() { document.getElementById(`current--${activePlayer}`).textContent = 0; currentScore = 0; activePlayer = activePlayer === 0 ? 1 : 0; player0El.classList.toggle('player--active'); player1El.classList.toggle('player--active'); } function playerWon() { document .querySelector(`.player--${activePlayer}`) .classList.remove('player--active'); document .querySelector(`.player--${activePlayer}`) .classList.add('player--winner'); playing = false; diceEl.classList.add('hidden'); }
/** * @file treeview.ts * @author Etienne Cochard * @license * Copyright (c) 2019-2021 R-libre ingenierie * * 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 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 <https://www.gnu.org/licenses/>. **/ import { Component, Container, ContainerEventMap, ContainerProps, EvDblClick, EventHandler, html } from './component'; import { HtmlString, Rect } from './tools'; import { Icon, IconID } from './icon'; import { Label } from './label'; import { HLayout, VLayout } from './layout'; import { EvClick, BasicEvent, EvDrag, EvSelectionChange } from './x4_events'; export interface EvExpand extends BasicEvent { node: TreeNode; } function EvExpand(node: TreeNode) { return BasicEvent<EvExpand>({ node }); } export interface HierarchicalNode { id: number; parent: number; name: string; leaf: boolean } export interface TreeNode { id: any; text: string | HtmlString; icon?: IconID; children?: TreeNode[]; open?: boolean; data?: any; parent?: number; cls?: string; } interface TreeViewEventMap extends ContainerEventMap { click: EvClick; dblclick: EvDblClick; expand: EvExpand; drag: EvDrag; selectionchange: EvSelectionChange; } export interface TreeViewProps extends ContainerProps<TreeViewEventMap> { root: TreeNode; // root node indent?: number; // items indentation gadgets?: Component[]; sort?: boolean; // sort items canDragItems?: boolean; renderItem?: ( itm: TreeNode ) => Component; dblclick?: EventHandler<EvDblClick>; selectionchange?: EventHandler<EvSelectionChange>; drag?: EventHandler<EvDrag>; } /** * */ export class TreeView extends VLayout<TreeViewProps, TreeViewEventMap> { m_view: Container; m_container: Container; m_selection: { id: any; el: Component }; constructor(props: TreeViewProps) { super(props); props.root = props.root; props.indent = props.indent ?? 8; props.gadgets = props.gadgets; props.sort = props.sort ?? true; this.m_selection = null; this.m_container = new Container({ cls: '@scroll-container' }); this.m_view = new Container({ cls: '@scroll-view', flex: 1, content: this.m_container }); this.setContent([ this.m_view, props.gadgets ? new HLayout({ cls: 'gadgets', content: props.gadgets }) : null, ]) this.setDomEvent( 'click', (e) => this._click(e) ); this.setDomEvent( 'dblclick', (e) => this._click(e) ); if (props.canDragItems) { this.setDomEvent('dragstart', (ev: DragEvent) => { let hit = Component.getElement(ev.target as HTMLElement, Component); let node = hit?.getData("node"); if (node) { ev.dataTransfer.effectAllowed = 'move'; ev.dataTransfer.items.add(JSON.stringify({ type: 'treeview', id: node.id }), 'string'); } else { ev.preventDefault(); ev.stopPropagation(); } }); this.setDomEvent('dragover', ev => this._dragEnter(ev)); this.setDomEvent('dragenter', ev => this._dragEnter(ev)); this.setDomEvent('dragend', ev => this._dragLeave(ev)); this.setDomEvent('dragleave', ev => this._dragLeave(ev)); this.setDomEvent('drop', ev => this._dragLeave(ev)); this.setDomEvent('drop', ev => this._drop(ev) ); } this.mapPropEvents(props, 'dblclick', 'drag', 'selectionchange' ); } private _dragEnter(ev: DragEvent) { ev.preventDefault(); let hit = Component.getElement(ev.target as HTMLElement, Component); let node = hit?.getData("node"); if (node) { hit.addClass('@drag-over'); ev.dataTransfer.dropEffect = 'move'; } } private _dragLeave(ev: Event) { let hit = Component.getElement(ev.target as HTMLElement, Component); let node = hit?.getData("node"); if (node) { hit.removeClass('@drag-over'); } } private _drop(ev: DragEvent) { let hit = Component.getElement(ev.target as HTMLElement, Component); let node = hit?.getData("node"); if (!node) { node = this.m_props.root; } if (node) { let parent: TreeNode; // is a folder if (node.children) { parent = node; } // in it's parent node else { parent = hit.getData("parent"); } for (let i = 0; i < ev.dataTransfer.items.length; i++) { ev.dataTransfer.items[0].getAsString((value) => { let data = JSON.parse(value); this.emit('drag', EvDrag( node, data, parent) ); }); } } } render() { this.__update( ); } private __update( ) { if (this.m_props.root) { let items = []; this._buildBranch(this.m_props.root, -1, items, this.m_props.root); this.m_container.setContent(items); } } updateElement( id: any ) { const { node: child, item } = this._getNode( id ); if( child ) { const pn = child.dom.parentNode; const newchild = this._makeNode( item, child.dom.classList.value, child.getData('icon'), child.getData('level') ); const dm = newchild._build( ); pn.replaceChild( dm, child.dom ); if( this.m_selection?.el===child ) { this.m_selection.el = newchild; } } } set root(root: TreeNode) { this.m_props.root = root; this.update(); } /** * same as root = xxx but keep elements open */ refreshRoot(root: TreeNode) { let openList = []; this.forEach((node: TreeNode): boolean => { if (node.open) { openList.push(node.id); } return false; }); let oldSel = this.selection; this.m_props.root = root; this.forEach((node: TreeNode): boolean => { if (openList.indexOf(node.id) >= 0) { node.open = true; } return false; }); this.__update( ); } private _buildBranch(node: TreeNode, level: number, items: Component[], parent: TreeNode) { let cls = '@tree-item'; if( node.cls ) { cls += ' '+node.cls; } if (!node.open && node.children) { cls += ' collapsed'; } if (node.children) { cls += ' folder'; if (node.children.length == 0) { cls += ' empty'; } } let icon: IconID = node.icon; if (icon === undefined) { if (node.children) { icon = 0xf078; } else { icon = 0xf1c6; } } if (level >= 0) { const item = this._makeNode( node, cls, icon, level ); if (this.m_selection?.id == node.id) { this.m_selection.el = item; item.addClass('selected'); } items.push(item); } if (level == -1 || node.open) { if (node.children) { if (this.m_props.sort) { // sort items case insensitive: // first folders // then items node.children = node.children.sort((a, b) => { let at = (a.children ? '0' + a.text : a.text).toLocaleLowerCase(); let bt = (b.children ? '0' + b.text : b.text).toLocaleLowerCase(); return at < bt ? -1 : at > bt ? 1 : 0; }); } node.children.forEach((c) => { this._buildBranch(c, level + 1, items, node) }); } } } private _renderDef( node: TreeNode ) { return new Label({ cls: 'tree-label', flex:1, text: node.text }); } private _makeNode( node: TreeNode, cls: string, icon: IconID, level: number ): Component { return new HLayout({ cls, content: [ new Icon({ cls: 'tree-icon', icon }), this.m_props.renderItem ? this.m_props.renderItem( node ) : this._renderDef( node ), ], data: { 'node': node, 'level': level, 'icon': icon, }, style: { paddingLeft: 4 + level * this.m_props.indent }, attrs: { draggable: this.m_props.canDragItems ? true : undefined }, }) } /** * */ forEach(cb: (node) => boolean) { let found = null; function scan(node) { if (cb(node) == true) { return true; } if (node.children) { for (let i = 0; i < node.children.length; i++) { if (scan(node.children[i])) { return true; } } } } if (this.m_props.root) { scan(this.m_props.root); } return found; } ensureVisible( id: any ) { const { node } = this._getNode( id ); if( node ) { node.scrollIntoView( ); } } set selection(id: any) { if (this.m_selection?.el) { this.m_selection.el.removeClass('selected'); } this.m_selection = null; if (id !== undefined) { const { node: sel } = this._getNode( id ); if( sel ) { this.m_selection = { id: id, el: sel }; sel.addClass('selected'); sel.scrollIntoView( ); } } } private _getNode( id ): {node:Component,item:TreeNode} { let found = { node: null, item: null }; this.m_container.enumChilds((c) => { let node = c.getData('node'); if (node?.id == id) { found = {node:c,item:node}; return true; } }); return found; } get selection() { return this.m_selection?.id; } getNodeWithId(id: any): TreeNode { return this.forEach((node) => node.id == id); } /** * */ private _click(ev: MouseEvent) { let dom = ev.target as HTMLElement; let idom = dom; while (dom != this.dom) { let el = Component.getElement(dom); let nd = el?.getData('node') as TreeNode; if (nd) { if (nd.children) { // on text or on expando ? if (el.hasClass('selected') || idom.classList.contains('tree-icon') ) { //expando nd.open = nd.open ? false : true; } this.m_selection = { id: nd.id, el: null }; let offset = this.m_view?.dom?.scrollTop; this.update( ); if (offset) { this.m_view.dom.scrollTo(0, offset); } this.emit('expand', EvExpand(nd)); } else { this.selection = nd.id; if (ev.type == 'click') { this.emit('click', EvClick(nd)); } else { this.emit('dblclick', EvDblClick(nd)); } } this.emit('selectionchange', EvSelectionChange(nd)); return; } dom = dom.parentElement; } if (ev.type == 'click') { this.emit('selectionchange', EvSelectionChange(null) ); } } /** * constructs a tree node from an array of strings * elements are organized like folders (separator = /) * @example * let root = TreeView.buildFromString( [ * 'this/is/a/final/file' * 'this/is/another/file' * ] ); */ static buildFromStrings(paths: string[], separator = '/'): TreeNode { let root: TreeNode = { id: 0, text: '<root>', children: [] }; function insert(elements: TreeNode[], path: string) { let pos = path.indexOf(separator); let main = path.substr(0, pos < 0 ? undefined : pos); let elem: TreeNode; if (pos >= 0) { elem = elements.find((el) => { return el.text == main; }); } if (!elem) { elem = { id: path, text: main, }; elements.push(elem); } if (pos >= 0) { if (!elem.children) { elem.children = []; } insert(elem.children, path.substr(pos + separator.length)); } } paths.forEach((path) => { insert(root.children, path); }); return root; } /** * constructs a tree node from an array of nodes like * node { * id: number, * parent: number, * name: string * } */ static buildFromHierarchy(nodes: HierarchicalNode[], cb?: (node: TreeNode) => void): TreeNode { let root: TreeNode = { id: 0, text: '<root>', children: [] }; let tree_nodes: TreeNode[] = []; function insert(node: HierarchicalNode) { let elem: TreeNode; let pelem: TreeNode; if (node.parent > 0) { pelem = tree_nodes.find((tnode: TreeNode) => tnode.id == node.parent); if (!pelem) { pelem = { id: node.parent, text: '', children: [] }; tree_nodes.push(pelem); } if (!pelem.children) { pelem.children = []; } } else { pelem = root; } elem = tree_nodes.find((tnode: TreeNode) => tnode.id == node.id); if (!elem) { elem = { id: node.id, text: node.name, parent: node.parent, }; if (!node.leaf) { elem.children = []; } else { elem.icon = null; } } else { elem.text = node.name; elem.parent = node.parent; } tree_nodes.push(elem); pelem.children.push(elem) } nodes.forEach(insert); if (cb) { tree_nodes.forEach(cb); } return root; } }
import React, { useEffect } from "react"; import { logoutAction } from "../actions/LoginActions"; import { useSelector, useDispatch } from "react-redux"; import { Link, useNavigate } from "react-router-dom"; import bye from "../images/bye.png"; const Logout = () => { const dispatch = useDispatch(); const navigate = useNavigate(); const user = useSelector((state) => state.login.user); useEffect(() => { dispatch(logoutAction(user)); if(user.userId === 0){ return navigate('/login'); } }, []); return ( <div> <img className="img-fluid mt-5" src={bye} alt="" style={{maxWidth: '300px'}}/> <h1 className="mt-5"> Logged out successfully! </h1> <Link to='/' type="button" className="btn btn-primary m-2"> <i class="bi bi-house-fill"></i> Home </Link> <Link to='/login' type="button" className="btn btn-success m-2"> <i class="bi bi-box-arrow-in-right"></i> Login </Link> </div> ); }; export default Logout;
require("../env"); require("../../d3"); require("../../d3.geo"); var vows = require("vows"), assert = require("assert"); var suite = vows.describe("d3.geo.bonne"); suite.addBatch({ "default instance": { topic: function() { return d3.geo.bonne(); }, "scale defaults to 200": function(bonne) { assert.equal(bonne.scale(), 200); }, "parallel defaults to 45°": function(bonne) { assert.equal(bonne.parallel(), 45); }, "origin defaults to [0,0]": function(bonne) { assert.deepEqual(bonne.origin(), [0, 0]); }, "translate defaults to [480, 250]": function(bonne) { assert.deepEqual(bonne.translate(), [480, 250]); } }, "Bonne at 40° parallel": { topic: function() { return d3.geo.bonne().parallel(40); }, "Arctic": function(bonne) { var lonlat = [0, 85], coords = bonne(lonlat); assert.inDelta(coords, [480, 92.920367], 1e-6); assert.inDelta(bonne.invert(coords), lonlat, 1e-6); }, "Antarctic": function(bonne) { var lonlat = [0, -85], coords = bonne(lonlat); assert.inDelta(coords, [480, 686.332312], 1e-6); assert.inDelta(bonne.invert(coords), lonlat, 1e-6); }, "Hawaii": function(bonne) { var lonlat = [-180, 0], coords = bonne(lonlat); assert.inDelta(coords, [103.604887, -22.895998], 1e-6); assert.inDelta(bonne.invert(coords), lonlat, 1e-6); }, "Phillipines": function(bonne) { var lonlat = [180, 0], coords = bonne(lonlat); assert.inDelta(coords, [856.395112, -22.895998], 1e-6); assert.inDelta(bonne.invert(coords), lonlat, 1e-6); }, "invert observes translation": function() { var bonne = d3.geo.bonne().translate([123, 99]).scale(100), coords = bonne([0, 85]), lonlat = bonne.invert(coords); assert.inDelta(lonlat[0], 0, 1e-6); assert.inDelta(lonlat[1], 85, 1e-6); }, "invert(project(location)) equals location": function(bonne) { for (var i = -1; i < 20; ++i) { var location = [Math.random() * 360 - 180, Math.random() * 180 - 90]; assert.inDelta(location, bonne.invert(bonne(location)), .5); } }, "project(invert(point)) equals point": function(bonne) { for (var i = -1; i < 20; ++i) { var point = [Math.random() * 700 + 100, Math.random() * 400 + 50]; assert.inDelta(point, bonne(bonne.invert(point)), .5); } } }, "Werner": { topic: function() { return d3.geo.bonne().parallel(90); }, "invert(project(location)) equals location": function(bonne) { for (var i = -1; i < 20; ++i) { var location = [Math.random() * 360 - 180, Math.random() * 180 - 90]; assert.inDelta(location, bonne.invert(bonne(location)), .5); } }, "project(invert(point)) equals point": function(bonne) { for (var i = -1; i < 20; ++i) { var point = [Math.random() * 700 + 100, Math.random() * 400 + 50]; assert.inDelta(point, bonne(bonne.invert(point)), .5); } } }, "Sinsuoidal": { topic: function() { return d3.geo.bonne().parallel(0); }, "invert(project(location)) equals location": function(bonne) { for (var i = -1; i < 20; ++i) { var location = [Math.random() * 360 - 180, Math.random() * 180 - 90]; assert.inDelta(location, bonne.invert(bonne(location)), .5); } }, "project(invert(point)) equals point": function(bonne) { for (var i = -1; i < 20; ++i) { var point = [Math.random() * 700 + 100, Math.random() * 400 + 50]; assert.inDelta(point, bonne(bonne.invert(point)), .5); } } } }); suite.export(module);
import Blog from '@/public/svgs/blog-sidebar.svg' import Discord from '@/public/svgs/discord-sidebar.svg' import AboutXANALIA from '@/public/svgs/icon-about-sidebar.svg' // import Award from '@/public/svgs/icon-award-sidebar.svg' import Collections from '@/public/svgs/icon-collections-sidebar.svg' import Create from '@/public/svgs/icon-create-sidebar.svg' import Home from '@/public/svgs/icon-home-sidebar.svg' import ExploreNFTs from '@/public/svgs/icon-market-sidebar.svg' import ProfileActive from '@/public/svgs/icon-profile-active.svg' import Profile from '@/public/svgs/icon-profile.svg' import Medium from '@/public/svgs/medium-sidebar.svg' import Twitter from '../../../public/svgs/twitter-sidebar.svg' // import Activity from '@/public/svgs/icon-activity-sidebar.svg' // import Farm from '@/public/svgs/icon-farm-sidebar.svg' // import Ranking from '@/public/svgs/icon-ranking.svg' import AboutXanaActive from '@/public/svgs/icon-about-xanalia-active.svg' // import AwardActive from '@/public/svgs/icon-award-active.svg' import CollectionActive from '@/public/svgs/icon-collections-active.svg' import CommunityActive from '@/public/svgs/icon-community-active.svg' import Community from '@/public/svgs/icon-community-sidebar.svg' import CreateActive from '@/public/svgs/icon-create-active.svg' import Doc from '@/public/svgs/icon-doc-sidebar.svg' import HomeActive from '@/public/svgs/icon-home-active.svg' import MarketActive from '@/public/svgs/icon-marketplace-active.svg' import MyItemActive from '@/public/svgs/icon-my-item-active.svg' import MyItem from '@/public/svgs/icon-my-items.svg' import StatisticActive from '@/public/svgs/icon-statistic-active.svg' import Statistics from '@/public/svgs/icon-statistic.svg' // import MyItemActive from '@/public/svgs/icon-my-item-active.svg' export const itemsSidebar: Array<{ icon: any iconActive?: any label: string href: string isOpenNewTab?: boolean isLogin?: boolean items?: Array<{ icon?: any label: string href: string isOpenNewTab?: boolean isLogin?: boolean }> }> = [ { icon: <Home />, iconActive: <HomeActive />, label: 'HOME', href: '/', }, { icon: <ExploreNFTs />, iconActive: <MarketActive />, label: 'MARKETPLACE', href: '/marketplace', }, { icon: <Collections />, iconActive: <CollectionActive />, label: 'COLLECTIONS', href: '/collections', }, // { // icon: <Launchpad />, // iconActive: <LaunchPadActive />, // label: 'LAUNCHPAD', // href: '/launchpad', // }, { icon: <Create />, iconActive: <CreateActive />, label: 'CREATE', href: '/create', items: [ { label: 'COLLECTION', href: '/create/collection', isLogin: true, }, { label: 'NFT', href: '/create/nft', isLogin: true, }, ], }, { icon: <MyItem />, iconActive: <MyItemActive />, label: 'MY_ITEMS', href: '/my-items?tab=nft', isLogin: true, }, { icon: <Profile />, iconActive: <ProfileActive />, label: 'MY_PROFILE', href: '/profile/account', isLogin: true, }, // { // icon: <Ranking />, // label: 'MY_COLLECTIONS', // href: '/my-collection', // items: [ // { // label: 'CREATE_COLLECTION', // href: '/my-collections/create-collection', // }, // { // label: 'COLLECTIONS_LIST', // href: '/my-collections/collections-list', // }, // ], // }, // { // icon: <Award />, // iconActive: <AwardActive />, // label: 'AWARDS', // href: '/award-1', // }, { icon: <AboutXANALIA />, iconActive: <AboutXanaActive />, label: 'ABOUT_XANALIA', isOpenNewTab: true, href: 'https://v1.xanalia.com/about', }, // { // icon: <Activity />, // label: 'ACTIVITY', // href: '/activity', // }, // { // icon: <Farm />, // label: 'Farm', // href: '/farm', // }, { icon: <Statistics />, iconActive: <StatisticActive />, label: 'STATISTICS', href: '/statistics', items: [ { label: 'RANKING', href: '/statistics/ranking', }, { label: 'ACTIVITY', href: '/statistics/activity', }, ], }, { icon: <Doc />, label: 'DOC', href: 'https://docs.xanalia.com/xanalia/', isOpenNewTab: true, }, ] export const communityArr: Array<{ icon: any iconActive?: any label: string href: string isOpenNewTab?: boolean isLogin?: boolean items?: Array<{ icon?: any label: string href: string isOpenNewTab?: boolean isLogin?: boolean }> }> = [ { icon: <Community />, iconActive: <CommunityActive />, label: 'COMMUNITY', href: '/community', items: [ { icon: <Discord />, label: 'DISCORD', href: 'https://discord.com/invite/XANA', isOpenNewTab: true, }, { icon: <Twitter />, label: 'TWITTER', href: 'https://twitter.com/xanalia_nft', isOpenNewTab: true, }, { icon: <Medium />, label: 'MEDIUM', href: 'https://xanametaverse.medium.com/', isOpenNewTab: true, }, { icon: <Blog />, label: 'BLOG', href: 'https://web.xanalia.com/blog/', isOpenNewTab: true, }, ], }, ]
package com.istad.istadresfulapi.utils; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; @AllArgsConstructor @NoArgsConstructor @Data @Accessors(chain = true) public class Response <T>{ public enum Status{ OK, BAD_REQUEST, UNAUTHORIZED, EXCEPTION, VALIDATION_EXCEPTION, WRONG_CREDENTIAL, ACCESS_DENIED, NOT_FOUND, DUPLICATE_ENTRY, SUCCESS_DELETE, CREATE_SUCCESS , UPDATE_SUCCESS } private T payload; private Object message; private boolean success = false; private Object metadata; private Status status; //create methods public static <T> Response<T> ok(){ Response<T> response = new Response<>(); response.setStatus(Status.OK); response.setSuccess(true); return response; } public static <T> Response<T> badRequest(){ Response<T> response = new Response<>(); response.setStatus(Status.BAD_REQUEST); response.setSuccess(false); return response; } public static <T> Response<T> createSuccess(){ Response<T> response = new Response<>(); response.setStatus(Status.CREATE_SUCCESS); response.setSuccess(true); return response; } public static <T> Response<T> updateSuccess(){ Response<T> response = new Response<>(); response.setStatus(Status.UPDATE_SUCCESS); response.setSuccess(true); return response; } public static <T> Response<T> deleteSuccess(){ Response<T> response = new Response<>(); response.setStatus(Status.SUCCESS_DELETE); response.setSuccess(true); return response; } public static <T> Response<T> notFound(){ Response<T> response = new Response<>(); response.setStatus(Status.NOT_FOUND); // response.setSuccess(true); return response; } public static <T> Response<T> exception(){ Response<T> response = new Response<>(); response.setStatus(Status.EXCEPTION); response.setSuccess(false); return response; } }
import React from 'react'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import MovieList from './pages/MovieList'; import NewMovie from './pages/NewMovie'; import MovieDetails from './pages/MovieDetails'; import EditMovie from './pages/EditMovie'; import NotFound from './pages/NotFound'; function App() { return ( <div> <h1>Movie Card Library CRUD</h1> <BrowserRouter> <Switch> <Route exact path="/" component={ MovieList } /> <Route exact path="/movies/new" render={ (props) => <NewMovie { ...props } /> } /> <Route exact path="/movies/:id" render={ (props) => <MovieDetails { ...props } /> } /> <Route exact path="/movies/:id/edit" render={ (props) => <EditMovie { ...props } /> } /> <Route component={ NotFound } /> </Switch> </BrowserRouter> </div> ); } export default App;
import { lazy } from 'react'; import { Route, Routes } from 'react-router-dom'; import SharedLayout from './SharedLayout'; const Home = lazy(() => import('../pages/Home')); const AboutUs = lazy(() => import('../pages/AboutUs')); const Adoption = lazy(() => import('../pages/Adoption')); const PetPage = lazy(() => import('../pages/PetPage')) const CheckList = lazy(() => import('../pages/CheckList')); const Help = lazy(() => import('../pages/Help')); const Contacts = lazy(() => import('../pages/Contacts')); export const App = () => { return ( <div> <Routes> <Route path="/" element={<SharedLayout />}> <Route index element={<Home />} /> <Route path="/about-us" element={<AboutUs />} /> <Route path="/adoption" element={<Adoption />} /> <Route path="/adoption/:petId" element={<PetPage />} /> <Route path="/check-list" element={<CheckList />} /> <Route path="/help" element={<Help />} /> <Route path="/contacts" element={<Contacts />} /> <Route path="*" element={<Home />} /> </Route> </Routes> </div> ); };
import React, { useState, useEffect } from 'react' import { Link } from 'react-router-dom' import { Form, Button, Row, Col } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' import Message from '../components/Message' import Loader from '../components/Loader' import { login } from '../actions/userActions' import FormContainer from '../components/FormContainer' import { useNavigate, useLocation } from 'react-router-dom'; const LoginScreen = () => { const [email, setEmail] = useState('') const [password, setPassword] = useState('') const dispatch = useDispatch() const userLogin = useSelector((state) => state.userLogin); const { loading, error, userInfo } = userLogin; const location = useLocation(); const navigate = useNavigate(); const redirect = new URLSearchParams(location.search).get('redirect') || '/'; useEffect(() => { if (userInfo) { navigate(redirect); } }, [navigate, userInfo, redirect]); //表单提交函数 const submitHandler = (e) => { e.preventDefault() //dispatch login函数 dispatch(login(email, password)) } return ( <FormContainer> <h1>登录</h1> {error && <Message variant='danger'>{error}</Message>} {loading && <Loader />} <Form onSubmit={submitHandler}> <Form.Group controlId='email'> <Form.Label>邮箱地址:</Form.Label> <Form.Control type='email' placeholder='请输入邮箱' value={email} onChange={(e) => setEmail(e.target.value)} ></Form.Control> </Form.Group> <Form.Group controlId='password'> <Form.Label>密码:</Form.Label> <Form.Control type='password' placeholder='请输入密码' value={password} onChange={(e) => setPassword(e.target.value)} ></Form.Control> </Form.Group> <Button type='submit' variant='primary'> 登录 </Button> </Form> <Row className='py-3'> <Col> 新用户? <Link to={redirect ? `/register?redirect=${redirect}` : '/register'}> 去注册 </Link> </Col> </Row> </FormContainer> ) } export default LoginScreen;
/** * @author Raju Lakshman * @date Sept 2020 * @description Test class for the ddMultiSelectPicklist component and framework */ @IsTest public without sharing class CDdMultiSelectPicklistTest { @IsTest public static void testObjectRecords() { CDdMultiSelectPicklistCtrl.InitWrapper initWrapper = CDdMultiSelectPicklistCtrl.getSearchInfo('Example_Object_Records'); system.assert(initWrapper.searchInfo.Query_and_Cache_on_Init__c == false,'Example_Object_Records Query and Cache on Init is incorrect'); List<CDdMultiSelectPicklistWrapper> recordIdsToIgnore = new List<CDdMultiSelectPicklistWrapper>(); List<User> users = [SELECT Id,Name FROM User WHERE Name LIKE 'John%' and isActive = true LIMIT 1]; if (!users.isEmpty()) { recordIdsToIgnore.add(createTestWrapper(users[0].Id,users[0].Name)); } CDdMultiSelectPicklistValuesWrapper valuesWrapper = CDdMultiSelectPicklistCtrl.getLookupResultBySearchInfo( 'John', JSON.serialize(recordIdsToIgnore), null, initWrapper.searchInfo, initWrapper.searchInfo.DD_Multi_Select_Picklist_SOSL_Return__r == null ? new List<DD_Multi_Select_Picklist_SOSL_Return__mdt>() : initWrapper.searchInfo.DD_Multi_Select_Picklist_SOSL_Return__r ); system.assertEquals(valuesWrapper.keyWord,'John','Invalid keyword'); for (CDdMultiSelectPicklistWrapper value : valuesWrapper.values) { if (!users.isEmpty()) system.assertNotEquals(value.value,users[0].Id,'Example_Object_Records exclude record did not work'); system.assert(value.pillLabel.containsIgnoreCase('john'),'Did not find keyword in return value'); } } @IsTest public static void testAggregateQuery() { CDdMultiSelectPicklistCtrl.InitWrapper initWrapper = CDdMultiSelectPicklistCtrl.getSearchInfo('Example_Aggregate_Query'); system.assert(initWrapper.searchInfo.Query_and_Cache_on_Init__c == true,'Example_Aggregate_Query Query and Cache on Init is incorrect'); system.assert(!initWrapper.lookupResults.isEmpty(),'Example_Aggregate_Query lookupResult is empty'); } @IsTest public static void testSOSL() { CDdMultiSelectPicklistCtrl.InitWrapper initWrapper = CDdMultiSelectPicklistCtrl.getSearchInfo('Example_SOSL'); system.assert(initWrapper.searchInfo.Query_and_Cache_on_Init__c == false,'Example_SOSL Query and Cache on Init is incorrect'); List<DD_Multi_Select_Picklist_SOSL_Return__mdt> soslMdt = initWrapper.searchInfo.DD_Multi_Select_Picklist_SOSL_Return__r; system.assert(soslMdt != null && !soslMdt.isEmpty(),'Example_SOSL Did not have sosl cmt records'); List<CDdMultiSelectPicklistWrapper> recordIdsToIgnore = new List<CDdMultiSelectPicklistWrapper>(); List<User> users = [SELECT Id,Name FROM User WHERE Name LIKE 'John%' and isActive = true LIMIT 2]; List<Id> fixedSearchResults = new List<Id>(); if (!users.isEmpty()) { recordIdsToIgnore.add(createTestWrapper(users[0].Id,users[0].Name)); if (users.size() == 2) fixedSearchResults.add(users[1].Id); } Test.setFixedSearchResults( fixedSearchResults ); CDdMultiSelectPicklistValuesWrapper valuesWrapper = CDdMultiSelectPicklistCtrl.getLookupResultBySearchInfo( 'John', JSON.serialize(recordIdsToIgnore), null, initWrapper.searchInfo, initWrapper.searchInfo.DD_Multi_Select_Picklist_SOSL_Return__r ); system.assertEquals(valuesWrapper.keyWord,'John','Invalid keyword'); } @IsTest public static void testPicklistMetadata() { CDdMultiSelectPicklistCtrl.InitWrapper initWrapper = CDdMultiSelectPicklistCtrl.getSearchInfo('Example_Object_Picklist'); system.assert(initWrapper.searchInfo.Query_and_Cache_on_Init__c == true,'Example_Object_Picklist Query and Cache on Init is incorrect'); system.assert(!initWrapper.lookupResults.isEmpty(),'Example_Object_Picklist Lookupresult is empty'); } @IsTest public static void testStaticValues() { CDdMultiSelectPicklistCtrl.InitWrapper initWrapper = CDdMultiSelectPicklistCtrl.getSearchInfo('Example_Filter_Static_Values'); system.assert(initWrapper.searchInfo.Query_and_Cache_on_Init__c == true,'Example_Filter_Static_Values Query and Cache on Init is incorrect'); system.assert(!initWrapper.lookupResults.isEmpty(),'Example_Filter_Static_Values Lookupresult is empty'); } @IsTest public static void testCustomSearch() { CDdMultiSelectPicklistCtrl.InitWrapper initWrapper = CDdMultiSelectPicklistCtrl.getSearchInfo('Example_Custom_Search'); system.assert(initWrapper.searchInfo.Query_and_Cache_on_Init__c == false,'Example_Custom_Search Query and Cache on Init is incorrect'); Map<String,Object> arguments = new Map<String,Object> { 'IsActive' => 'true' }; CDdMultiSelectPicklistValuesWrapper valuesWrapper = CDdMultiSelectPicklistCtrl.getLookupResultBySearchInfo( 'John', CDdCoreConstants.BLANK_STRING, JSON.serialize(arguments), initWrapper.searchInfo, initWrapper.searchInfo.DD_Multi_Select_Picklist_SOSL_Return__r == null ? new List<DD_Multi_Select_Picklist_SOSL_Return__mdt>() : initWrapper.searchInfo.DD_Multi_Select_Picklist_SOSL_Return__r ); system.assertEquals(valuesWrapper.keyWord,'John','Invalid keyword'); } @isTest public static void testLookupResult() { CDdMultiSelectPicklistValuesWrapper valuesWrapper = CDdMultiSelectPicklistCtrl.getLookupResult( 'John', '[]', null, 'Example_Object_Records'); system.assertEquals(valuesWrapper.keyWord,'John','Invalid keyword'); } @isTest public static void testIncreaseCodeCoverage() { CDdMultiSelectPicklistValuesWrapper valuesWrapper = new CDdMultiSelectPicklistValuesWrapper(); List<CDdMultiSelectPicklistWrapper> toSort = new List<CDdMultiSelectPicklistWrapper>(); toSort.add(createTestWrapper('1')); toSort.add(createTestWrapper('3')); toSort.add(createTestWrapper('5')); toSort.add(createTestWrapper('2')); toSort.add(createTestWrapper('4')); List<CDdMultiSelectPicklistWrapperSorter> dropdownLabelSorter = new List<CDdMultiSelectPicklistWrapperSorter>(); List<CDdMultiSelectPicklistWrapperSorter> valueSorter = new List<CDdMultiSelectPicklistWrapperSorter>(); for (CDdMultiSelectPicklistWrapper wrapper : toSort) { dropdownLabelSorter.add(new CDdMultiSelectPicklistWrapperSorter(wrapper)); valueSorter.add(new CDdMultiSelectPicklistWrapperSorter(wrapper,'value')); } dropdownLabelSorter.sort(); valueSorter.sort(); } private static CDdMultiSelectPicklistWrapper createTestWrapper(String value) { return createTestWrapper(value,value); } private static CDdMultiSelectPicklistWrapper createTestWrapper(String value,String label) { CDdMultiSelectPicklistWrapper wrapper = new CDdMultiSelectPicklistWrapper(); wrapper.dropDownLabel = label; wrapper.pillLabel = label; wrapper.value = value; return wrapper; } }
import { create_UUID } from '@/helpers/common' import { sequelize } from '@/helpers/connection' import { element as elementPaginate } from '@/helpers/paginate' import { CustomerResourceModel } from '@/models' import { CustomerResourceRepositiory } from '@/repositories' import DateUtils from '@/utils/DateUtils' import { Message } from '@/utils/Message' import ResponseUtils from '@/utils/ResponseUtils' import * as dotenv from 'dotenv' const { QueryTypes } = require('sequelize') dotenv.config() class CustomerResourceService { constructor() { this.result = ResponseUtils this.customerResourceModel = CustomerResourceModel } async create(payload) { try { const customerResource = await CustomerResourceRepositiory.create(payload) return customerResource } catch (error) { throw { statusCode: 400, message: Message.DO_NOT_CREATE, } } } async update(params) { try { const payload = { data: params.template, option: { id: params.id }, } const template = await CustomerResourceRepositiory.update(payload) return template } catch (error) { throw { statusCode: 400, message: Message.DO_NOT_UPDATE, } } } async findById(id) { try { return await this.customerResourceModel .findOne({ where: { id: id, }, }) .then((res) => res.dataValues) } catch (error) { throw { statusCode: 400, message: Message.CUSTOMER_RESOURCE_NOT_FIND, } } } async deleteById(id) { try { const findData = await this.customerResourceModel.findOne({ where: { id: id, }, }) if (!findData) { return this.result(false, 400, Message.CUSTOMER_RESOURCE_NOT_FIND, null) } return await CustomerResourceRepositiory.delete({ id }).then((res) => res) } catch (error) { throw { statusCode: 400, message: Message.CUSTOMER_RESOURCE_NOT_FIND, } } } async get(req, res) { try { const limitInput = req.query.perPage const pageInput = req.query.currentPage const name = req.query.name const field_name = req.query.fieldName let selectSql = 'SELECT c_r.*, COUNT(c.id) AS num_customers' let fromSql = ' FROM public.customer_resources as c_r' let leftJoin = ` LEFT JOIN public.customers as c on c."customer_resource_id"::uuid = c_r."id"::uuid` let bindParam = [] let whereSql = ' WHERE 1 = 1 ' if (name) { bindParam.push('%' + name + '%') whereSql += ` AND c_r.name ilike $${bindParam.length} ` } if (field_name) { bindParam.push('%' + field_name + '%') whereSql += ` AND c_r.field_name ilike $${bindParam.length} ` } let groupby = ' GROUP BY c_r.id' let orderBy = ` ORDER BY c_r.created_at DESC ` let rawSql = selectSql + fromSql + leftJoin + whereSql + groupby + orderBy const result = await sequelize.query(rawSql, { bind: bindParam, type: QueryTypes.SELECT, }) const totalRecord = result.length if (!limitInput || !pageInput) { const elements = await sequelize.query(rawSql, { bind: bindParam, type: QueryTypes.SELECT, }) const customerResourceData = { customerResource: elements, } return this.result(200, true, Message.SUCCESS, customerResourceData) } const { totalPage, page, offset } = elementPaginate({ totalRecord: result.length, page: pageInput, limit: limitInput, }) const elements = await sequelize.query( rawSql + ` LIMIT ${limitInput} OFFSET ${offset}`, { bind: bindParam, type: QueryTypes.SELECT } ) const customerResourceData = { customerResource: elements, paginate: { totalRecord, totalPage, size: +limitInput, page: +page, }, } return this.result(200, true, Message.SUCCESS, customerResourceData) } catch (error) { throw { statusCode: error?.statusCode || 400, message: error?.message, } } } //lấy danh sách khách hàng của nguồn async getCustomerOfResource(req, res) { try { const limitInput = req.query.perPage const pageInput = req.query.currentPage const customerResourceId = req.query.customerResourceId const userId = req.query.userId const statusSend = req.query.statusSend === '0' ? 'Đã gửi' : req.query.statusSend === '1' ? 'Chưa gửi' : req.query.statusSend === '2' ? 'Gửi lỗi' : '' const startDate = req.query.startDate ? DateUtils.convertStartDateToStringFullTime(req.query.startDate) : null const endDate = req.query.endDate ? DateUtils.convertEndDateToStringFullTime(req.query.endDate) : null let selectSql = `SELECT * FROM (SELECT c.*, users.name as user_name, c_r.name as customer_resource, c.start_date, c.send_date, Case WHEN c.frequency_of_email IS NULL AND c.send_date IS NULL THEN 'Chưa gửi' WHEN c.frequency_of_email IS NULL AND c.send_date IS NOT NULL AND c.status = 0 THEN 'Đã gửi' WHEN c.frequency_of_email IS NULL AND c.send_date IS NOT NULL AND c.status = 2 THEN 'Gửi lỗi' WHEN c.frequency_of_email IS NOT NULL AND c.send_date IS NULL THEN 'Chưa gửi' WHEN c.frequency_of_email IS NOT NULL AND c.send_date <= c.start_date THEN 'Chưa gửi' WHEN c.frequency_of_email IS NOT NULL AND c.send_date > c.start_date AND c.status = 0 THEN 'Đã gửi' WHEN c.frequency_of_email IS NOT NULL AND c.send_date > c.start_date AND c.status = 2 THEN 'Gửi lỗi' END as status_send, ` let countEmail = `( SELECT COUNT(m_h.id) AS sent_count from public.sent_mail_histories as m_h where m_h.customer_id = c.customer_id ` let countFeedback = `(SELECT COUNT( DISTINCT CASE WHEN m_h.status_feedback = '1' THEN m_h.id END ) AS feedback_count from public.sent_mail_histories as m_h where m_h.customer_id = c.customer_id ` let fromSql = ` From ( select customer_id, name, romaji_name, url, email, address, frequency_of_email, customer_resource_id, created_at, person_in_charge_id, send_date, status, ( Current_date - ( Case WHEN frequency_of_email = '1' THEN 7 WHEN frequency_of_email = '2' THEN 30 WHEN frequency_of_email = '3' THEN 60 WHEN frequency_of_email = '4' THEN 90 WHEN frequency_of_email = '5' THEN 180 ELSE 0 END ) ) :: timestamp with time zone as start_date FROM ( SELECT c.id AS customer_id, c.name, c.romaji_name, c.url, c.email, c.address, c.frequency_of_email, c.customer_resource_id, c.created_at, c.person_in_charge_id, m_h.send_date, m_h.status, ROW_NUMBER() OVER ( PARTITION BY c.id ORDER BY m_h.send_date DESC ) AS rn FROM public.customers as c LEFT JOIN public.sent_mail_histories as m_h ON c.id = m_h.customer_id ) as subquery WHERE rn = 1 ) as c` let leftJoin = ` LEFT JOIN public.customer_resources as c_r on c.customer_resource_id = c_r.id LEFT JOIN public.users on c.person_in_charge_id = users.id ` let bindParam = [] let whereSql = ` WHERE css.customer_resource_id = '${customerResourceId}' ` if (startDate) { bindParam.push(startDate) countEmail += ` AND m_h.send_date >= $${bindParam.length} ` countFeedback += ` AND m_h.send_date >= $${bindParam.length} ` } if (endDate) { bindParam.push(endDate) countEmail += ` AND m_h.send_date <= $${bindParam.length} ` countFeedback += ` AND m_h.send_date <= $${bindParam.length} ` } if (userId) { bindParam.push(userId) whereSql += ` AND css.person_in_charge_id = $${bindParam.length} ` } if (statusSend) { bindParam.push(statusSend) whereSql += ` AND css.status_send = $${bindParam.length} ` } countEmail += '),' countFeedback += ')' let groupby = ` GROUP BY c.customer_id, c.name, c.romaji_name, c.url, c.email, c.address, c.frequency_of_email, c.customer_resource_id, c.start_date, c_r.id, c.created_at, c.person_in_charge_id, users.name,c.send_date, c.status ORDER BY c.created_at DESC ) as css` let rawSql = selectSql + countEmail + countFeedback + fromSql + leftJoin + groupby + whereSql const result = await sequelize.query(rawSql, { bind: bindParam, type: QueryTypes.SELECT, }) const totalSentCount = result?.reduce((accumulator, item) => { return accumulator + parseInt(item?.sent_count) }, 0) const totalResponseCount = result?.reduce((accumulator, item) => { return accumulator + parseInt(item?.feedback_count) }, 0) const totalRecord = result?.length const { totalPage, page, offset } = elementPaginate({ totalRecord: result?.length, page: pageInput, limit: limitInput, }) const elements = await sequelize.query( rawSql + ` LIMIT ${limitInput} OFFSET ${offset}`, { bind: bindParam, type: QueryTypes.SELECT } ) const customerResourceData = { customerResource: { data: elements?.map((item) => { return { ...item, id: create_UUID() } }), total_sent_count: totalSentCount, total_response_count: totalResponseCount, }, paginate: { totalRecord, totalPage, size: +limitInput, page: +page, }, } return this.result(200, true, Message.SUCCESS, customerResourceData) } catch (error) { throw { statusCode: error?.statusCode || 400, message: error?.message, } } } //lấy lịch sử gửi mail của nguồn async getHistorySendMail(req, res) { try { const limitInput = req.query.perPage const pageInput = req.query.currentPage const customerResourceId = req.query.customerResourceId const customerId = req.query.customerId const statusResponse = req.query.statusResponse const startDate = req.query.startDate ? DateUtils.convertStartDateToStringFullTime(req.query.startDate) : null const endDate = req.query.endDate ? DateUtils.convertEndDateToStringFullTime(req.query.endDate) : null let selectSql = `SELECT c.id as customer_id, c.name, c.url, c.email, m_h.feedback_date, m_h.send_date, m_h.status_feedback, m_h.user_id, c_r.name as customer_resource, users.name as user_name, m_h.status, m_h.template_id, m_h.pregnancy_status_sending, templates.template_name ` let fromSql = ' FROM public.customers as c' let leftJoin = ` INNER JOIN public.sent_mail_histories as m_h on c."id"::uuid = m_h."customer_id"::uuid LEFT JOIN public.customer_resources as c_r on c."customer_resource_id"::uuid = c_r."id"::uuid LEFT JOIN PUBLIC.templates on m_h.template_id = templates.id LEFT JOIN public.users on m_h."user_id"= users."id" ` let bindParam = [] let whereSql = ` WHERE c.customer_resource_id = '${customerResourceId}' AND c.id = '${customerId}' ` if (statusResponse) { bindParam.push(statusResponse) whereSql += ` AND m_h.status_feedback = $${bindParam.length} ` } if (startDate) { bindParam.push(startDate) whereSql += ` AND m_h.send_date >= $${bindParam.length} ` } if (endDate) { bindParam.push(endDate) whereSql += ` AND m_h.send_date <= $${bindParam.length} ` } let orderBy = ` ORDER BY m_h.send_date DESC ` let rawSql = selectSql + fromSql + leftJoin + whereSql + orderBy const result = await sequelize.query(rawSql, { bind: bindParam, type: QueryTypes.SELECT, }) const totalRecord = result.length const { totalPage, page, offset } = elementPaginate({ totalRecord: result.length, page: pageInput, limit: limitInput, }) const elements = await sequelize.query( rawSql + ` LIMIT ${limitInput} OFFSET ${offset}`, { bind: bindParam, type: QueryTypes.SELECT } ) const customerResourceData = { customerResource: elements?.map((item) => { return { ...item, id: create_UUID() } }), paginate: { totalRecord, totalPage, size: +limitInput, page: +page, }, } return this.result(200, true, Message.SUCCESS, customerResourceData) } catch (error) { throw { statusCode: error?.statusCode || 400, message: error?.message, } } } //lấy danh sách khách hàng + số lượng khách hàng được gửi mail async getCustomerOfResourceSent(req, res) { try { const sendDate = req.query.sendDate const pregnancyStatusSending = req.query.pregnancyStatusSending let bindParam = [] let bindParamCr = [] let selectSql = `SELECT r.id, r.name, COUNT(h.id) as total_customer ` let fromSql = ` FROM public.sent_mail_histories as h ` let leftJoin = ` join public.customers as c on h.customer_id = c.id join public.customer_resources as r on c.customer_resource_id = r.id ` let where = `where h.send_date = '${sendDate}' AND h.pregnancy_status_sending = ${pregnancyStatusSending}` let groupby = ' GROUP BY r.id' let rawSql = selectSql + fromSql + leftJoin + where + groupby const result = await sequelize.query(rawSql, { bind: bindParam, type: QueryTypes.SELECT, }) const selectCr = ` Select cr.id, cr.name from customer_resources as cr` const resultCr = await sequelize.query(selectCr, { bind: bindParamCr, type: QueryTypes.SELECT, }) const mergedResult = resultCr?.map((c) => { const r = result?.find((r) => r?.id === c?.id) if (r) { return { id: r?.id, name: r?.name, total_customer: r?.total_customer } } return { id: c.id, name: c.name } }) return this.result(200, true, Message.SUCCESS, mergedResult) } catch (error) { throw { statusCode: error?.statusCode || 400, message: error?.message, } } } //lấy danh sách khách hàng được import theo từng nguồn async getHistoryImportCustomer(req, res) { try { const limitInput = req.query.perPage const pageInput = req.query.currentPage const startDate = req.query.startDate ? DateUtils.convertStartDateToStringFullTime(req.query.startDate) : null const endDate = req.query.endDate ? DateUtils.convertEndDateToStringFullTime(req.query.endDate) : null const customerResourceId = req.query.customerResourceId const createdBy = req.query.createdBy let bindParam = [] let selectSql = `SELECT ich.id, ich.import_date, ich.customer_number, users.name as created_by` let fromSql = ` FROM public.import_customer_histories as ich ` let leftJoin = ` left join users on ich.created_by = users.username ` let where = `where ich.customer_resource_id = '${customerResourceId}' ` let groupby = ' GROUP BY ich.id, ich.import_date, ich.customer_number, users.name ' if (startDate) { bindParam.push(startDate) where += ` AND ich.import_date >= $${bindParam.length} ` } if (endDate) { bindParam.push(endDate) where += ` AND ich.import_date <= $${bindParam.length} ` } if (createdBy) { bindParam.push(createdBy) where += ` AND users.id = $${bindParam.length} ` } let rawSql = selectSql + fromSql + leftJoin + where + groupby const result = await sequelize.query(rawSql, { bind: bindParam, type: QueryTypes.SELECT, }) const totalRecord = result?.length if (!limitInput || !pageInput) { const elements = await sequelize.query(rawSql, { bind: bindParam, type: QueryTypes.SELECT, }) const customerResourceData = { customerResource: elements, } return this.result(200, true, Message.SUCCESS, customerResourceData) } const { totalPage, page, offset } = elementPaginate({ totalRecord: result?.length, page: pageInput, limit: limitInput, }) const elements = await sequelize.query( rawSql + ` LIMIT ${limitInput} OFFSET ${offset}`, { bind: bindParam, type: QueryTypes.SELECT } ) const customerResourceData = { customerResource: elements, paginate: { totalRecord, totalPage, size: +limitInput, page: +page, }, } return this.result(200, true, Message.SUCCESS, customerResourceData) } catch (error) { throw { statusCode: error?.statusCode || 400, message: error?.message, } } } //xem chi tiết khách hàng theo từng lần import async getDetailHistoryImportCustomer(req, res) { try { const importCustomerHistoriesId = req.query.importCustomerHistoriesId let bindParam = [] let selectSql = `SELECT dt.*, cr.name as customer_resource_name from detail_import_customer_histories as dt LEFT JOIN customer_resources as cr on cr.id = dt.customer_resource_id where import_customer_histories_id = '${importCustomerHistoriesId}'` const result = await sequelize.query(selectSql, { bind: bindParam, type: QueryTypes.SELECT, }) const customerResourceData = { customerResource: result, } return this.result(200, true, Message.SUCCESS, customerResourceData) } catch (error) { throw { statusCode: error?.statusCode || 400, message: error?.message, } } } } export default new CustomerResourceService()
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2008, 2009, 2010, 2011 CERN. ## ## Invenio 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. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """BibCirculation ..........""" __revision__ = "$Id$" # bibcirculation imports import invenio.bibcirculation_dblayer as db import invenio.template bibcirculation_templates = invenio.template.load('bibcirculation') # others invenio imports from invenio.config import \ CFG_SITE_LANG, \ CFG_CERN_SITE, \ CFG_SITE_SUPPORT_EMAIL from invenio.dateutils import get_datetext import datetime from invenio.webuser import collect_user_info from invenio.mailutils import send_email from invenio.bibcirculation_utils import hold_request_mail, \ book_title_from_MARC, \ make_copy_available, \ create_ill_record #book_information_from_MARC from invenio.bibcirculation_cern_ldap import get_user_info_from_ldap from invenio.bibcirculation_config import CFG_BIBCIRCULATION_LIBRARIAN_EMAIL def perform_loanshistoricaloverview(uid, ln=CFG_SITE_LANG): """ Display Loans historical overview for user uid. @param uid: user id @param ln: language of the page @return body(html) """ invenio_user_email = db.get_invenio_user_email(uid) is_borrower = db.is_borrower(invenio_user_email) result = db.get_historical_overview(is_borrower) body = bibcirculation_templates.tmpl_loanshistoricaloverview(result=result, ln=ln) return body def perform_borrower_loans(uid, barcode, borrower_id, request_id, ln=CFG_SITE_LANG): """ Display all the loans and the requests of a given borrower. @param barcode: identify the item. Primary key of crcITEM. @type barcode: string @param borrower_id: identify the borrower. Primary key of crcBORROWER. @type borrower_id: int @param request_id: identify the request: Primary key of crcLOANREQUEST @type request_id: int @return body(html) """ infos = [] is_borrower = db.is_borrower(db.get_invenio_user_email(uid)) loans = db.get_borrower_loans(is_borrower) requests = db.get_borrower_requests(is_borrower) tmp_date = datetime.date.today() + datetime.timedelta(days=30) new_due_date = get_datetext(tmp_date.year, tmp_date.month, tmp_date.day) #renew loan if barcode: recid = db.get_id_bibrec(barcode) queue = db.get_queue_request(recid) if len(queue) != 0: infos.append("It is not possible to renew your loan for " \ "<strong>" + book_title_from_MARC(recid) + "</strong>. Another user " \ "is waiting for this book.") else: db.update_due_date(barcode, new_due_date) infos.append("Your loan has been renewed with sucess.") #cancel request if request_id: db.cancel_request(request_id, 'cancelled') make_copy_available(request_id) #renew all loans elif borrower_id: list_of_recids = db.get_borrower_recids(borrower_id) for (recid) in list_of_recids: queue = db.get_queue_request(recid[0]) #check if there are requests if len(queue) != 0: infos.append("It is not possible to renew your loan for " \ "<strong>" + book_title_from_MARC(recid) + "</strong>. Another user" \ " is waiting for this book.") else: db.update_due_date_borrower(borrower_id, new_due_date) infos.append("All loans have been renewed with success.") body = bibcirculation_templates.tmpl_yourloans(loans=loans, requests=requests, borrower_id=is_borrower, infos=infos, ln=ln) return body def perform_get_holdings_information(recid, req, ln=CFG_SITE_LANG): """ Display all the copies of an item. @param recid: identify the record. Primary key of bibrec. @type recid: int @return body(html) """ holdings_information = db.get_holdings_information(recid) body = bibcirculation_templates.tmpl_holdings_information2(recid=recid, req=req, holdings_info=holdings_information, ln=ln) return body def perform_get_pending_request(ln=CFG_SITE_LANG): """ @param ln: language of the page """ status = db.get_loan_request_by_status("pending") body = bibcirculation_templates.tmpl_get_pending_request(status=status, ln=ln) return body def perform_new_request(recid, barcode, ln=CFG_SITE_LANG): """ Display form to be filled by the user. @param uid: user id @type: int @param recid: identify the record. Primary key of bibrec. @type recid: int @param barcode: identify the item. Primary key of crcITEM. @type barcode: string @return request form """ body = bibcirculation_templates.tmpl_new_request2(recid=recid, barcode=barcode, ln=ln) return body def perform_new_request_send(uid, recid, period_from, period_to, barcode, ln=CFG_SITE_LANG): """ @param recid: recID - Invenio record identifier @param ln: language of the page """ nb_requests = db.get_number_requests_per_copy(barcode) is_on_loan = db.is_item_on_loan(barcode) if nb_requests == 0 and is_on_loan is not None: status = 'waiting' elif nb_requests == 0 and is_on_loan is None: status = 'pending' else: status = 'waiting' user = collect_user_info(uid) is_borrower = db.is_borrower(user['email']) if is_borrower != 0: address = db.get_borrower_address(user['email']) if address != 0: db.new_hold_request(is_borrower, recid, barcode, period_from, period_to, status) is_on_loan=db.is_item_on_loan(barcode) db.update_item_status('requested', barcode) if not is_on_loan: send_email(fromaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, toaddr=CFG_SITE_SUPPORT_EMAIL, subject='Hold request for books confirmation', content=hold_request_mail(recid, is_borrower), attempt_times=1, attempt_sleeptime=10 ) if CFG_CERN_SITE == 1: message = bibcirculation_templates.tmpl_message_request_send_ok_cern() else: message = bibcirculation_templates.tmpl_message_request_send_ok_other() else: if CFG_CERN_SITE == 1: email=user['email'] result = get_user_info_from_ldap(email) try: ldap_address = result['physicalDeliveryOfficeName'][0] except KeyError: ldap_address = None if ldap_address is not None: db.add_borrower_address(ldap_address, email) db.new_hold_request(is_borrower, recid, barcode, period_from, period_to, status) db.update_item_status('requested', barcode) send_email(fromaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, toaddr=CFG_SITE_SUPPORT_EMAIL, subject='Hold request for books confirmation', content=hold_request_mail(recid, is_borrower), attempt_times=1, attempt_sleeptime=10 ) message = bibcirculation_templates.tmpl_message_request_send_ok_cern(ln=ln) else: message = bibcirculation_templates.tmpl_message_request_send_fail_cern(ln=ln) else: message = bibcirculation_templates.tmpl_message_request_send_fail_other(ln=ln) else: if CFG_CERN_SITE == 1: result = get_user_info_from_ldap(email=user['email']) try: name = result['cn'][0] except KeyError: name = None try: email = result['mail'][0] except KeyError: email = None try: phone = result['telephoneNumber'][0] except KeyError: phone = None try: address = result['physicalDeliveryOfficeName'][0] except KeyError: address = None try: mailbox = result['postOfficeBox'][0] except KeyError: mailbox = None if address is not None: db.new_borrower(name, email, phone, address, mailbox, '') is_borrower = db.is_borrower(email) db.new_hold_request(is_borrower, recid, barcode, period_from, period_to, status) db.update_item_status('requested', barcode) send_email(fromaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, toaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, subject='Hold request for books confirmation', content=hold_request_mail(recid, is_borrower), attempt_times=1, attempt_sleeptime=10 ) message = bibcirculation_templates.tmpl_message_request_send_ok_cern() else: message = bibcirculation_templates.tmpl_message_request_send_fail_cern() else: message = bibcirculation_templates.tmpl_message_request_send_ok_other() body = bibcirculation_templates.tmpl_new_request_send(message=message, ln=ln) return body def ill_request_with_recid(recid, ln=CFG_SITE_LANG): """ Display ILL form. @param recid: identify the record. Primary key of bibrec. @type recid: int @param uid: user id @type: int """ body = bibcirculation_templates.tmpl_ill_request_with_recid(recid=recid, infos=[], ln=ln) return body #(title, year, authors, isbn, publisher) = book_information_from_MARC(int(recid)) #book_info = {'title': title, 'authors': authors, 'place': place, 'publisher': publisher, # 'year' : year, 'edition': edition, 'isbn' : isbn} def ill_register_request_with_recid(recid, uid, period_of_interest_from, period_of_interest_to, additional_comments, conditions, only_edition, ln=CFG_SITE_LANG): """ Register a new ILL request. @param recid: identify the record. Primary key of bibrec. @type recid: int @param uid: user id @type: int @param period_of_interest_from: period of interest - from(date) @type period_of_interest_from: string @param period_of_interest_to: period of interest - to(date) @type period_of_interest_to: string """ # create a dictionnary book_info = {'recid': recid} user = collect_user_info(uid) is_borrower = db.is_borrower(user['email']) if is_borrower == 0: if CFG_CERN_SITE == 1: result = get_user_info_from_ldap(email=user['email']) try: name = result['cn'][0] except KeyError: name = None try: email = result['mail'][0] except KeyError: email = None try: phone = result['telephoneNumber'][0] except KeyError: phone = None try: address = result['physicalDeliveryOfficeName'][0] except KeyError: address = None try: mailbox = result['postOfficeBox'][0] except KeyError: mailbox = None if address is not None: db.new_borrower(name, email, phone, address, mailbox, '') else: message = bibcirculation_templates.tmpl_message_request_send_fail_cern() else: message = bibcirculation_templates.tmpl_message_request_send_fail_other() return bibcirculation_templates.tmpl_ill_register_request_with_recid(message=message, ln=ln) address = db.get_borrower_address(user['email']) if address == 0: if CFG_CERN_SITE == 1: email=user['email'] result = get_user_info_from_ldap(email) try: address = result['physicalDeliveryOfficeName'][0] except KeyError: address = None if address is not None: db.add_borrower_address(address, email) else: message = bibcirculation_templates.tmpl_message_request_send_fail_cern() else: message = bibcirculation_templates.tmpl_message_request_send_fail_other() return bibcirculation_templates.tmpl_ill_register_request_with_recid(message=message, ln=ln) if not conditions: infos = [] infos.append("You didn't accept the ILL conditions.") return bibcirculation_templates.tmpl_ill_request_with_recid(recid, infos=infos, ln=ln) else: db.ill_register_request(book_info, is_borrower, period_of_interest_from, period_of_interest_to, 'new', additional_comments, only_edition or 'False','book') if CFG_CERN_SITE == 1: message = bibcirculation_templates.tmpl_message_request_send_ok_cern() else: message = bibcirculation_templates.tmpl_message_request_send_ok_other() #Notify librarian about new ILL request. send_email(fromaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, toaddr="[email protected]", subject='ILL request for books confirmation', content=hold_request_mail(recid, is_borrower), attempt_times=1, attempt_sleeptime=10) return bibcirculation_templates.tmpl_ill_register_request_with_recid(message=message, ln=ln) def display_ill_form(ln=CFG_SITE_LANG): """ Display ILL form @param uid: user id @type: int """ body = bibcirculation_templates.tmpl_display_ill_form(infos=[], ln=ln) return body def ill_register_request(uid, title, authors, place, publisher, year, edition, isbn, period_of_interest_from, period_of_interest_to, additional_comments, conditions, only_edition, request_type, ln=CFG_SITE_LANG): """ Register new ILL request. Create new record (collection: ILL Books) @param uid: user id @type: int @param authors: book's authors @type authors: string @param place: place of publication @type place: string @param publisher: book's publisher @type publisher: string @param year: year of publication @type year: string @param edition: book's edition @type edition: string @param isbn: book's isbn @type isbn: string @param period_of_interest_from: period of interest - from(date) @type period_of_interest_from: string @param period_of_interest_to: period of interest - to(date) @type period_of_interest_to: string @param additional_comments: comments given by the user @type additional_comments: string @param conditions: ILL conditions @type conditions: boolean @param only_edition: borrower wants only the given edition @type only_edition: boolean """ item_info = (title, authors, place, publisher, year, edition, isbn) create_ill_record(item_info) book_info = {'title': title, 'authors': authors, 'place': place, 'publisher': publisher, 'year': year, 'edition': edition, 'isbn': isbn} user = collect_user_info(uid) is_borrower = db.is_borrower(user['email']) #Check if borrower is on DB. if is_borrower != 0: address = db.get_borrower_address(user['email']) #Check if borrower has an address. if address != 0: #Check if borrower has accepted ILL conditions. if conditions: #Register ILL request on crcILLREQUEST. db.ill_register_request(book_info, is_borrower, period_of_interest_from, period_of_interest_to, 'new', additional_comments, only_edition or 'False', request_type) #Display confirmation message. message = "Your ILL request has been registered and the " \ "document will be sent to you via internal mail." #Notify librarian about new ILL request. send_email(fromaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, toaddr=CFG_SITE_SUPPORT_EMAIL, subject='ILL request for books confirmation', content="", attempt_times=1, attempt_sleeptime=10 ) #Borrower did not accept ILL conditions. else: infos = [] infos.append("You didn't accept the ILL conditions.") body = bibcirculation_templates.tmpl_display_ill_form(infos=infos, ln=ln) #Borrower doesn't have an address. else: #If BibCirculation at CERN, use LDAP. if CFG_CERN_SITE == 1: email=user['email'] result = get_user_info_from_ldap(email) try: ldap_address = result['physicalDeliveryOfficeName'][0] except KeyError: ldap_address = None # verify address if ldap_address is not None: db.add_borrower_address(ldap_address, email) db.ill_register_request(book_info, is_borrower, period_of_interest_from, period_of_interest_to, 'new', additional_comments, only_edition or 'False', request_type) message = "Your ILL request has been registered and the document"\ " will be sent to you via internal mail." send_email(fromaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, toaddr=CFG_SITE_SUPPORT_EMAIL, subject='ILL request for books confirmation', content="", attempt_times=1, attempt_sleeptime=10 ) else: message = "It is not possible to validate your request. "\ "Your office address is not available. "\ "Please contact ... " else: # Get information from CERN LDAP if CFG_CERN_SITE == 1: result = get_user_info_from_ldap(email=user['email']) try: name = result['cn'][0] except KeyError: name = None try: email = result['mail'][0] except KeyError: email = None try: phone = result['telephoneNumber'][0] except KeyError: phone = None try: address = result['physicalDeliveryOfficeName'][0] except KeyError: address = None try: mailbox = result['postOfficeBox'][0] except KeyError: mailbox = None # verify address if address is not None: db.new_borrower(name, email, phone, address, mailbox, '') is_borrower = db.is_borrower(email) db.ill_register_request(book_info, is_borrower, period_of_interest_from, period_of_interest_to, 'new', additional_comments, only_edition or 'False', request_type) message = "Your ILL request has been registered and the document"\ " will be sent to you via internal mail." send_email(fromaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, toaddr=CFG_SITE_SUPPORT_EMAIL, subject='ILL request for books confirmation', content="", attempt_times=1, attempt_sleeptime=10 ) else: message = "It is not possible to validate your request. "\ "Your office address is not available."\ " Please contact ... " body = bibcirculation_templates.tmpl_ill_register_request_with_recid(message=message, ln=ln) return body
#![allow(dead_code)] use std::{ iter::once, ops::{Deref, DerefMut}, }; use bytes::{BufMut, BytesMut}; pub struct Message(BytesMut); impl Message { pub fn new() -> Self { Self(BytesMut::zeroed(12)) } pub fn from(data: &[u8]) -> Self { Self(BytesMut::from(data)) } pub fn id(&self) -> u16 { u16::from_be_bytes([self[0], self[1]]) } pub fn set_id(&mut self, id: u16) { self[..2].copy_from_slice(&id.to_be_bytes()); } pub fn set_query(&mut self) { self[2] &= 0b0111_1111; } pub fn set_response(&mut self) { self[2] |= 0b1000_0000; } pub fn opcode(&self) -> u8 { self[2] << 1 >> 4 } pub fn rd(&self) -> u8 { self[2] & 0b0000_0001 } pub fn rcode(&self) -> u8 { self[3] & 0b0000_1111 } pub fn set_rcode(&mut self, rcode: u8) { self[3] = (self[3] & 0b1111_0000) | (0b0000_1111 & rcode) } pub fn add_question(&mut self, name: &str, record_type: u16, class: u16) { self.unsplit(encode_domain(name)); self.put_u16(record_type); self.put_u16(class); let question_count = u16::from_be_bytes([self[4], self[5]]) + 1; self[4..6].copy_from_slice(&question_count.to_be_bytes()); } pub fn add_answer(&mut self, name: &str, record_type: u16, class: u16, ttl: u32, data: u32) { self.unsplit(encode_domain(name)); self.put_u16(record_type); self.put_u16(class); self.put_u32(ttl); self.put_u16(4u16); self.put_u32(data); let answer_count = u16::from_be_bytes([self[6], self[7]]) + 1; self[6..8].copy_from_slice(&answer_count.to_be_bytes()); } } impl Deref for Message { type Target = BytesMut; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Message { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } pub fn encode_domain(name: &str) -> BytesMut { name.split('.').flat_map(|label| once(label.len() as u8).chain(label.bytes())).chain(once(0u8)).collect() }
/** @page test-introduction Introduction to tests @tableofcontents @section overview Overview A test has several important attributes, and are often referred to in the form: test-$ENVIRONMENT-$NAME[~$VARIATION] This identifies a single test instance, with the purpose of executing and providing a single result (See @ref running). @subsection attr-name Name A tests name is a unique identifier. The directory `tests/$NAME/` contains all files related to a specific test. A test has one or more test instances. @subsection attr-category Category A tests category is a broad delineation of its purpose. All defined categories are: @dontinclude build/common.mk @skipline ALL_CATEGORIES - `xsa` are dedicated tests to confirm the presence or absence of a specific security vulnerability. - `functional` are tests covering a specific area of functionality. - `utility` are not really tests, but exist to dump specific information about the VM environment. - `special` covers the example and environment sanity checks. - `in-development` covers tests which aren't yet complete, and are not ready to be run automatically yet. @subsection attr-envs Environments A test is built for one or more environments. The environment encodes: - The Xen VM ABI in use (PV or HVM). - The compilation width (32bit or 64bit). - The primary paging mode (none, PSE, PAE). All available environments are: @skipline ALL_ENVIRONMENTS Some more specific collections for environments are also available: @skipline PV_ENVIRONMENTS @until 64BIT_ENVIRONMENTS An individual test, compiled for more than one environment, will end up with a individual microkernel binary for each specified environment. @subsection Variations Variations are optional. Some tests may only want to run the binary once, but some tests want to run the same binary multiple times in different configurations, reporting separate results. The variation suffix (if present) is arbitrary and defined by the test itself. @section build Building @subsection build-create Creating a new test A helper script is provided to create the initial boilerplate. It prompts for some information, and writes out some default files: $ ./make-new-test.sh Test name: example Category [utility]: special Environments [hvm32]: $(ALL_ENVIRONMENTS) Extra xl.cfg? [y/N]: n Writing default tests/example/Makefile Writing default tests/example/main.c $ @subsection build-main Minimal main.c @dontinclude tests/example/main.c The minimum for main.c is to include the framework: @skipline <xtf.h> Choose a suitable title: @skipline const char test_title Implement test_main(): @skipline main( @line { And make a call to xtf_success() somewhere before test_main() returns: @skipline xtf_success @line } @subsection build-build Building Building this will generate a number of files. $ make -j4 ... <snip> $ ls tests/example/ info.json main.c main-hvm32.d main-hvm32.o main-hvm32pae.d main-hvm32pae.o main-hvm32pse.d main-hvm32pse.o main-hvm64.d main-hvm64.o main-pv32pae.d main-pv32pae.o main-pv64.d main-pv64.o Makefile test-hvm32-example test-hvm32-example.cfg test-hvm32pae-example test-hvm32pae-example.cfg test-hvm32pse-example test-hvm32pse-example.cfg test-hvm64-example test-hvm64-example.cfg test-pv32pae-example test-pv32pae-example.cfg test-pv64-example test-pv64-example.cfg The `.o` and `.d` files are build artefacts, leading to the eventual `test-$ENV-$NAME` microkernel. Individual `xl.cfg` files are generated for each microkernel. `info.json` contains metadata about the test. @section install Installing If XTF in being built in dom0, all paths should be set up to run correctly. # xl create tests/example/test-hvm64-example.cfg If XTF is built elsewhere, it should be installed: $ make install xtfdir=/path DESTDIR=/path with paths appropriate for the system under test. @section running Running A test will by default write synchronously to all available consoles: # ./xtf-runner test-hvm64-example Executing 'xl create -p tests/example/test-hvm64-example.cfg' Parsing config from tests/example/test-hvm64-example.cfg Executing 'xl console test-hvm64-example' Executing 'xl unpause test-hvm64-example' --- Xen Test Framework --- Environment: HVM 64bit (Long mode 4 levels) Hello World Test result: SUCCESS Combined test results: test-hvm64-example SUCCESS The result is covered by the report.h API. In short, the options are: - Success - The test passed. - Skip - The test cannot be completed for configuration reasons. - Error - An error in the environment or test code itself. - Failure - An issue with the functional area under test. */
<script type="text/javascript"> // eslint-disable-next-line func-names (function () { function validPin(tmppin) { const tmpPin = parseInt(tmppin, 10); if (Number.isInteger(tmpPin) && tmpPin >= 0 && tmpPin <= 255) { return true; } return false; } function onEditSave() { if ($('#node-input-pinmode').val() == 1) { // eslint-disable-line eqeqeq if (!validPin($('#node-input-pin').val())) { $('#node-input-pin').val('0'); } } } function oneditprepare() { $('#node-input-pinmode').on('change', function onChangePinmode() { if ($(this).val() == 0) { // eslint-disable-line eqeqeq $('#div-write-pin').show(); } else { $('#div-write-pin').hide(); } }).change(); } function label() { let pin = 'pin error'; const type = 'Write'; const dynamic = (this.pinmode == 1); // eslint-disable-line eqeqeq if (validPin(this.pin)) { pin = `Pin V${this.pin} - ${type}`; } if (dynamic) { pin = `Pin Dynamic - ${type}`; } return this.name || pin; } RED.nodes.registerType('blynk-iot-out-write', { category: 'Blynk IoT', paletteLabel: 'write', defaults: { name: { value: '' }, pin: { value: '', required: false, validate: RED.validators.regex(/^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/) }, pinmode: { value: 0 }, client: { type: 'blynk-iot-client', required: true }, }, color: '#8be8c8', inputs: 1, outputs: 0, icon: 'white-globe.png', align: 'right', labelStyle() { return this.name ? 'node_label_italic' : ''; }, label, oneditsave: onEditSave, oneditprepare, }); }()); </script> <!-- Blynk out Node - Write --> <script type="text/x-red" data-template-name="blynk-iot-out-write"> <div class="form-row" id="client-row"> <label for="node-input-client"><i class="fa fa-bookmark"></i> <span>Connection</span></label> <input type="text" id="node-input-client"> </div> <div class="form-row"> <label for="node-input-pinmode"><i class="fa fa-cogs"></i> <span>Pin Mode</span></label> <select id="node-input-pinmode" style="width:70%"> <option value="0">Fixed</option> <option value="1">Dynamic</option> </select> </div> <div class="form-row" id="div-write-pin"> <label for="node-input-pin"><i class="fa fa-dot-circle-o"></i> <span>Virtual Pin</span></label> <input type="number" id="node-input-pin" min="0" max="255" placeholder="pin"> </div> <div class="form-row"> <label for="node-input-name"><i class="fa fa-tag"></i> <span>Name</span></label> <input type="text" id="node-input-name" data-i18n="[placeholder]node-red:common.label.name"> </div> </script> <script type="text/x-red" data-help-name="blynk-iot-out-write"> <p>Blynk write node.</p> <p>This node will write the value in <code>msg.payload</code> to the specified pin number.</p><br> <p>"Pin mode" selects whether the pin number is fixed or dynamic<br> &nbsp;&nbsp; Fixed, select the pin number in the interface<br> &nbsp;&nbsp; Dynamic, the pin number is passed through <code> msg.pin</code> property</p> <p class="form-tips"> Official documentation: <a href="https://docs.blynk.io/en/blynk.edgent-firmware-api/virtual-pins#blynk.virtualwrite-vpin-value">Virtual Pins - Write data</a> <p> </script>
import { useContext, useState, useEffect } from 'react'; import PopupWithForm from './PopupWithForm'; import { CurrentUserContext } from '../contexts/CurrentUserContext'; function EditProfilePopup({ isOpen, onClose, onUpdateUser }) { const currentUser = useContext(CurrentUserContext); const [name, setName] = useState(''); const [description, setDescription] = useState(''); const handleNameChange = (evt) => { setName(evt.target.value); }; const handleDescriptionChange = (evt) => { setDescription(evt.target.value); }; const handleSubmit = (evt) => { evt.preventDefault(); onUpdateUser({ name, about: description, }); }; useEffect(() => { setName(currentUser.name || ''); setDescription(currentUser.about || ''); }, [currentUser, isOpen]); return ( <PopupWithForm name="profile" title="Редактировать профиль" buttonText="Сохранить" isOpen={isOpen} onClose={onClose} onSubmit={handleSubmit} > <fieldset className="form__set"> <label className="form__field"> <input type="text" placeholder="Ваше имя" className="form__input form__input_profile-name" id="edit-name" name="name" minLength="2" maxLength="40" value={name} onChange={handleNameChange} required /> <span className="form__input-error edit-name-error"></span> </label> <label className="form__field"> <input type="text" placeholder="Чем занимаетесь?" className="form__input form__input_profile-job" id="edit-job" name="job" minLength="2" maxLength="200" value={description} onChange={handleDescriptionChange} required /> <span className="form__input-error edit-job-error"></span> </label> </fieldset> </PopupWithForm> ); } export default EditProfilePopup;
"""Модуль предоставляет класс-одиночку `Save` для работы с файлом 'assets/save.json'.""" from enum import StrEnum from pathlib import Path from game.contrib.singleton_ import SingletonMeta from game.contrib.dict_ import alias from game.contrib.files import save_json, load_json from game.config import GameConfig __all__ = ( 'Save', 'save', ) class Save(dict, metaclass=SingletonMeta): FILE_PATH: Path = GameConfig.ASSETS_PATH.joinpath('save.json') class Key(StrEnum): COINS_COUNT = 'coins_count' def __init__(self) -> None: super().__init__(load_json(self.FILE_PATH)) def __setitem__(self, key, value) -> None: super().__setitem__(key, value) self.save() def save(self) -> None: save_json(self.FILE_PATH, self) coins_count: int = alias(Key.COINS_COUNT) save: Save = Save() if __name__ == '__main__': print(save) save.coins_count += 5
import { memo } from 'react'; import { useOnPressEnter } from '../../../hooks'; import Input from '../../ui/Input'; import Button from '../../ui/Button'; import styles from './InputSearch.module.scss'; type InputSearchProps = { onChange: () => void; value: string; textButton?: string; withOnEnter?: boolean; isLoading?: boolean; onClick?: () => void; placeholder?: string; }; const InputSearch = ({ onClick = () => {}, textButton = 'Search', isLoading = false, withOnEnter = true, placeholder = 'Search', ...rest }: InputSearchProps) => { const onEnterHandler = withOnEnter && onClick ? onClick : () => {}; const onPressEnter = useOnPressEnter(onEnterHandler); return ( <div className={styles.inputContainer}> <Input name="search" placeholder={placeholder} classNameContainer={styles.input} onKeyPress={onPressEnter} {...rest} /> <Button className={styles.button} isLoading={isLoading} onClick={onClick}> {textButton} </Button> </div> ); }; export default memo(InputSearch);
package com.example.tinycalculator import android.Manifest import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import com.example.tinycalculator.ui.theme.TinyCalculatorTheme class MainActivity : ComponentActivity() { private val activityResultLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions()) { permissions -> // Handle Permission granted/rejected var permissionGranted = true permissions.entries.forEach { if (it.key in REQUIRED_PERMISSIONS && !it.value) permissionGranted = false } if (!permissionGranted) { Toast.makeText(baseContext, "Permission request denied", Toast.LENGTH_SHORT).show() } else { Toast.makeText(baseContext, "Permission request accepted", Toast.LENGTH_SHORT).show() } } override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) if (allPermissionsGranted()) { setScreen() } else { requestPermissions() } } private fun setScreen(){ Log.d("Log","MainActivity: SetScreen") setContent { TinyCalculatorTheme { // A surface container using the 'background' color from the theme TinyCalculatorApp() } } } private fun requestPermissions() { activityResultLauncher.launch(REQUIRED_PERMISSIONS) } private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission( baseContext, it) == PackageManager.PERMISSION_GRANTED } companion object { private val REQUIRED_PERMISSIONS = mutableListOf ( Manifest.permission.CAMERA).apply { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { add(Manifest.permission.WRITE_EXTERNAL_STORAGE) } if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2){ add(Manifest.permission.READ_EXTERNAL_STORAGE) } }.toTypedArray() } }
import { createContext, useState } from 'react'; import PropTypes from 'prop-types'; import { Products } from '@/data/products'; import { Shops } from '@/data/shops'; // Creamos el contexto export const CartContext = createContext(); // Proveedor del contexto export const CartProvider = ({children}) => { const [cartItems, setCartItems] = useState([]); const [productItems] = useState(Products.productItems); const [shopItems] = useState(Shops.shopItems); // Funciones para manejar el carrito de compras const addToCart = (product) => { // Lógica para agregar un producto al carrito setCartItems([...cartItems, product]); }; const removeFromCart = (productId) => { // Lógica para eliminar un producto del carrito setCartItems(cartItems.filter(item => item.id !== productId)); }; // valor proporcionado por el proveedor const value = { cartItems, addToCart, productItems, shopItems, removeFromCart, }; return <CartContext.Provider value={value}>{children}</CartContext.Provider>; }; //Validación de tipo para children CartProvider.propTypes = { children: PropTypes.node.isRequired, };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>1.props基本使用</title> </head> <body> <div id="person1"></div> <div id="person2"></div> <div id="person3"></div> <script type="text/javascript" src="../js/react.development.js"></script> <script type="text/javascript" src="../js/react-dom.development.js" ></script> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel"> //創建組件 class Person extends React.Component { render() { const { name, age, sex } = this.props; return ( <ul> <li>姓名:{name}</li> <li>年齡:{age}</li> <li>性別:{sex}</li> </ul> ); } } // 渲染組件到頁面 ReactDOM.render( <Person name="mike" age="20" sex="男" />, document.getElementById("person1") ); ReactDOM.render( <Person name="nancy" age="30" sex="女" />, document.getElementById("person2") ); const p = { name: "geroge", age: 25, sex: "男", }; // ReactDOM.render( // <Person name={p.name} age={p.age} sex={p.sex} />, // document.getElementById("person3") // ); ReactDOM.render(<Person {...p} />, document.getElementById("person3")); </script> </body> </html>
import platform import sys import time import torch import shutil # 对文件的一些操作 import core.globals import glob import argparse import multiprocessing as mp import os from pathlib import Path # 和路径有关 import tkinter as tk # 窗口GUI设计 from tkinter import filedialog from tkinter.filedialog import asksaveasfilename from core.processor import process_video, process_img from core.utils import is_img, detect_fps, set_fps, create_video, add_audio, extract_frames, rreplace from core.config import get_face import webbrowser import psutil import cv2 import threading from PIL import Image, ImageTk pool = None # 用来设置进程池 args = {} parser = argparse.ArgumentParser() parser.add_argument('-f', '--face', help='use this face', dest='source_img') parser.add_argument('-t', '--target', help='replace this face', dest='target_path') parser.add_argument('-o', '--output', help='save output to this file', dest='output_file') parser.add_argument('--gpu', help='use gpu', dest='gpu', action='store_true', default=False) parser.add_argument('--keep-fps', help='maintain original fps', dest='keep_fps', action='store_true', default=False) parser.add_argument('--keep-frames', help='keep frames directory', dest='keep_frames', action='store_true', default=False) parser.add_argument('--max-memory', help='set max memory', default=4, type=int) parser.add_argument('--max-cores', help='number of cores to use', dest='cores_count', type=int, default=max(psutil.cpu_count() - 2, 2)) for name, value in vars(parser.parse_args()).items(): args[name] = value sep = "/" # 判断目前正在使用的平台 Windows 返回 'nt' Linux/mac 返回'posix' if os.name == "nt": sep = "\\" # 内存配置 def limit_resources(): if args['max_memory'] >= 1: memory = args['max_memory'] * 1024 * 1024 * 1024 if str(platform.system()).lower() == 'windows': # 判断是否为windows操作系统 import ctypes kernel32 = ctypes.windll.kernel32 kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory)) else: # 其他操作系统 import resource resource.setrlimit(resource.RLIMIT_DATA, (memory, memory)) # 程序运行前的一些环境检查 def pre_check(): # python需要>=3.8 # if sys.version_info < (3, 8): # quit(f'Python version is not supported - please upgrade to 3.8 or higher') # 判断ffmpeg是否安装 if not shutil.which('ffmpeg'): quit('ffmpeg is not installed!') # 预权重路径 model_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'inswapper_128.onnx') # 判断权重是否存在 if not os.path.isfile(model_path): quit('File "inswapper_128.onnx" does not exist!') # 是否使用GPU if '--gpu' in sys.argv: print(sys.argv) CUDA_VERSION = torch.version.cuda # 获取cuda版本 CUDNN_VERSION = torch.backends.cudnn.version() # cudnn版本 NVIDIA_PROVIDERS = ['CUDAExecutionProvider', 'TensorrtExecutionProvider'] if len(list(set(core.globals.providers) - set(NVIDIA_PROVIDERS))) > 1: # 判断是否支持gpu if not torch.cuda.is_available() or not CUDA_VERSION: quit("You are using --gpu flag but CUDA isn't available or properly installed on your system.") # cuda要求 11.4≤ cuda ≤11.8 # if CUDA_VERSION > '11.8': # quit(f"CUDA version {CUDA_VERSION} is not supported - please downgrade to 11.8.") # if CUDA_VERSION < '11.4': # quit(f"CUDA version {CUDA_VERSION} is not supported - please upgrade to 11.8") # # cudnn要求 8.2.2≤ cuda ≤ 8.9.1 # if CUDNN_VERSION < 8220: # quit(f"CUDNN version {CUDNN_VERSION} is not supported - please upgrade to 8.9.1") # if CUDNN_VERSION > 8910: # quit(f"CUDNN version {CUDNN_VERSION} is not supported - please downgrade to 8.9.1") core.globals.providers = ['CUDAExecutionProvider'] # cpu运行 else: core.globals.providers = ['CPUExecutionProvider'] # 开始进程 视频人脸交换 def start_processing(): # 记录进程启动时间 start_time = time.time() # 当为gpu运行时 if args['gpu']: print('gpu 推理') # source_img:图像路径,frame_paths:图像序列路径。 # frame_paths是目标人脸,将source_img替换到frame_paths人脸 process_video(args['source_img'], args["frame_paths"]) # 记录结束时间 end_time = time.time() print(flush=True) # 打印人脸检测进程运行时间 print(f"Processing time: {end_time - start_time:.2f} seconds", flush=True) return # 获取图像序列路径 frame_paths = args["frame_paths"] n = len(frame_paths)//(args['cores_count']) processes = [] for i in range(0, len(frame_paths), n): # pool.apply_async异步非阻塞 不用等待当前进程执行完毕,随时根据系统调度来进行进程切换 p = pool.apply_async(process_video, args=(args['source_img'], frame_paths[i:i+n],)) processes.append(p) for p in processes: p.get() # 进程关闭 pool.close() # 加入主进程 pool.join() end_time = time.time() print(flush=True) print(f"Processing time: {end_time - start_time:.2f} seconds", flush=True) # 图像的预处理 def preview_image(image_path): img = Image.open(image_path) # 图像大小的resize img = img.resize((180, 180), Image.ANTIALIAS) photo_img = ImageTk.PhotoImage(img) # GUI显示 left_frame = tk.Frame(window) left_frame.place(x=60, y=100) img_label = tk.Label(left_frame, image=photo_img) img_label.image = photo_img img_label.pack() # 视频的预处理 def preview_video(video_path): cap = cv2.VideoCapture(video_path) if not cap.isOpened(): print("Error opening video file") return ret, frame = cap.read() if ret: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # opencv2PIL img = Image.fromarray(frame) img = img.resize((180, 180), Image.ANTIALIAS) # 仅需读取一帧并在GUI上显示即可 photo_img = ImageTk.PhotoImage(img) right_frame = tk.Frame(window) right_frame.place(x=360, y=100) img_label = tk.Label(right_frame, image=photo_img) img_label.image = photo_img img_label.pack() cap.release() # 选择source人脸 def select_face(): args['source_img'] = filedialog.askopenfilename(title="Select a face") # 选择打开什么文件,返回的是文件名 # 对source人脸图像进行预处理 preview_image(args['source_img']) # 选择target人脸 def select_target(): args['target_path'] = filedialog.askopenfilename(title="Select a target") # 获得target人脸文件名 # 对视频进行预处理并开启线程 threading.Thread(target=preview_video, args=(args['target_path'],)).start() # 保持FPS def toggle_fps_limit(): args['keep_fps'] = limit_fps.get() != True # 保持frames def toggle_keep_frames(): args['keep_frames'] = keep_frames.get() != True # 保存文件 def save_file(): filename, ext = 'output.mp4', '.mp4' # 判断目标文件名是否为图片,"png", "jpg", "jpeg", "bmp",否则保存为视频格式 if is_img(args['target_path']): # 如果是图片则保存为图片格式 filename, ext = 'output.png', '.png' args['output_file'] = asksaveasfilename(initialfile=filename, defaultextension=ext, filetypes=[("All Files","*.*"),("Videos","*.mp4")]) def status(string): if 'cli_mode' in args: print("Status: " + string) else: status_label["text"] = "Status: " + string window.update() def start(): print("DON'T WORRY. IT'S NOT STUCK/CRASHED.\n" * 5) # 这并不是卡住了,而是在等待! # 判断输入图像路径是否正确 if not args['source_img'] or not os.path.isfile(args['source_img']): print("\n[WARNING] Please select an image containing a face.") return # # 判断输入图像路径是否正确 elif not args['target_path'] or not os.path.isfile(args['target_path']): print("\n[WARNING] Please select a video/image to swap face in.") return if not args['output_file']: args['output_file'] = rreplace(args['target_path'], "/", "/swapped-", 1) if "/" in target_path else "swapped-"+target_path global pool # 进程池 pool = mp.Pool(args['cores_count']) target_path = args['target_path'] # 人脸检测 test_face = get_face(cv2.imread(args['source_img'])) if not test_face: # 如果没有检测到人脸 print("\n[WARNING] No face detected in source image. Please try with another one.\n") return # 判断是否为图像,"png", "jpg", "jpeg", "bmp" if is_img(target_path): # 人脸交换 process_img(args['source_img'], target_path, args['output_file']) status("swap successful!") return # 视频 video_name = os.path.basename(target_path) # 读取视频名字,xx.mp4,eg:test.mp4 video_name = os.path.splitext(video_name)[0] # 去除后缀 eg:test output_dir = os.path.join(os.path.dirname(target_path), video_name) # 输出路径 Path(output_dir).mkdir(exist_ok=True) status("detecting video's FPS...") fps = detect_fps(target_path) # 检测帧率 # 如果keep_fps=False,并且 fps>30,则进行FPS处理 if not args['keep_fps'] and fps > 30: this_path = output_dir + "/" + video_name + ".mp4" set_fps(target_path, this_path, 30) target_path, fps = this_path, 30 # 获取视频路径和帧率 else: shutil.copy(target_path, output_dir) status("extracting frames...") # extract_frames(target_path, output_dir) args['frame_paths'] = tuple(sorted( glob.glob(output_dir + f"/*.png"), key=lambda x: int(x.split(sep)[-1].replace(".png", "")) )) status("swapping in progress...") start_processing() status("creating video...") create_video(video_name, fps, output_dir) status("adding audio...") add_audio(output_dir, target_path, args['keep_frames'], args['output_file']) save_path = args['output_file'] if args['output_file'] else output_dir + "/" + video_name + ".mp4" print("\n\nVideo saved as:", save_path, "\n\n") status("swap successful!") if __name__ == "__main__": global status_label, window # 预权重,python环境的检查 pre_check() # 内存检测 limit_resources() # 状态触发 if args['source_img']: args['cli_mode'] = True start() quit() # UI设置 window = tk.Tk() window.geometry("600x700") window.title("roop") window.configure(bg="#2d3436") window.resizable(width=False, height=False) # Contact information support_link = tk.Label(window, text="Donate to project <3", fg="#fd79a8", bg="#2d3436", cursor="hand2", font=("Arial", 8)) support_link.place(x=180,y=20,width=250,height=30) support_link.bind("<Button-1>", lambda e: webbrowser.open("https://github.com/sponsors/s0md3v")) # Select a face button face_button = tk.Button(window, text="Select a face", command=select_face, bg="#2d3436", fg="#74b9ff", highlightthickness=4, relief="flat", highlightbackground="#74b9ff", activebackground="#74b9ff", borderwidth=4) face_button.place(x=60,y=320,width=180,height=80) # Select a target button target_button = tk.Button(window, text="Select a target", command=select_target, bg="#2d3436", fg="#74b9ff", highlightthickness=4, relief="flat", highlightbackground="#74b9ff", activebackground="#74b9ff", borderwidth=4) target_button.place(x=360,y=320,width=180,height=80) # FPS limit checkbox limit_fps = tk.IntVar() fps_checkbox = tk.Checkbutton(window, relief="groove", activebackground="#2d3436", activeforeground="#74b9ff", selectcolor="black", text="Limit FPS to 30", fg="#dfe6e9", borderwidth=0, highlightthickness=0, bg="#2d3436", variable=limit_fps, command=toggle_fps_limit) fps_checkbox.place(x=30,y=500,width=240,height=31) fps_checkbox.select() # Keep frames checkbox keep_frames = tk.IntVar() frames_checkbox = tk.Checkbutton(window, relief="groove", activebackground="#2d3436", activeforeground="#74b9ff", selectcolor="black", text="Keep frames dir", fg="#dfe6e9", borderwidth=0, highlightthickness=0, bg="#2d3436", variable=keep_frames, command=toggle_keep_frames) frames_checkbox.place(x=37,y=450,width=240,height=31) # Start button start_button = tk.Button(window, text="Start", bg="#f1c40f", relief="flat", borderwidth=0, highlightthickness=0, command=lambda: [save_file(), start()]) start_button.place(x=240,y=560,width=120,height=49) # Status label status_label = tk.Label(window, width=580, justify="center", text="Status: waiting for input...", fg="#2ecc71", bg="#2d3436") status_label.place(x=10,y=640,width=580,height=30) window.mainloop()
import 'dart:io'; import 'package:flutter/material.dart'; class DefaultAvatar extends StatelessWidget { final String url; final double borderWidth; final double size; final double elevation; final Color borderColor; final Color backgroundColor; final File fileImage; DefaultAvatar({ @required this.url, this.borderWidth = 2, this.borderColor = Colors.white, this.backgroundColor, this.size = 128, this.elevation = 6, this.fileImage, }); @override Widget build(BuildContext context) { return Material( elevation: this.elevation, color: Colors.transparent, borderRadius: BorderRadius.circular(this.size), child: Container( width: this.size, height: this.size, decoration: BoxDecoration( color: Colors.transparent, borderRadius: BorderRadius.circular(this.size), border: Border.all( color: this.borderColor, width: this.borderWidth, ), image: DecorationImage(image: this._getImage(), fit: BoxFit.cover))), ); } ImageProvider _getImage() { if (fileImage == null && (this.url == null || this.url.isEmpty)) { return AssetImage( 'assets/images/avatar.png', ); } return NetworkImage(this.url); } }
import 'dart:convert'; import 'package:faker/faker.dart'; import 'package:flutter/services.dart'; class LargeDataSet { List<String>? _categories; List<String>? _venues; List<String>? _languages; static final LargeDataSet _instance = LargeDataSet._internal(); // Private Constructor LargeDataSet._internal(); factory LargeDataSet() { return _instance; } List<String> get categoriesList { _categories ??= _getCategories(); return _categories!; } List<String> get venuesList { _venues ??= _getVenues(); return _venues!; } Future<List<String>> get languagesList async { _languages ??= await _getLanguages(); return _languages!; } List<String> _getCategories() { List<String> items = []; for (int i = 0; i < 1000; i++) items.add(faker.lorem.words(3).join(' ')); return items; } List<String> _getVenues() { List<String> items = []; for (int i = 0; i < 1000; i++) items.add(faker.lorem.words(2).join(' ')); return items; } Future<List<String>> _getLanguages() async { List<String> items; String filePath = "assets/languages.json"; String jsonString = await rootBundle.loadString(filePath); items = await json.decode(jsonString); return items; } }
--- title: In 2024, How to Unlock iPhone 8 Passcode without iTunes without Knowing Passcode? | Dr.fone date: 2024-05-19T07:27:26.809Z updated: 2024-05-20T07:27:26.809Z tags: - unlock - remove screen lock categories: - ios - iphone description: This article describes How to Unlock iPhone 8 Passcode without iTunes without Knowing Passcode? excerpt: This article describes How to Unlock iPhone 8 Passcode without iTunes without Knowing Passcode? keywords: how to remove passcode from iphone,factory reset locked iphone without itunes,how to turn off find my iphone when phone is broken,how much does unlock a phone cost,total wireless unlock,what can jailbreak iphone do thumbnail: https://www.lifewire.com/thmb/bJZjivkvkiXSPidjAhZPdQz2Xu8=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/GettyImages-545995058-58ed21243df78cadab023f3c.jpg --- ## How to Unlock Apple iPhone 8 Passcode without iTunes without Knowing Passcode? If you have been locked out of your iOS device and would like to know how to unlock Apple iPhone 8 passcode without iTunes, then you have come to the right place. Unlike Android, iOS is quite particular when it comes to passcode security and doesn’t provide too many ways to reset the passcode. Therefore, users have to take added measures to unlock their screens. Even though this article focuses on the Apple iPhone 8 screen lock, you can follow the same instructions for other iOS devices. Read on and learn how to unlock Apple iPhone 8 passcode without iTunes. <iframe width="560" height="315" src="https://www.youtube.com/embed/wXbqfC7JTKc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="allowfullscreen"></iframe> ![Safe download](https://images.wondershare.com/drfone/article/2022/05/security.svg)safe & secure ## Part 1: How to unlock Apple iPhone 8 passcode with Dr.Fone - Screen Unlock (iOS)? Most of the users find it hard to unlock their devices by taking the assistance of iTunes. After all, it is a more complicated and time-consuming process. Ideally, you can take the assistance of a third-party tool like [Dr.Fone - Screen Unlock (iOS)](https://tools.techidaily.com/wondershare/drfone/iphone-unlock/) to [bypass the Apple iPhone 8 passcode.](https://drfone.wondershare.com/unlock/bypass-iphone-passcode.html) This tool will wipe out all the data after unlocking iPhone. It provides extremely reliable and easy solutions regarding the removal of the Apple iPhone 8 screen lock. Besides that, the tool can also be used to recover any kind of problem related to your iOS device. It is compatible with all the leading iOS versions and devices. All you need to do is access its user-friendly interface and follow simple click-through steps to unlock your device. To learn how to unlock Apple iPhone 8 passcode without iTunes (using Dr.Fone toolkit), follow these steps: ### [Dr.Fone - Screen Unlock (iOS)](https://tools.techidaily.com/wondershare/drfone/iphone-unlock/) Unlock iPhone Screen Without Password - Unlock screen passwords from all iPhone, iPad, and iPod Touch. - Bypass iCloud activation lock and Apple ID without password.![New icon](https://images.wondershare.com/drfone/others/new_23.png) - No tech knowledge is required; everybody can handle it. - Fully compatible with the latest iOS/iPadOS. **3981454** people have downloaded it 1\. To start with, download Dr.Fone - Screen Unlock (iOS) and install it on your computer. Launch it and select the option of "Screen Unlock" from the home screen. 2\. Now, connect your Apple iPhone 8 to your system and wait for a while as Dr.Fone will detect it automatically. Click on the “Unlock iOS Screen” button to initiate the process. ![how to unlock Apple iPhone 8 passcode without itunes-start to unlock Apple iPhone 8](https://images.wondershare.com/drfone/guide/unlock-ios-screen-1.png) 3\. As you would connect your Apple iPhone 8 to your system, you will get a “Trust this Computer” prompt. Make sure that you close this window by tapping on the “x” button. Once connected, Dr.Fone will ask you to follow some steps to set your device in Recovery mode, allowing it to be detected. ![how to unlock Apple iPhone 8 passcode without itunes-set your device in DFU mode](https://images.wondershare.com/drfone/guide/unlock-ios-screen-3.png) 4\. Meanwhile, the Dr.Fone interface will provide the following screen, asking for various details related to your device. Provide crucial information related to your device (model, iOS version, and more) and click on the “Download” button. ![how to unlock Apple iPhone 8 passcode without itunes-download firmware](https://images.wondershare.com/drfone/guide/unlock-ios-screen-4.png) 5\. Wait for a while, as the application will download the related firmware for your device and make it ready. It might take a while for the firmware to be downloaded completely. 6\. Once it is done, you will get the following prompt. To unlock your device, you need to uncheck the “Retain native data” feature, since the passcode can’t be removed without your Apple iPhone 8’s data loss. Click on the “Unlock Now” button. ![how to unlock Apple iPhone 8 passcode without itunes-unlock now](https://images.wondershare.com/drfone/guide/unlock-ios-screen-6.png) 7\. You would be asked to confirm your choice, as the process will reset your device. After providing the on-screen confirmation code, click on the “Unlock” button and let the application unlock your device. 8\. In a matter of a few seconds, your device will be reset, and its passcode would also be removed. You will get the following message once the process is completed. ![how to unlock Apple iPhone 8 passcode without itunes-unlock Apple iPhone 8 successfully](https://images.wondershare.com/drfone/guide/unlock-ios-screen-9.png) In the end, you can simply disconnect your Apple iPhone 8 safely from the system and restart it. It would be restarted without any passcode, letting you access it in a trouble-free manner. ![Safe download](https://images.wondershare.com/drfone/article/2022/05/security.svg)safe & secure #### **You may also be interested in:** - [4 Ways to Unlock iPhone without Passcode](https://drfone.wondershare.com/unlock/unlock-iphone-without-passcode.html) - [3 Ways to Unlock A Disabled iPhone Without iTunes](https://drfone.wondershare.com/unlock/unlock-disabled-iphone-without-itunes.html) - [4 Ways to Bypass iPhone Passcode Easily](https://drfone.wondershare.com/unlock/bypass-iphone-passcode.html) - [How to Fix It If We've Are Locked Out of iPad?](https://drfone.wondershare.com/unlock/locked-out-of-ipad.html) ## Part 2: How to unlock Apple iPhone 8 passcode with Find My iPhone? Apple also allows its users to remotely locate, lock, and erase their devices. Though, this feature can also be used to reset a device and remove its passcode. Needless to say, while doing so, you will reset your device. To learn how to unlock Apple iPhone 8 passcode without iTunes (with the Find My iPhone feature), follow these steps: 1\. To start with, open the iCloud website on your system and login using your Apple ID and password. ![how to unlock Apple iPhone 8 passcode without itunes-log in icloud.com](https://images.wondershare.com/drfone/article/2017/09/15060131172457.jpg) 2\. From the home screen, you can access several features. Select “Find my iPhone” to proceed. 3\. Now, click on the “All Device” dropdown button to select the Apple iPhone 8 device that you want to unlock. ![how to unlock Apple iPhone 8 passcode without itunes-select Apple iPhone 8](https://images.wondershare.com/drfone/article/2017/09/15060131563681.jpg) 4\. After selecting your device, you will get an option to ring it, lock it, or erase it. Click on the “Erase iPhone” option. ![how to unlock Apple iPhone 8 passcode without itunes-erase Apple iPhone 8](https://images.wondershare.com/drfone/article/2017/09/15060131746196.jpg) 5\. Agree with the pop-up message and choose to restore your device. Once it is done, your phone will be restarted without any lock. ## Part 3: How to unlock Apple iPhone 8 passcode in Recovery Mode? If none of the above-mentioned solutions would work, then you can always choose to put your Apple iPhone 8 in recovery mode and restore it. After when your Apple iPhone 8 would be restored, you can access it without any lock. It can be done by following these steps: 1\. Firstly, you need to put your device in recovery mode. Beforehand, you need to make sure that your device is turned off. If not, press the Power button and slide the screen to turn your Apple iPhone 8 off. ![how to unlock Apple iPhone 8 passcode without itunes-put Apple iPhone 8 in recovery mode](https://images.wondershare.com/drfone/article/2017/09/15060132012488.jpg) 2\. Now, launch iTunes on your Mac or Windows system. Afterward, press and hold the Home button on your Apple iPhone 8. While holding the Home button, connect it to your system. 3\. You will get an iTunes symbol on the screen. In no time, iTunes will also detect your device. 4\. As iTunes will detect your device in recovery mode, it will display a prompt similar to this. ![how to unlock Apple iPhone 8 passcode without itunes-restore Apple iPhone 8 to remove the lock screen](https://images.wondershare.com/drfone/article/2017/09/15060132381393.jpg) 5\. Simply agree to it and let iTunes restore your device. Once your device has been restored, you can access it without any screen lock. ## Part 4: About data loss after unlocking Apple iPhone 8 passcode As you can see, in all the above-mentioned solutions, your Apple iPhone 8 data would be lost while unlocking its passcode. This is because, as of now, there is no way to unlock an iPhone without restoring it. Needless to say, while restoring a device, its data is automatically lost. Since Apple is quite concerned about the security of the Apple iPhone 8 and the sensitivity of its data, it doesn’t let users unlock the Apple iPhone 8 device without losing their data. Even though lots of users have complained about this issue, Apple hasn’t come up with a solution yet. The best way to avoid this scenario is by taking a regular backup of your data. You can either backup your data on iCloud, via iTunes, or by using any third-party tool as well. In this way, you won’t be able to lose your important files while unlocking your device’s passcode. ## Conclusion Now when you know how to unlock Apple iPhone 8 passcode without iTunes, you can easily access your device. Ideally, you can simply take the assistance of [Dr.Fone - Screen Unlock (iOS)](https://tools.techidaily.com/wondershare/drfone/iphone-unlock/) to unlock your device. It can also be used to resolve any other problem related to your Apple iPhone 8/iPad as well. Feel free to give it a try and let us know if you face any problems while using it. ![Safe download](https://images.wondershare.com/drfone/article/2022/05/security.svg)safe & secure ## 5 Most Effective Methods to Unlock Apple iPhone 8 in Lost Mode Numerous security features make all Mac devices like iPhones, iPads, and Macs stand apart from the opposition in terms of user data safety. Lost Mode is one feature that locks your lost iPhone or other Apple devices so nobody can get to them. If your device is gone, you can use the Find My application on your other Apple device connected to a similar account to **unlock the lost iPhone.** If your Apple iPhone 8 is in Lost Mode and you don't have the foggiest idea of how to restore it, relax. This guide will cover every one of the techniques that you can use for **iPhone Lost Mode unlock**. ## Part 1: What Will Happen When iPhone Is in Lost Mode? The Apple iPhone 8 Lock feature permits remotely locking a lost Apple iPhone 8 to prevent people from using its data. If you set a password for a device before enabling the Lost Mode, you will need this password to unlock the Apple iPhone 8 once it has returned to its proprietor. The Lost Mode menu will ask you to set one if it has no password. Password is obligatory to stop Lost Mode once a device is returned to the owner, as Contact ID or Face ID won't work for this reason. ![lost mode](https://images.wondershare.com/drfone/article/2022/10/iphone-lost-mode-unlock-1.jpg) **Send a Custom Text Message:** When you sort out your lost iPhone and put it in Lost Mode, another supportive feature accessible to you is a custom message shown on the Lock Screen. You can enter any message to let an individual who found it realize this iPhone is lost. This way, you can demonstrate a phone number for the other person. That will expand opportunities to get your device back. **Erase Data Remotely:** Lost Mode allows you to delete the Apple iPhone 8 if you believe it's been some time since it's gone and you don't think you can get it back. Doing so will ensure nobody will use your user data. **Track Your Device on Map:** An owner can follow their lost iPhone on the map through the Lost Mode menu. The menu additionally gives email warnings to show the last location of your Apple iPhone 8. **Play Songs:** Playing a sound might assist you with finding your lost iPhone if it's still close by. The Apple iPhone 8 will play a sound at top volume, no matter what volume level was set on the Apple iPhone 8 device when you lost it. ### 1\. Remove lost mode by entering the correct passcode The most straightforward method for unlocking the Apple iPhone 8 in Lost Mode is entering the password on the actual device. If your device was protected with a password before placing it in Lost Mode, enter it again. If your device had no password while placing it in Lost Mode and you've entered it into iCloud while placing your Apple iPhone 8 into Lost Mode, utilize this password. That will help you **unlock lost iPhone**, and you can start operating your Apple iPhone 8 again. ### 2\. Remove it from Find My in iCloud One more method for unlocking the Lost Mode on your Apple iPhone 8 is to utilize the Find My iPhone application on the official iCloud site. Follow the steps underneath to do so: 1. Go to <www.icloud.com> and utilize your account details to sign in. 2. Click the "Find My iPhone" button and select all iDevices. 3. Pick the Apple iPhone 8 device you need to unlock in Lost Mode and tap the "Lost Mode" button. 4. Click the "Stop Lost Mode" button to remove the lock from the phone. 5. Confirm this activity by clicking the "Stop Lost Mode" button again. ### 3\. Use iCloud DNS Bypass Domain Name Service is an unsafe technique that utilizes a domain name to an IP address. iCloud stores every iPhone's information, and when an iPhone is set up, it sends a request through DNS to ensure whether the Apple iPhone 8 device has an activation lock enabled. The DNS bypass will send a fake "device isn't locked" message to iCloud through a server. It allows you to go through the setting of your Apple iPhone 8 and access some applications. However, you must remember that this technique works on iOS 11 or older versions. Follow these steps to utilize the iCloud DNS bypassing strategy to **unlock lost iPhone**: - Insert SIM in your Apple iPhone 8, turn it on, and select a preferred language and your location. - A WiFi screen will spring up. Tap on the "I" icon. If you are now connected with your WiFi, tap "Forget this Network." ![dns bypass](https://images.wondershare.com/drfone/article/2022/10/iphone-lost-mode-unlock-2.jpg) - Tap on "Configure DNS," and enter a DNS server as per your region from the list underneath: USA: 104.154.51.7 Asia: 104.155.28.90 Europe: 104.155.28.90 South America: 35.199.88.219 Australia and Oceania: 35.189.47.23 - Clean old DNS server off of ISP modem, select and connect to a WiFi network. Click the Back button when a popup says that the Apple iPhone 8 device is attempting to connect to the Apple servers. - You will now be on the DNS bypass screen. Pick the applications from the list to keep using your device. However, only a handful of applications are available through this. ### 4\. Use Emergency Call This technique is the most widely recognized one. You can bypass your iCloud activation by settling on a fake Emergency call. Nonetheless, it is accounted for that this strategy probably won't work for everyone. If your Apple iPhone 8 is on lost mode and attempting to unlock it, you can try using this method. Follow these steps for making an Emergency call on your **iPhone in Lost Mode unlock:** - Click the "Emergency Call" option on your locked device. ![emergency call](https://images.wondershare.com/drfone/article/2022/10/iphone-lost-mode-unlock-3.jpg) - Dial "\*#96274825\*0000\*1#," then, at that point, press and hold the dial button for 10 to 15 minutes. - If it's not working, try changing the last digit from 1-9. If this doesn't work, have a go at setting 0 after 9. Remember to hold the dial button. - Press Home, and it will return you to the beginning screen. Select the language and country, and the activation screen will never appear again. Now create a new password after **iPhone Lost Mode unlock.** ### 5\. Apple iPhone Unlock Apple iPhone Unlock is a site that can assist you with **iPhone in Lost Mode unlock**. You must give them your Apple iPhone 8's IMEI and model number to get their services. The benefit of Apple iPhone Unlock is that they keep themselves updated with the latest technology. They are educated regarding their tool's advancement by giving updates every time. ![apple iphone unlock](https://images.wondershare.com/drfone/article/2022/10/iphone-lost-mode-unlock-4.jpg) **Critical Features of Apple iPhone Unlock:** - As per their site, Apple iPhone Unlock can work with every one of the Apple iPhone 8 devices going from iPhone 4 to iPhone 14 Pro Max. - Don't bother downloading anything to your PC or phone like others. Another iPhone lock screen expects you to download their tool or software to work. ## Bonus Tips: How to Unlock Our iPhone Screen? ### Dr.Fone-Screen Unlock An expert unlocking tool comes in handy when no other method works. In this case, we strongly suggest you use the Dr.Fone-Screen Unlock tool by Wondershare. Dr.Fone is a reliable tool and has been in the market for a long time. Professional unlock service providers use it because of its ease of use and clean interface. So, without looking any further, download this tool for a remarkable unlocking experience. The methods below will guide you into unlocking your Apple iPhone 8 within no time: **Step 1. Connect your Apple iPhone 8/iPad** Open the Dr.Fone software and tap the "Unlock iOS Screen." ![screen unlock](https://images.wondershare.com/drfone/guide/drfone-home.png) **Step 2. Boot iPhone in Recovery/DFU mode** Before bypassing the Apple iPhone 8 lock screen, we want to boot it in Recovery or DFU mode by adhering to the on-screen guidelines. The Recovery mode is suggested for the iOS lock screen. However, if you can't activate the Recovery mode, you can figure out how to activate the DFU mode from their official site. ![recovery mode](https://images.wondershare.com/drfone/guide/unlock-ios-screen-3.png) **Step 3. Affirm Device Information** After getting the phone in DFU mode, Dr.Fone will show the Apple iPhone 8 device information, for example, the Apple iPhone 8 model and other data. You can choose the right information from the dropdown menu if the information isn't right. Then, at that point, download the firmware for your Apple iPhone 8. ![device information](https://images.wondershare.com/drfone/guide/unlock-ios-screen-4.png) **Step 4. Unlock the Apple iPhone 8 Screen Lock** After downloading the required firmware effectively, click Unlock Now to remove the lock. However, note that this unlocking system will wipe the user data on your Apple iPhone 8. Truly, there is no answer for **iPhone Lost Mode unlock** without losing your data. ![unlocked successfully](https://images.wondershare.com/drfone/guide/unlock-ios-screen-9.png) ### The Bottom Line You might forget the password used before placing your Apple iPhone 8 in Lost Mode. It is also likely to purchase a locked device, and then you can't contact the owner to unlock it and don't know your Apple ID details. Some might think this is a dead situation, and you can't use the iPhone. Luckily, we’re here to provide a series of dependable and secure solutions that will help your **iPhone in Lost Mode unlock.** ## Detailed Review of doctorSIM Unlock Service For Apple iPhone 8 IMEI unlocking frees a mobile device from the limitations imposed by its original carrier. This allows the Apple iPhone 8 device to operate with different network providers worldwide. Numerous tools and techniques exist to unlock phones. These include software-based unlocking, hardware modifications, and IMEI-based solutions. Among these methods, [doctorSIM](https://www.doctorsim.com/us-en/) stands out as a reliable and reputable service. While alternative operational solutions are available, IMEI unlocking remains a popular choice. Some users may find it necessary when changing carriers or traveling abroad. In this **doctorSIM review**, we'll review its functions, reliability, and pros and cons. ![imei unlocking with doctorsim](https://images.wondershare.com/drfone/article/2024/01/doctor-sim-unlock-reviews-1.jpg) ## Part 1. Understanding The Basic Mechanism Behind doctorSIM: A Review doctorSIM is a comprehensive solution for smartphones and offers a whole lot of features. These services range from recharging mobile devices to unlocking carrier locks. When it comes to unlocking carrier locks, **doctorSIM legit** claims to work for any carrier anywhere worldwide. Its primary function revolves around providing users with the ability to unlock their devices. The tool provides users with the convenience of checking if their device is blacklisted. This service extends globally and comes at a reasonable price point. Moreover, **doctorSIM unlock review** and unlocking solutions cater to most iOS devices and Android phones. It includes even lesser-known niche brands, offering compatibility across a wide spectrum. ### Key Features of doctorSIM 1. It allows you to check the SIM lock status and warranty status of your iOS device. 2. doctorSIM can also help you check the [iCloud Activation Lock](https://drfone.wondershare.com/ios-16/how-to-bypass-icloud-activation-lock-screen-on-ios-16.html)Status and MI Account Activation Status. 3. Along with the old devices, this service is also compatible with the latest models, such as the Apple iPhone 8 15 series, ### Pros - There is no need to download and install any software on the Apple iPhone 8 device. - Jailbreaking the Apple iPhone 8 device isn't a requirement. - Offers a 30-day money-back guarantee. ### Con - It can take up to a week to unlock a device ## Part 2. Using doctorSIM for Easy IMEI Unlocking Operations **doctorSIM unlock reviews** simplify the unlocking process by leveraging the [IMEI number](https://drfone.wondershare.com/unlock/unlock-phone-free-with-imei-number.html). Here, users can submit their device's IMEI number and relevant details. It then provides an unlocking code or instructions tailored to their device model and carrier. Below are the instructions you should adhere to to unlock your device: - **Step 1.** You can start by accessing the doctorSIM website using a web browser. Here, click the "Unlock" option, and from the drop-down menu, choose your device brand, for example, "Apple." ![select your device type](https://images.wondershare.com/drfone/article/2024/01/doctor-sim-unlock-reviews-2.jpg) - **Step 2.** On the following screen, scroll down to choose your smartphone model, followed by your country and network carrier. Next, choose the "Service" you want to use, provide an IMEI number, agree to the terms, and click "Next." ![choose country and carrier](https://images.wondershare.com/drfone/article/2024/01/doctor-sim-unlock-reviews-3.jpg) - **Step 3.** This will take you to the next screen, where you can view the "Summary" of your order. If everything is all right, press “Next” to move to payments to pay the charges via Credit Card or Crypto. Afterward, wait for the process to complete, which can take days. ![review order summary ](https://images.wondershare.com/drfone/article/2024/01/doctor-sim-unlock-reviews-4.jpg) ## Part 3. Is the Entire doctorSIM System Legit? doctorSIM is generally regarded as a legitimate platform for unlocking mobile devices. Its legitimacy is supported by various factors, ranging from reputation to customer reviews. It has established a credible reputation within the mobile device unlocking industry. The service has been operating for several years and has garnered users' trust. The platform operates within the legal frameworks governing IMEI unlocking services. It adheres to regulations and ensures that the unlocking methods used are lawful. While specific reviews may vary, many users have reported positive experiences. Customer **doctorSIM reviews** highlight the platform's reliability, effectiveness, and user-friendly interface. It provides clear information about the unlocking process, associated fees, and service terms. Such effective transparency contributes to its credibility. ## Part 4. Other Top Alternatives of IMEI Unlocking It is important to clarify that doctorSIM primarily focuses on IMEI unlocking. This liberates a device from carrier restrictions to enable use with various networks. Amongst all the discussion, it is crucial to differentiate that this service does not offer iCloud Activation Lock removal in any case. Here are some top alternatives specifically that you can consider when using doctorSIM for unlocking purposes: ### 1\. [IMEIDocto](https://imeidoctor.com/en_us) Specializing in unlocking iPhones by IMEI, IMEIDoctor is a trusted service. It offers a dependable solution for users seeking freedom from carrier restrictions. IMEIDoctor stands out further due to its extensive support for various iPhone models and carriers. It solidifies its status as a reliable choice. ![imeidoctor imei unlocking alternative](https://images.wondershare.com/drfone/article/2024/01/doctor-sim-unlock-reviews-5.jpg) ### 2\. [CellUnlocker](https://www.cellunlocker.net/) CellUnlocker stands out as a reputable IMEI unlocking service, catering to many types of smartphones. Known for its reliability, the service facilitates unlocking for numerous carriers globally. This provides flexibility for users requiring international use of their devices. The user-friendly interface further enhances the overall experience. ![cellunlocker imei unlocking alternative](https://images.wondershare.com/drfone/article/2024/01/doctor-sim-unlock-reviews-6.jpg) ### 3\. [IMEIUnlockSIM](https://www.imeiunlocksim.com/) IMEIUnlockSIM is a specialized service focusing on unlocking iPhones through IMEI. Known for its straightforward process, it aims to provide users with a hassle-free experience. This service also offers iCloud unlock and IMEI checks. The service supports a variety of iPhone and Android models and provides timely customer support. ![imeiunlocksim imei unlocking alternative](https://images.wondershare.com/drfone/article/2024/01/doctor-sim-unlock-reviews-7.jpg) ### 4\. [iUnlockBase](https://www.unlockbase.com/) This IMEI unlocking service is a comprehensive service renowned for its expansive database. It supports a large number of devices and carriers. The platform provides various unlocking services, such as network unlocking and iCloud unlocking. Serving a worldwide audience, iUnlockBase guarantees a seamless unlocking process. ![iunlockbase imei unlocking alternative](https://images.wondershare.com/drfone/article/2024/01/doctor-sim-unlock-reviews-8.jpg) ## Part 5. What To Do When iCloud Activation Lock Active? Although IMEI Unlocking turns out to be quite an exceptional service, it generally is not the only thing that becomes a barrier for iPhone users. The iCloud Activation binds an Apple device to a user's Apple ID, making itself a great security measure. It presents a unique circumstance where services such as **doctorSIM legit** are inapplicable. [Wondershare Dr.Fone](https://tools.techidaily.com/wondershare/drfone/drfone-toolkit/) specializes in bypassing the iCloud Activation Lock. It allows users to circumvent it without needing the Apple ID. This unique capability sets Dr.Fone apart from other solutions. Once the activation lock is removed, it grants full access to users' devices. Dr.Fone also extends its capabilities to remove an Apple ID in cases where the password is forgotten. Its remarkable performance includes the permanent bypass of the Apple ID lock. ### Notable Characteristics of Wondershare Dr.Fone 1. [Remove MDM](https://drfone.wondershare.com/unlock/mdm-bypass-free.html)or Screen Time passcodes on your device effortlessly, preserving your data. 2. Wondershare Dr.Fone specializes in bypassing various screen locks, including passcodes and Face IDs. 3. Fone can remove the iTunes backup encryption lock without any impact on your data. ### Steps To Bypass iCloud Activation Lock via Wondershare Dr.Fone Dr.Fone is intended for users locked out of their devices. Given below are the steps you need to follow when using Dr.Fone to bypass iCloud Activation Lock: #### 1\. For Devices Running iOS/iPadOS 12.0 to 14.8.1 - **Step 1. Installation and iCloud Activation Lock Removal** Install and launch the most recent version of Wondershare Dr.Fone onto your computer. Now, proceed to the "Toolbox" tab, navigate to "Screen Unlock" and select "iOS." In the following window, choose "iCloud Activation Lock Removal" and click "Start" to begin the process and receive a prompt to connect your iOS device. Once connected, the window will display the progress status. ![proceed with icloud activation lock removal](https://images.wondershare.com/drfone/guide/bypass-activation-lock-2.png) - **Step 2. Device Identification and Unlock Initiation** Now, decide whether your device is GSM or CDMA, as it is an important aspect. Bypassing iCloud Activation Lock on a GSM device won't affect the Apple iPhone 8 device. However, running this process on a CDMA device will result in a loss of cellular activities. Click "Unlock Now" to proceed further, and if your device is CDMA type, you'll encounter a series of pointers. Go through them and click "Got It!" after agreeing with all the mentioned points. ![start to unlock device](https://images.wondershare.com/drfone/guide/bypass-activation-lock-4.png) - **Step 3. Jailbreaking and Activation Lock Bypass** After this, if your iDevice isn't jailbroken, you will be required to jailbreak your device. For that, you can follow the step-by-step textual instructions or watch a video. Once the Apple iPhone 8 device is jailbroken, the process will commence automatically to bypass the Activation Lock. A completion message will pop up on the window when the process finishes. Afterward, tap the “Done” button to finalize the process successfully. ![icloud activation lock successfully removed](https://images.wondershare.com/drfone/guide/bypass-activation-lock-9.png) #### 2\. For Devices Running iOS/iPadOS 15.0 to 16.3 - **Step 1. iCloud Activation Lock Removal Setup** On accessing the “iCloud Activation Lock Removal” page, a notification will display on the screen, alerting the user about the ongoing process. Carefully review all the information provided and select the "I have read and agree to the agreement" option. Proceed by tapping on the "Got It!" choice. ![unlock required iphone device](https://images.wondershare.com/drfone/guide/bypass-activation-lock-11.png) - **Step 2. DFU Mode Initiation and Device Unlock** Follow the on-screen instructions to initiate the [DFU Mode](https://drfone.wondershare.com/dfu-mode/tools-for-iphone-to-enter-dfu-mode.html) for your iOS device. Once in the particular mode, the program will send an initial command to the Apple iPhone 8 device, prompting it to restart. Click the right arrow to proceed and repeat putting the iOS device in DFU Mode. Likewise, upon completion, the program will activate and unlock the Apple iPhone 8 device promptly. Finally, click the "Got It!" button to conclude the process. ![read agreement and agree](https://images.wondershare.com/drfone/guide/bypass-activation-lock-13.png) - **Step 3. Completion of iCloud Activation Lock Removal** After processing the Apple iPhone 8 device in DFU Mode, Dr.Fone initiates the iCloud Activation Lock removal process. Monitor the progress bar to witness the process's completion. Once finished, a completion message will appear on the screen. Click “Done” to finalize the removal of the iCloud Activation Lock. ![icloud activation lock bypassed](https://images.wondershare.com/drfone/guide/bypass-activation-lock-16.png) #### 3\. For Devices Running iOS/iPadOS 16.4~16.6 For users with devices operating on iOS/iPadOS versions 16.4~16.6, Dr.Fone offers a streamlined approach to removing the iCloud Activation Lock. This solution is crafted to autonomously retrieve and jailbreak your device. This eliminates the necessity for manual interference or the use of third-party apps. Post-jailbreak, proceed with the steps detailed above in the "For Devices Running iOS/iPadOS 12.0 to 14.8.1" section. ## Conclusion Throughout this **doctorSIM unlock service review**, we explored the different IMEI unlocking services, focusing on doctorSIM as a reliable solution. We covered its legitimacy, user-friendly interface, and efficacy in unlocking devices from carrier restrictions. Additionally, we discussed alternatives for iCloud Activation Lock removal. It emphasizes the uniqueness of tools like Wondershare Dr.Fone bypassing this security feature. _**Tips:** Are you searching for a powerful iPhone Unlock tool? No worries as [Dr.Fone](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) is here to help you. Download it and start a seamless unlock experience!_ <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://iphone-unlock.techidaily.com/a-comprehensive-guide-to-apple-iphone-15-plus-blacklist-removal-tips-and-tools-drfone-by-drfone-ios/"><u>A Comprehensive Guide to Apple iPhone 15 Plus Blacklist Removal Tips and Tools | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/locked-out-of-apple-iphone-12-mini-5-ways-to-get-into-a-locked-apple-iphone-12-mini-drfone-by-drfone-ios/"><u>Locked Out of Apple iPhone 12 mini? 5 Ways to get into a Locked Apple iPhone 12 mini | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-do-you-remove-restricted-mode-on-iphone-xr-drfone-by-drfone-ios/"><u>How Do You Remove Restricted Mode on iPhone XR | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-complete-fixes-to-solve-iphone-7-plus-randomly-asking-for-apple-id-password-drfone-by-drfone-ios/"><u>In 2024, Complete Fixes To Solve iPhone 7 Plus Randomly Asking for Apple ID Password | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-many-attempts-to-unlock-iphone-7-plus-drfone-by-drfone-ios/"><u>In 2024, How Many Attempts To Unlock iPhone 7 Plus | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/remove-device-supervision-from-your-apple-iphone-12-pro-max-drfone-by-drfone-ios/"><u>Remove Device Supervision From your Apple iPhone 12 Pro Max | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-change-your-apple-id-password-on-your-iphone-6s-drfone-by-drfone-ios/"><u>How To Change Your Apple ID Password On your iPhone 6s | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/is-your-apple-iphone-13-pro-max-in-security-lockout-proper-ways-to-unlock-drfone-by-drfone-ios/"><u>Is Your Apple iPhone 13 Pro Max in Security Lockout? Proper Ways To Unlock | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-iphone-is-disabled-here-is-the-way-to-unlock-disabled-apple-iphone-xs-max-drfone-by-drfone-ios/"><u>In 2024, iPhone Is Disabled? Here Is The Way To Unlock Disabled Apple iPhone XS Max | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/remove-device-supervision-from-your-iphone-13-drfone-by-drfone-ios/"><u>Remove Device Supervision From your iPhone 13 | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-make-the-most-of-your-iphone-6-lock-screen-with-notifications-drfone-by-drfone-ios/"><u>How to Make the Most of Your iPhone 6 Lock Screen with Notifications? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/reset-itunes-backup-password-of-apple-iphone-x-prevention-and-solution-drfone-by-drfone-ios/"><u>Reset iTunes Backup Password Of Apple iPhone X Prevention & Solution | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/3-ways-to-erase-iphone-13-mini-when-its-locked-within-seconds-drfone-by-drfone-ios/"><u>3 Ways to Erase iPhone 13 mini When Its Locked Within Seconds | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-iphone-14-passcode-without-computer-drfone-by-drfone-ios/"><u>In 2024, How to Unlock iPhone 14 Passcode without Computer? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-apple-iphone-14-without-swiping-up-6-ways-drfone-by-drfone-ios/"><u>In 2024, How To Unlock Apple iPhone 14 Without Swiping Up? 6 Ways | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/unlock-iphone-15-pro-max-with-forgotten-passcode-different-methods-you-can-try-drfone-by-drfone-ios/"><u>Unlock iPhone 15 Pro Max With Forgotten Passcode Different Methods You Can Try | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-complete-guide-on-unlocking-apple-iphone-8-with-a-broken-screen-drfone-by-drfone-ios/"><u>In 2024, Complete Guide on Unlocking Apple iPhone 8 with a Broken Screen? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-complete-guide-on-unlocking-iphone-8-plus-with-a-broken-screen-drfone-by-drfone-ios/"><u>In 2024, Complete Guide on Unlocking iPhone 8 Plus with a Broken Screen? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-do-you-unlock-your-apple-iphone-11-pro-max-learn-all-4-methods-drfone-by-drfone-ios/"><u>In 2024, How Do You Unlock your Apple iPhone 11 Pro Max? Learn All 4 Methods | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/complete-fixes-to-solve-apple-iphone-6-plus-randomly-asking-for-apple-id-password-drfone-by-drfone-ios/"><u>Complete Fixes To Solve Apple iPhone 6 Plus Randomly Asking for Apple ID Password | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-bypass-apple-iphone-12-passcode-easily-video-inside-drfone-by-drfone-ios/"><u>In 2024, How to Bypass Apple iPhone 12 Passcode Easily Video Inside | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-different-methods-to-unlock-your-iphone-15-pro-drfone-by-drfone-ios/"><u>In 2024, Different Methods To Unlock Your iPhone 15 Pro | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-iphone-14-backup-password-never-set-but-still-asking-heres-the-fix-drfone-by-drfone-ios/"><u>In 2024, iPhone 14 Backup Password Never Set But Still Asking? Heres the Fix | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-resolve-your-apple-iphone-11-pro-max-keeps-asking-for-outlook-password-drfone-by-drfone-ios/"><u>In 2024, Resolve Your Apple iPhone 11 Pro Max Keeps Asking for Outlook Password | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-change-your-apple-id-password-on-your-apple-iphone-13-drfone-by-drfone-ios/"><u>In 2024, How To Change Your Apple ID Password On your Apple iPhone 13 | Dr.fone</u></a></li> <li><a href="https://pokemon-go-android.techidaily.com/where-is-the-best-place-to-catch-dratini-on-realme-12plus-5g-drfone-by-drfone-virtual-android/"><u>Where Is the Best Place to Catch Dratini On Realme 12+ 5G | Dr.fone</u></a></li> <li><a href="https://activate-lock.techidaily.com/how-to-delete-icloud-account-with-or-without-password-from-your-iphone-14-pro-maxwindowsmac-by-drfone-ios/"><u>How to Delete iCloud Account with or without Password from your iPhone 14 Pro Max/Windows/Mac</u></a></li> <li><a href="https://android-location.techidaily.com/in-2024-10-fake-gps-location-apps-on-android-of-your-honor-90-pro-drfone-by-drfone-virtual/"><u>In 2024, 10 Fake GPS Location Apps on Android Of your Honor 90 Pro | Dr.fone</u></a></li> <li><a href="https://ai-vdieo-software.techidaily.com/updated-audio-to-video-conversion-101-what-you-need-to-consider/"><u>Updated Audio to Video Conversion 101 What You Need to Consider</u></a></li> <li><a href="https://bypass-frp.techidaily.com/in-2024-hassle-free-ways-to-remove-frp-lock-on-infinix-smart-8withwithout-a-pc-by-drfone-android/"><u>In 2024, Hassle-Free Ways to Remove FRP Lock on Infinix Smart 8with/without a PC</u></a></li> <li><a href="https://android-transfer.techidaily.com/in-2024-easiest-guide-how-to-clone-xiaomi-redmi-note-12r-phone-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>In 2024, Easiest Guide How to Clone Xiaomi Redmi Note 12R Phone? | Dr.fone</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/in-2024-list-of-pokemon-go-joysticks-on-motorola-edgeplus-2023-drfone-by-drfone-virtual-android/"><u>In 2024, List of Pokémon Go Joysticks On Motorola Edge+ (2023) | Dr.fone</u></a></li> <li><a href="https://sim-unlock.techidaily.com/in-2024-top-imei-unlokers-for-your-oppo-a38-phone-by-drfone-android/"><u>In 2024, Top IMEI Unlokers for Your Oppo A38 Phone</u></a></li> <li><a href="https://review-topics.techidaily.com/possible-solutions-to-restore-deleted-music-from-vivo-y78t-by-fonelab-android-recover-music/"><u>Possible solutions to restore deleted music from Vivo Y78t</u></a></li> <li><a href="https://sim-unlock.techidaily.com/in-2024-ways-to-find-unlocking-codes-for-nokia-150-2023-phones-by-drfone-android/"><u>In 2024, Ways To Find Unlocking Codes For Nokia 150 (2023) Phones</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-unlock-samsung-galaxy-a54-5g-pin-codepattern-lockpassword-by-drfone-android/"><u>How to Unlock Samsung Galaxy A54 5G PIN Code/Pattern Lock/Password</u></a></li> <li><a href="https://apple-account.techidaily.com/in-2024-how-to-reset-apple-id-and-apple-password-from-iphone-8-plus-by-drfone-ios/"><u>In 2024, How to Reset Apple ID and Apple Password From iPhone 8 Plus</u></a></li> <li><a href="https://sim-unlock.techidaily.com/in-2024-what-does-enter-puk-code-mean-and-why-did-the-sim-get-puk-blocked-on-samsung-galaxy-f15-5g-device-by-drfone-android/"><u>In 2024, What Does Enter PUK Code Mean And Why Did The Sim Get PUK Blocked On Samsung Galaxy F15 5G Device</u></a></li> <li><a href="https://screen-mirror.techidaily.com/in-2024-a-guide-tecno-camon-20-pro-5g-wireless-and-wired-screen-mirroring-drfone-by-drfone-android/"><u>In 2024, A Guide Tecno Camon 20 Pro 5G Wireless and Wired Screen Mirroring | Dr.fone</u></a></li> <li><a href="https://apple-account.techidaily.com/in-2024-how-to-erase-an-apple-iphone-12-pro-max-without-apple-id-by-drfone-ios/"><u>In 2024, How to Erase an Apple iPhone 12 Pro Max without Apple ID?</u></a></li> </ul></div>
import { useEffect, useMemo, useRef, useState } from "react"; import { debounce } from "lodash"; const LLDebouncedAutoResizeTextarea = ({ value, onChange, placeholder, cols, autoFocus, focus, twStyle, }: { value: string[]; onChange: (value: string[]) => void; placeholder?: string; cols?: number; autoFocus?: boolean; focus?: boolean; twStyle?: string; }) => { const [optimisticValue, setOptimisticValue] = useState<string>( value.join("\n") ); const textarea = useRef<HTMLTextAreaElement>(null); useEffect(() => { setOptimisticValue(value.join("\n")); }, [value]); useEffect(() => { if (!textarea.current) return; textarea.current.style.height = "0px"; textarea.current.style.height = textarea.current.scrollHeight + "px"; }); useEffect(() => { if (focus && textarea.current) return textarea.current.focus(); }, [focus]); const debouncedOnChange = useMemo( () => debounce( (value: string, onChangeFx: (value: string[]) => void) => onChangeFx(value.split(/\r?\n/)), 300 ), [] ); return ( <textarea ref={textarea} className={`${twStyle} resize-none bg-white px-4 py-2 outline-none border-l-2 border-gray-500 hover:border-cyan-300 focus:border-cyan-300 focus:outline-none`} placeholder={placeholder} value={optimisticValue} onChange={(event) => { setOptimisticValue(event.target.value); debouncedOnChange(event.target.value, onChange); }} cols={cols} autoFocus={autoFocus} /> ); }; export default LLDebouncedAutoResizeTextarea;
@draft2019-09 Feature: maxContains draft2019-09 In order to use json-schema As a developer I want to support maxContains in draft2019-09 Scenario Outline: maxContains without contains is ignored /* Schema: { "$schema": "https://json-schema.org/draft/2019-09/schema", "maxContains": 1 } */ Given the input JSON file "maxContains.json" And the schema at "#/0/schema" And the input data at "<inputDataReference>" And I generate a type for the schema And I construct an instance of the schema type from the data When I validate the instance Then the result will be <valid> Examples: | inputDataReference | valid | description | | #/000/tests/000/data | true | one item valid against lone maxContains | | #/000/tests/001/data | true | two items still valid against lone maxContains | Scenario Outline: maxContains with contains /* Schema: { "$schema": "https://json-schema.org/draft/2019-09/schema", "contains": {"const": 1}, "maxContains": 1 } */ Given the input JSON file "maxContains.json" And the schema at "#/1/schema" And the input data at "<inputDataReference>" And I generate a type for the schema And I construct an instance of the schema type from the data When I validate the instance Then the result will be <valid> Examples: | inputDataReference | valid | description | | #/001/tests/000/data | false | empty data | | #/001/tests/001/data | true | all elements match, valid maxContains | | #/001/tests/002/data | false | all elements match, invalid maxContains | | #/001/tests/003/data | true | some elements match, valid maxContains | | #/001/tests/004/data | false | some elements match, invalid maxContains | Scenario Outline: maxContains with contains, value with a decimal /* Schema: { "$schema": "https://json-schema.org/draft/2019-09/schema", "contains": {"const": 1}, "maxContains": 1.0 } */ Given the input JSON file "maxContains.json" And the schema at "#/2/schema" And the input data at "<inputDataReference>" And I generate a type for the schema And I construct an instance of the schema type from the data When I validate the instance Then the result will be <valid> Examples: | inputDataReference | valid | description | | #/002/tests/000/data | true | one element matches, valid maxContains | | #/002/tests/001/data | false | too many elements match, invalid maxContains | Scenario Outline: minContains less than maxContains /* Schema: { "$schema": "https://json-schema.org/draft/2019-09/schema", "contains": {"const": 1}, "minContains": 1, "maxContains": 3 } */ Given the input JSON file "maxContains.json" And the schema at "#/3/schema" And the input data at "<inputDataReference>" And I generate a type for the schema And I construct an instance of the schema type from the data When I validate the instance Then the result will be <valid> Examples: | inputDataReference | valid | description | | #/003/tests/000/data | false | actual < minContains < maxContains | | #/003/tests/001/data | true | minContains < actual < maxContains | | #/003/tests/002/data | false | minContains < maxContains < actual |
<template> <div class="about"> <h2>{{ route.params.userName }}</h2> <el-button type="primary" @click="query">查询</el-button> <el-table :data="data.tableData" style="width: 100%"> <el-table-column label="电影名" prop="title" width="180" /> <el-table-column label="评分" prop="rate" width="180" /> <el-table-column label="简介" prop="url" /> <el-table-column label="封面"> <template #default="scope"> <img :src="scope.row.cover" alt="封面" width="44" height="23" /> </template> </el-table-column> <el-table-column label="操作"> <template #default="scope"> <el-button size="small" @click="handleEdit(scope.$index, scope.row)" >编辑</el-button > <el-button size="small" type="danger" @click="deleteMovie(scope.$index, scope.row)" >删除</el-button > </template> </el-table-column> </el-table> <el-dialog v-model="dialogFormVisible" title="编辑"> <el-form :model="data.editData"> <el-form-item label="电影名" :label-width="formLabelWidth"> <el-input v-model="data.editData.title" autocomplete="off" /> </el-form-item> <el-form-item label="评分" :label-width="formLabelWidth"> <el-input v-model="data.editData.rate" autocomplete="off" /> </el-form-item> </el-form> <template #footer> <span class="dialog-footer"> <el-button @click="dialogFormVisible = false">取消</el-button> <el-button type="primary" @click="editMovie()">确定</el-button> </span> </template> </el-dialog> </div> </template> <script setup lang="ts"> import { ref, reactive, onMounted } from "vue"; import { useRoute } from "vue-router"; import axios from "@/utils/axios"; const route = useRoute(); const dialogFormVisible = ref(false); const formLabelWidth = "140px"; function query() { axios.get("/movies/query").then((res) => { // data.tableData = res.data.movieList; data.tableData = res.data; }); } function handleEdit(index, row) { dialogFormVisible.value = true; data.editData = row; } const editMovie = () => { const { title, rate, id } = data.editData || {}; axios .post("/movies/update", { id, title, rate, }) .then((res) => { console.log(res); dialogFormVisible.value = false; query(); }); }; function deleteMovie(index, row) { const { id } = row || {}; dialogFormVisible.value = false; axios({ url: "/movies/delete", method: "POST", data: { id, }, }).then((res) => { console.log(res); query(); }); } const data = reactive({ tableData: [], editData: { title: "", rate: "", }, }); onMounted(() => { query(); }); </script>
import { useState, useEffect } from 'react'; import { LRUCache } from 'lru-cache'; const cache = new LRUCache( {max: 70 }); // Crea una instancia de la caché con un límite de 50 elementos export const useCachedImage = (src) => { const [isInCache, setIsInCache] = useState(false); const [imageSrc, setImageSrc] = useState(''); useEffect(() => { if (cache.has(src)) { setIsInCache(true); setImageSrc(cache.get(src)); } else { const image = new Image(); image.src = src; image.onload = () => { cache.set(src, src); setIsInCache(true); setImageSrc(src); }; } }, [src]); return { isInCache, imageSrc }; }; export const useImagePreloading = (imagesToPreload) => { useEffect(() => { const preloadImages = () => { imagesToPreload.forEach((imageUrl) => { if (!cache.has(imageUrl)) { const image = new Image(); image.src = imageUrl; image.onload = () => { cache.set(imageUrl, imageUrl); }; } }); }; preloadImages(); }, [imagesToPreload]); };
import java.util.concurrent.*; // Here, I implemented ArrayBlockingQueue instead of ArrayList to the ProducerConsumer public class Main { public static void main(String[] args) { ArrayBlockingQueue<String> buffer = new ArrayBlockingQueue<>(6); ExecutorService executorService = Executors.newFixedThreadPool(3); Producer producer = new Producer(buffer, ThreadColor.ANSI_YELLOW.getColor()); Consumer consumer1 = new Consumer(buffer, ThreadColor.ANSI_PURPLE.getColor()); Consumer consumer2 = new Consumer(buffer, ThreadColor.ANSI_BLACK.getColor()); executorService.execute(producer); executorService.execute(consumer1); executorService.execute(consumer2); //There are 3 threads (3 is the limit of pool - line 14) in pool that's why this submit() method added to queue, and it waits for any thread finish Future<String> future = executorService.submit(new Callable<String>() { @Override public String call() throws Exception { System.out.println(ThreadColor.ANSI_WHITE.getColor() + "I'm being printed for the Callable class"); return "This is the callable result"; } }); try { System.out.println(future.get()); } catch (ExecutionException e) { System.out.println("Something went wrong"); } catch (InterruptedException e) { System.out.println("Thread running the task was interrupted"); } executorService.shutdown(); } }
#include "binary_trees.h" /** * binary_tree_sibling - finds the sibling of a node in a binary tree * @node: pointer to the node to find the sibling * * Return: pointer to the sibling node, or NULL if node has no sibling, * node is NULL, or the parent is NULL */ binary_tree_t *binary_tree_sibling(binary_tree_t *node) { /*Check if the input node or its parent is NULL*/ if (node == NULL || node->parent == NULL) { /*Return NULL if the node or the parent is NULL*/ return (NULL); } /*If the current node is the left child, return the right child*/ if (node->parent->left == node) { /*Return the right child of the parent as the sibling*/ return (node->parent->right); } /*Return the left child as the sibling*/ return (node->parent->left); }
# Admin Dashboard Boilerplate Laravel 10 and Soft UI Dashboard theme. [<img src="https://s3.amazonaws.com/creativetim_bucket/products/602/original/soft-ui-dashboard-laravel.jpg" width="100%" />](https://soft-ui-dashboard-laravel.creative-tim.com/dashboard) ## Installation 1. Unzip the downloaded archive 2. Copy and paste **admin-dashboard-boilerplate** folder in your **projects** folder. Rename the folder to your project's name 3. In your terminal run `composer install` 4. Copy `.env.example` to `.env` and updated the configurations (mainly the database configuration) 5. In your terminal run `php artisan key:generate` 6. Run `php artisan migrate --seed` to create the database tables and seed the users tables 7. Run `php artisan storage:link` to create the storage symlink (if you are using **Vagrant** with **Homestead** for development, remember to ssh into your virtual machine and run the command from there). ## Usage Register a user or login with default user **[email protected]** and password **Secret123** from your database and start testing (make sure to run the migrations and seeders for these credentials to be available). Spatie Role and Permission is already added. So, if you would to implement ACL. Your can update `config/roles_and_permissions.php` according to your application requirements. After updating roles_and_permissions config, run `php artisan add:roles_and_permissions` to seed the roles and permissions. ## Documentation [Laravel](https://laravel.com/docs/10.x) [Soft UI Dashboard](https://soft-ui-dashboard-laravel.creative-tim.com/documentation/getting-started/overview.html). ### Dashboard You can access the dashboard either by using the "**Dashboard**" link in the left sidebar or by adding **/dashboard** in the url after logging in. ## File Structure ``` app ├── Console │ └── Kernel.php ├── Exceptions │ └── Handler.php ├── Http │ ├── Controllers │ │ ├── Auth │ │ │ ├── ChangePasswordController.php │ │ │ ├── InfoUserController.php │ │ │ ├── RegisterController.php │ │ │ ├── ResetController.php │ │ │ └── SessionController.php │ │ ├── Controller.php │ │ └── HomeController.php │ ├── Kernel.php │ └── Middleware │ ├── Authenticate.php │ ├── EncryptCookies.php │ ├── PreventRequestsDuringMaintenance.php │ ├── RedirectIfAuthenticated.php │ ├── TrimStrings.php │ ├── TrustHosts.php │ ├── TrustProxies.php │ └── VerifyCsrfToken.php ├── Models │ └── User.php ├── Policies │ └── UsersPolicy.php ├── Providers │ ├── AppServiceProvider.php │ ├── AuthServiceProvider.php │ ├── BroadcastServiceProvider.php │ ├── EventServiceProvider.php │ └── RouteServiceProvider.php config ├── app.php ├── auth.php ├── broadcasting.php ├── cache.php ├── cors.php ├── database.php ├── filesystems.php ├── hashing.php ├── logging.php ├── mail.php ├── queue.php ├── sanctum.php ├── services.php ├── session.php ├── view.php | database | ├──factories | | UserFactory.php | | | ├──migrations | | 2014_10_12_000000_create_users_table.php | | 2014_10_12_100000_create_password_resets_table.php | | 2019_08_19_000000_create_failed_jobs_table.php | | 2019_12_14_000001_create_personal_access_tokens_table.php | | | └──seeds | DatabaseSeeder.php | UserSeeder.php | +---public | | .htaccess | | favicon.ico | | index.php | | | +---css | | app.css | | soft-ui-dashboard.css | +---js | | app.js | | | +---assets | | demo.css | | docs-soft.css | | docs.js | | | | +---css | | | | nucleo-icons.css | | | | nucleo-svg.css | | | | soft-ui-dashboard.css | | | | soft-ui-dashboard.css.map | | | └── soft-ui-dashboard.min.css | | | | +---+---js | | soft-ui--dashboard.js | | soft-ui--dashboard.js.map | | soft-ui--dashboard.min.js | | | +---core | bootstrap.bundle.min.js | bootstrap.min.js | popper.min.js | +---resources | +---lang | | \---en | | auth.php | | pagination.php | | passwords.php | | validation.php | | | \---views | | | +---admin | | dashboard.blade.php | | | +---user | | user-management.blade.php | | user-profile.blade.php | | | +---layouts | | | | | +---footers | | | | | | | +--auth | | | | footer.blade.php | | | +--guest | | | footer.blade.php | | | | | +---navbars | | | app.blade.php | | | | | +--auth | | | nav.blade.php | | | sidebar.blade.php | | +--guest | | | nav.blade.php | | | | | +--user_type | | auth.blade.php | | guest.blade.php | | | +---session | | | login-session.blade.php | | | register.blade.php | | | | | +---reset-password | | resetPassword.blade.php | | sendEmail.blade.php | | | billing.blade.php | profile.blade.php | tables.blade.php | +---routes | api.php | channels.php | console.php | web.php ``` ## Credits - [Creative Tim](https://creative-tim.com/?ref=sudl-readme) - [UPDIVISION](https://updivision.com)
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style1.css"> <link rel = "stylesheet" type = "text/css" href = "css/style.css"> <link rel="stylesheet" media="screen and (max-width: 768px)" href="css/mobile.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css"> <title>Criação De Sites</title> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> </head> <body> <div class="container-fluid p-2" style="background-color: #DDEF3F;"></div> <div> <nav class="navbar col-12 navbar-expand-lg navbar-dark" style="background-color:#111931;"> <div class="container-fluid col-11"> <a class="navbar-brand" href="index.html">ACM Tech</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="index.html">Home</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Serviços </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="Criacao_Site.html">Criação de Sites</a></li> </ul> </ul> <p class="text-center"> <a href="tela_login.html" class="btn btn-secondary">Área do Desenvolvedor</a> </p> </div> </div> </nav> </div> <header id="showcase"> <div id="showcase-container"> <h2>Criação de Sites</h2> <p>Sites responsivos que tem a cara da sua Empresa!</p> </div> </header> <!-- About --> <section id="clients"> <div class="headline">Nossos clientes</div> <div id="clients-container"> <img src="img/cliente1.jpeg" class="client" alt=""> <img src="img/cliente2.jpeg" class="client" alt=""> <img src="img/cliente3.jpeg" class="client" alt=""> <img src="img/cliente4.jpeg" class="client" alt=""> </div> </section> <section id="features"> <div class="headline" style="color: white;">O que fazemos</div> <div id="features-container"> <div class="feature"> <i class="fas fa-tachometer-alt fa-3x"></i> <span class="feature-title">Planejamento.</span> <p>Criamos a modelagem do seu projeto dentro de um planejamento minucioso, sempre com você como protagonista em todo processo para que saia no seu gosto. É nessa etapa que irmeos criar o layout exclusivo para seu site.</p> </div> <div class="feature"> <i class="fas fa-code fa-3x"></i> <span class="feature-title">Desenvolvimento do Site.</span> <p> e o desenvolvimento do seu site com as melhores tecnologias do mercado.</p> </div> <div class="feature"> <i class="fas fa-layer-group fa-3x"></i> <span class="feature-title">Entrega de Site.</span> <p>Enfim entregamos o seu site logo após colocarmos no ar.</p> </div> </div> </section> <section id="product"> <div class="headline">Nosso produto</div> <div id="product-container"> <img src="img/acm-tech.png" alt="" class="iphone-x"> <div id="items"> <div class="item"> <i class="fas fa-map-marked fa-2x color-secondary"></i> <p>Nossa empresa tem uma flexilididade no seu atendimento, pois além de atendermos em nosso próprio escritório realizamos também virtual.</p> </div> <div class="item"> <i class="fas fa-users fa-2x color-primary"></i> <p>A empresa é composta por profissionais qualificados para oferecer nosso melhor produto a você cliente.</p> </div> <div class="item"> <i class="fas fa-glass-cheers fa-2x color-primary"></i> <p>Nossa empresa é reconhecida como uma das melhores do mercado atualmente!</p> </div> <div class="item"> <i class="fas fa-book-open fa-2x"></i> <p>Além, de seu site pronto entregamos o manual de usuário para que não fique dúvidas em relação da usabilidade de seu site e lhe ofereça a melhor experiência como usuário.</p> </div> </div> </div> </section> <section id="portfolio"> <div class="headline" style="color: white;">Portfólio</div> <div id="portfolio-container"> <img src="img/port1.jpeg" alt="" class="portfolio-image"> <img src="img/port2.jpeg" alt="" class="portfolio-image"> <img src="img/port3.jpeg" alt="" class="portfolio-image"> <img src="img/port4.jpeg" alt="" class="portfolio-image"> </div> </section> <div class="contato"> <div class="col-11 m-auto"> <br><h2 class="text-center" style="color:white;">Contato</h2> </div> <ol> <li> <div class="m-auto" style="width: 150px;"> <i class="fab fa-whatsapp" style="font-size: 50px; color:#DDEF3F;"></i> <br><br><p style="color: white;">(81)99112-8309 <br>Vamos Conversar? <a href="https://api.whatsapp.com/send?phone=5581991128309;" target="_blank">Conversar</a> </p> </div> </li> <li> <div class="m-auto" style="width: 150px;"> <i class="fas fa-envelope" style="font-size: 50px; color:#DDEF3F;"></i> <br><br><p style="color: white;">[email protected] <a href="https://mail.google.com/mail/u/3/?ogbl#inbox?compose=DmwnWrRpdtjqHMfRCrRThKvMgHBwJWtNxmDxrvRlgjnppjtfzfsFsbjfZpfXCPNgMZjprctffVWq" target="_blank">Enviar e-mail</a></p> </div> </li> <li> <div class="m-auto" style="width: 150px;"> <i class="fas fa-map-marker-alt" style="font-size: 50px; color:#DDEF3F;"></i> <br><p style="color: white;">R. Siqueira Campos, 120 - Centro, Belo Jardim - PE <br><a href="https://goo.gl/maps/rN85bbWnAncJhidu7" target="_blank">Ver no Mapa</a> </p> </div> </li> </ol> </div> <hr style="color: white;"> <div class="footer-basic"> <footer> <div class="social"><a href="#"><i class="icon ion-social-instagram"></i></a><a href="#"><i class="icon ion-social-twitter"></i></a><a href="#"><i class="icon ion-social-facebook"></i></a></div> <ul class="list-inline"> <li class="list-inline-item"><a href="index.html">Home</a></li> <li class="list-inline-item"><a href="Criacao_Site.html">Serviços</a></li> </ul> <p class="copyright">ACM Tech© 2021</p> </footer> </div> <!-- Font Awesome --> <script src="https://kit.fontawesome.com/f9e19193d6.js" crossorigin="anonymous"></script> <!-- jQuery CDN --> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <!-- Our JS file --> <script src="js/main.js"></script> </body> </html>
/*Colours*/ header{ background-color:#e6a5fa;; /* Set background colour of header */ } h1{ color: #510d91; background-color:#e6a5fa; /* Set background colour and text colour */ } h2{ color:#630db5; background-color: antiquewhite; /* Set background colour and text colour */ } h3{ color:#2E006E; /* Set text colour */ } main{ color:#2E006E; /* Set text colour */ } body{ color:#2E006E; /* Set text colour */ } /*Position and Font*/ .activePage{ /* Highlights the page you are on in the nav bar*/ background-color: #f7d5a8; } .logo{ width:75px; height:75px; margin-top: 10px; margin-left: 10px; margin-right: 10px; float:left; /* Sets the postion of the logo*/ } header{ border:#510d91 solid; width:100%; /* Creates the header border and makes it take up the whole width*/ } .mainLogin{ float:right; position:absolute; top:40px; right:15px; /* Positions the log in form in the top right of the page*/ } h1{ margin: 5px; margin-bottom: 2%; margin-left:30px; width: 90%; text-decoration: underline; padding: 16px; /* Positions H1 text, used in the header*/ } h2{ font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; text-align: center; margin: 5px; margin-bottom: 2%; width: 50%; text-decoration: underline; padding: 10px; border:#2E006E solid; /* Sets font and alignment of H2 text, as well as applying an underline and a border*/ } h3{ font-family: 'Franklin Gothic Medium'; font-size: medium; /*Sets the font size and type of H3*/ } ul{ list-style-type: none; margin: 5px; margin-bottom: 2%; width: 100%; padding: 0; overflow: hidden; background-color: antiquewhite; border:#510d91 solid; /* Nav bar, sets the container the list is inside*/ } li{ list-style-type: none; float: left; display: block; text-align: center; font-size: larger; width: 12%; border:#2E006E hidden; /* The list of pages inside the nav bar, positions them*/ } li:hover{ background-color: #f7d5a8; /* Changes the background colour whenever you hover over a link in the nav bar */ } li a:hover{ background-color:#f7d5a8 /* Changes the background colour whenever you hover over a link in the nav bar */ } .centImg{ margin-left: 30%; margin-top: 2%; margin-bottom: 2%; /* Positions an image to be more centred to the page*/ } .left-col{ background-color: aliceblue; border:#510d91 solid; border-radius: 10px; padding-top: 2px; padding-right: 10px; padding-left: 10px; padding-bottom: 2px; margin: 10px; width: 55%; height:fit-content; float: left; /* Defines a column on the left side of the screen for content to sit in*/ } .right-col{ float: right; background-color: aliceblue; border:#510d91 solid; border-radius: 10px; padding-top: 2px; padding-right: 10px; padding-left: 10px; padding-bottom: 2px; margin: 10px; width: 35%; height:fit-content; float: right; /* Defines the right column for content to be placed inside.*/ } .centre-text{ margin-left: 25%; /* Centres text*/ } fieldset{ margin-left: 5px; /* Assigns a margin to fieldsets */ } table{ text-indent: initial; white-space: normal; line-height: normal; font-weight: normal; font-size: 10pt; font-style: normal; text-align: start; border-spacing: 2px; font-variant: normal; border-collapse: collapse; padding-bottom: 30px; /* Creates the design of the table*/ } th{ display: table-cell; vertical-align: center; font-weight: bold; text-align: center; border: black 2px solid; border-spacing: 2px; /* Positions the table heads*/ } td{ display: table-cell; vertical-align: inherit; border: black 2px solid; border-spacing: 2px; width:250px; height:100px; padding:10px; /* Positions the table cells and provides a border to seperate elements*/ } tr { display: table-row; vertical-align: inherit; border-color: inherit; /* Positions the table rows*/ } tr:nth-child(even) { background-color:antiquewhite; /* Makes every even coloured column in the table the specified colour*/ } tr:hover{ background-color: aliceblue; } .carousel{ position:absolute; border-radius: 10px; margin-top: 10px; padding-top: 10px; padding-right: 10px; padding-left: 10px; padding-bottom: 20px; margin-bottom:20px; height:fit-content; width:53%; border-collapse: collapse; background-color: azure; border:#510d91 solid; /* Positions the carousel in the page*/ } .carousel-inner{ width:100% } .carousel-item{ width:100% } .carousel-control-prev{ float: left; bottom: 15%; height:10%; position: absolute; align-items: center; /* Positions the arrow to switch to the previous image*/ } .carousel-control-next{ bottom: 15%; height:10%; margin-left: 42%; position: absolute; align-items: center; /* Positions the arrow to switch to the next image*/ } .gallery-img{ width:100%; } #img-gallery{ padding-top:10px; } #img-gallery.row{ margin-bottom:10px; } .col{ padding:5px; } .left-col-small{ background-color: aliceblue; border:#510d91 solid; border-radius: 10px; padding-top: 2px; padding-right: 10px; padding-left: 10px; padding-bottom: 20px; margin: 10px; width: 25%; height:fit-content; float: left; /* A smaller version of the left column*/ } .right-col-big{ float: right; background-color: aliceblue; border:#510d91 solid; border-radius: 10px; padding-top: 2px; padding-right: 10px; padding-left: 10px; padding-bottom: 20px; margin: 10px; width: 60%; height:fit-content; float:right; /* A larger version of the right column*/ } .imgWidthFull{ width:90%; /* Sets the width of assigned object to 90%. Intended for images*/ } footer{ float: left; width:100%; margin-top: 300px; padding: 16px; /* Positions the footer at the bottom of the page */ } .newsImage{ height:25%; width:25%; float:left; padding: 5px; margin-bottom:10px; /* Shrinks an image down to fit in a smaller container, floats it left so text can be put in next to it, and adds some padding so its not too close.*/ } .textPadding{ padding:5px; /* Adds a litle padding */ } .fullWidth{ width:100%; } .news{ padding:30px; border:#510d91 solid; } #eventForm{ /* Provides features for the event submision form */ margin-top: 16px; padding:16px; padding-bottom: 20px; } .hide{ display: none; } #gloped{ /* Used for a specific line to make it small and hard to read for the dramatic effect*/ font-size: x-small; color:#afd7fa; }
/* * Copyright (c) 2011-2012 The Chromium OS Authors. * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <errno.h> #include <os.h> #include <cli.h> #include <malloc.h> #include <asm/getopt.h> #include <asm/io.h> #include <asm/sections.h> #include <asm/state.h> DECLARE_GLOBAL_DATA_PTR; int sandbox_early_getopt_check(void) { struct sandbox_state *state = state_get_current(); struct sandbox_cmdline_option **sb_opt = __u_boot_sandbox_option_start; size_t num_options = __u_boot_sandbox_option_count(); size_t i; int max_arg_len, max_noarg_len; /* parse_err will be a string of the faulting option */ if (!state->parse_err) return 0; if (strcmp(state->parse_err, "help")) { printf("u-boot: error: failed while parsing option: %s\n" "\ttry running with --help for more information.\n", state->parse_err); os_exit(1); } printf( "u-boot, a command line test interface to U-Boot\n\n" "Usage: u-boot [options]\n" "Options:\n"); max_arg_len = 0; for (i = 0; i < num_options; ++i) max_arg_len = max((int)strlen(sb_opt[i]->flag), max_arg_len); max_noarg_len = max_arg_len + 7; for (i = 0; i < num_options; ++i) { struct sandbox_cmdline_option *opt = sb_opt[i]; /* first output the short flag if it has one */ if (opt->flag_short >= 0x100) printf(" "); else printf(" -%c, ", opt->flag_short); /* then the long flag */ if (opt->has_arg) printf("--%-*s <arg> ", max_arg_len, opt->flag); else printf("--%-*s", max_noarg_len, opt->flag); /* finally the help text */ printf(" %s\n", opt->help); } os_exit(0); } int misc_init_f(void) { return sandbox_early_getopt_check(); } static int sandbox_cmdline_cb_help(struct sandbox_state *state, const char *arg) { /* just flag to sandbox_early_getopt_check to show usage */ return 1; } SANDBOX_CMDLINE_OPT_SHORT(help, 'h', 0, "Display help"); #ifndef CONFIG_SPL_BUILD int sandbox_main_loop_init(void) { struct sandbox_state *state = state_get_current(); /* Execute command if required */ if (state->cmd || state->run_distro_boot) { int retval = 0; cli_init(); #ifdef CONFIG_CMDLINE if (state->cmd) retval = run_command_list(state->cmd, -1, 0); if (state->run_distro_boot) retval = cli_simple_run_command("run distro_bootcmd", 0); #endif if (!state->interactive) os_exit(retval); } return 0; } #endif static int sandbox_cmdline_cb_boot(struct sandbox_state *state, const char *arg) { state->run_distro_boot = true; return 0; } SANDBOX_CMDLINE_OPT_SHORT(boot, 'b', 0, "Run distro boot commands"); static int sandbox_cmdline_cb_command(struct sandbox_state *state, const char *arg) { state->cmd = arg; return 0; } SANDBOX_CMDLINE_OPT_SHORT(command, 'c', 1, "Execute U-Boot command"); static int sandbox_cmdline_cb_fdt(struct sandbox_state *state, const char *arg) { state->fdt_fname = arg; return 0; } SANDBOX_CMDLINE_OPT_SHORT(fdt, 'd', 1, "Specify U-Boot's control FDT"); static int sandbox_cmdline_cb_default_fdt(struct sandbox_state *state, const char *arg) { const char *fmt = "%s.dtb"; char *fname; int len; len = strlen(state->argv[0]) + strlen(fmt) + 1; fname = os_malloc(len); if (!fname) return -ENOMEM; snprintf(fname, len, fmt, state->argv[0]); state->fdt_fname = fname; return 0; } SANDBOX_CMDLINE_OPT_SHORT(default_fdt, 'D', 0, "Use the default u-boot.dtb control FDT in U-Boot directory"); static int sandbox_cmdline_cb_interactive(struct sandbox_state *state, const char *arg) { state->interactive = true; return 0; } SANDBOX_CMDLINE_OPT_SHORT(interactive, 'i', 0, "Enter interactive mode"); static int sandbox_cmdline_cb_jump(struct sandbox_state *state, const char *arg) { /* Remember to delete this U-Boot image later */ state->jumped_fname = arg; return 0; } SANDBOX_CMDLINE_OPT_SHORT(jump, 'j', 1, "Jumped from previous U-Boot"); static int sandbox_cmdline_cb_memory(struct sandbox_state *state, const char *arg) { int err; /* For now assume we always want to write it */ state->write_ram_buf = true; state->ram_buf_fname = arg; err = os_read_ram_buf(arg); if (err) { printf("Failed to read RAM buffer\n"); return err; } return 0; } SANDBOX_CMDLINE_OPT_SHORT(memory, 'm', 1, "Read/write ram_buf memory contents from file"); static int sandbox_cmdline_cb_rm_memory(struct sandbox_state *state, const char *arg) { state->ram_buf_rm = true; return 0; } SANDBOX_CMDLINE_OPT(rm_memory, 0, "Remove memory file after reading"); static int sandbox_cmdline_cb_state(struct sandbox_state *state, const char *arg) { state->state_fname = arg; return 0; } SANDBOX_CMDLINE_OPT_SHORT(state, 's', 1, "Specify the sandbox state FDT"); static int sandbox_cmdline_cb_read(struct sandbox_state *state, const char *arg) { state->read_state = true; return 0; } SANDBOX_CMDLINE_OPT_SHORT(read, 'r', 0, "Read the state FDT on startup"); static int sandbox_cmdline_cb_write(struct sandbox_state *state, const char *arg) { state->write_state = true; return 0; } SANDBOX_CMDLINE_OPT_SHORT(write, 'w', 0, "Write state FDT on exit"); static int sandbox_cmdline_cb_ignore_missing(struct sandbox_state *state, const char *arg) { state->ignore_missing_state_on_read = true; return 0; } SANDBOX_CMDLINE_OPT_SHORT(ignore_missing, 'n', 0, "Ignore missing state on read"); static int sandbox_cmdline_cb_show_lcd(struct sandbox_state *state, const char *arg) { state->show_lcd = true; return 0; } SANDBOX_CMDLINE_OPT_SHORT(show_lcd, 'l', 0, "Show the sandbox LCD display"); static const char *term_args[STATE_TERM_COUNT] = { "raw-with-sigs", "raw", "cooked", }; static int sandbox_cmdline_cb_terminal(struct sandbox_state *state, const char *arg) { int i; for (i = 0; i < STATE_TERM_COUNT; i++) { if (!strcmp(arg, term_args[i])) { state->term_raw = i; return 0; } } printf("Unknown terminal setting '%s' (", arg); for (i = 0; i < STATE_TERM_COUNT; i++) printf("%s%s", i ? ", " : "", term_args[i]); puts(")\n"); return 1; } SANDBOX_CMDLINE_OPT_SHORT(terminal, 't', 1, "Set terminal to raw/cooked mode"); static int sandbox_cmdline_cb_verbose(struct sandbox_state *state, const char *arg) { state->show_test_output = true; return 0; } SANDBOX_CMDLINE_OPT_SHORT(verbose, 'v', 0, "Show test output"); int board_run_command(const char *cmdline) { printf("## Commands are disabled. Please enable CONFIG_CMDLINE.\n"); return 1; } static void setup_ram_buf(struct sandbox_state *state) { gd->arch.ram_buf = state->ram_buf; gd->ram_size = state->ram_size; } int main(int argc, char *argv[]) { struct sandbox_state *state; gd_t data; int ret; ret = state_init(); if (ret) goto err; state = state_get_current(); if (os_parse_args(state, argc, argv)) return 1; ret = sandbox_read_state(state, state->state_fname); if (ret) goto err; /* Remove old memory file if required */ if (state->ram_buf_rm && state->ram_buf_fname) os_unlink(state->ram_buf_fname); memset(&data, '\0', sizeof(data)); gd = &data; #if CONFIG_VAL(SYS_MALLOC_F_LEN) gd->malloc_base = CONFIG_MALLOC_F_ADDR; #endif setup_ram_buf(state); /* Do pre- and post-relocation init */ board_init_f(0); board_init_r(gd->new_gd, 0); /* NOTREACHED - board_init_r() does not return */ return 0; err: printf("Error %d\n", ret); return 1; }
// // ContentView.swift // A3_Map // // Created by Natalie Sahadeo on 2021-11-09. // import SwiftUI import MapKit import CoreLocation struct MyPharmacyView: View { @StateObject private var viewModel = ContentViewModel() @State var preferredPharmacy = "" @State var location: CLLocationCoordinate2D? @State var toggleDirections = false struct Location : Identifiable{ let id = UUID() let name : String let coordinate : CLLocationCoordinate2D } struct RouteSteps : Identifiable{ let id = UUID() let step : String } @State var routeSteps : [RouteSteps] = [ RouteSteps(step: "Directions") ] //Array of annotations @State var annotations = [ Location(name: "Empire State Building", coordinate: CLLocationCoordinate2D(latitude: 40.748440, longitude: -73.985664)) ] //Set the location to tbe the user's location var body: some View { ZStack{ Image("LimeGreenGradient") .resizable() .scaledToFill() .edgesIgnoringSafeArea(.all) VStack{ Text("Please enter your preferred pharmacy") TextField("Preferred Pharmacy", text: $preferredPharmacy).background(Color.white) .textFieldStyle(.roundedBorder).padding(.horizontal, 20) //Show Map Map(coordinateRegion: $viewModel.region, showsUserLocation: true, annotationItems: annotations){ item in MapPin(coordinate: item.coordinate) }.ignoresSafeArea().accentColor(Color(.systemPink)).frame(width: 300, height: 300, alignment: .center).onAppear{viewModel.checkIfLocationServiceIsEnabled()}.padding(.vertical, 25) Button(action: { routeSteps = [] toggleDirections.toggle() let sourceLoc = MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: CLLocationManager().location!.coordinate.latitude, longitude: CLLocationManager().location!.coordinate.longitude)) findNewLocation(source: sourceLoc) //Display directions using the .sheet }){Text("Get Directions")}.sheet(isPresented: $toggleDirections, content: { VStack(spacing: 0) { Text("Directions") .font(.largeTitle) .bold() .padding() Divider().background(Color(UIColor.systemBlue)) List(routeSteps){r in Text(r.step)} } } ) } } } //Get the location coordinates func getLocation(from enteredLocation: String, completion: @escaping (_ location: CLLocationCoordinate2D?)-> Void) { let geocoder = CLGeocoder() geocoder.geocodeAddressString(enteredLocation) { (placemarks, error) in guard let placemarks = placemarks, let location = placemarks.first?.location?.coordinate else { completion(nil) return } completion(location) } } func findNewLocation(source: MKPlacemark){ let geocoder = CLGeocoder() let locEntered = preferredPharmacy geocoder.geocodeAddressString(locEntered, completionHandler: { //placemarks is an array (placemarks, error) -> Void in if(error != nil){ print("Error") } //going to take the first item from list if let placemark = placemarks?[0]{ let coordinates : CLLocationCoordinate2D = placemark.location!.coordinate annotations.append(Location(name: placemark.name!, coordinate: placemark.location!.coordinate)) viewModel.region = MKCoordinateRegion(center: coordinates, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)) let request = MKDirections.Request() request.source = MKMapItem(placemark: MKPlacemark(coordinate: source.coordinate)) request.destination = MKMapItem(placemark: MKPlacemark(coordinate: coordinates)) request.requestsAlternateRoutes = false request.transportType = .automobile let directions = MKDirections(request: request) //still have to do a loop even though its gonna show one result since we set alternative routes to false directions.calculate(completionHandler: {response, error in for route in (response?.routes)!{ for step in route.steps { routeSteps.append(RouteSteps(step: step.instructions)) } } } ) } } )} //For accessing the location permissions final class ContentViewModel: NSObject, ObservableObject, CLLocationManagerDelegate{ @Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 43.60648, longitude: -79.58988), span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)) var locationManager : CLLocationManager? func checkIfLocationServiceIsEnabled(){ if CLLocationManager.locationServicesEnabled(){ locationManager = CLLocationManager() locationManager!.delegate = self } else{ print("Location is off") } } private func checkLocationAuthorization(){ guard let locationManager = locationManager else { return } switch locationManager.authorizationStatus{ case .notDetermined: locationManager.requestWhenInUseAuthorization() case .restricted: print("Location is restricted") case .denied: print("Location denied") case .authorizedAlways,.authorizedWhenInUse: region = MKCoordinateRegion(center: locationManager.location!.coordinate, span:MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)) @unknown default: break } } func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { checkLocationAuthorization() } } }
const express = require("express") const mongoose = require("mongoose") const path = require("path") const cookieParser = require("cookie-parser") require("dotenv").config() const app = express() app.use(express.urlencoded({urlencoded: true})) app.use(express.json()) app.use(cookieParser()) app.set("view engine", "ejs") app.use("/libs", express.static(path.join(__dirname, "node_modules"))) app.use("/static", express.static(path.join(__dirname, "public"))) mongoose.connect(process.env.MONGO_URI) .then(() => console.log(`Database connected`)) .catch(err => console.log(`Database connect error: ${err}`)) const adminRoutes = require("./routes/admin") const userRoutes = require("./routes/user") app.use("/admin", adminRoutes) app.use(userRoutes) const PORT = process.env.PORT || 4000 app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`))
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.compositor.overlays.strip; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Bitmap; import android.util.AttributeSet; import android.util.Size; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.ColorInt; import androidx.annotation.VisibleForTesting; import androidx.appcompat.content.res.AppCompatResources; import org.chromium.base.supplier.Supplier; import org.chromium.chrome.R; import org.chromium.chrome.browser.browser_controls.BrowserControlsStateProvider; import org.chromium.chrome.browser.compositor.LayerTitleCache; import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager; import org.chromium.chrome.browser.tab.EmptyTabObserver; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabObserver; import org.chromium.chrome.browser.tab.TabUtils; import org.chromium.chrome.browser.tasks.tab_management.TabThumbnailView; import org.chromium.chrome.browser.tasks.tab_management.TabUiThemeProvider; import org.chromium.chrome.browser.tasks.tab_management.TabUiThemeUtil; import org.chromium.url.GURL; public class StripTabDragShadowView extends FrameLayout { // Constants @VisibleForTesting protected static final int WIDTH_DP = 264; // Children Views private View mCardView; private TextView mTitleView; private ImageView mFaviconView; private TabThumbnailView mThumbnailView; // Internal State private Boolean mIncognito; private int mWidthPx; // External Dependencies private BrowserControlsStateProvider mBrowserControlStateProvider; private Supplier<TabContentManager> mTabContentManagerSupplier; private Supplier<LayerTitleCache> mLayerTitleCacheSupplier; private ShadowUpdateHost mShadowUpdateHost; private Tab mTab; private TabObserver mFaviconUpdateTabObserver; public interface ShadowUpdateHost { /** * Notify the host of this drag shadow that the source view has been changed and its drag * shadow needs to be updated accordingly. */ void requestUpdate(); } public StripTabDragShadowView(Context context, AttributeSet attrs) { super(context, attrs); mWidthPx = (int) (context.getResources().getDisplayMetrics().density * WIDTH_DP); } @Override protected void onFinishInflate() { super.onFinishInflate(); mCardView = findViewById(R.id.card_view); mTitleView = findViewById(R.id.tab_title); mFaviconView = findViewById(R.id.tab_favicon); mThumbnailView = findViewById(R.id.tab_thumbnail); } /** * Set external dependencies and starting view properties. * * @param browserControlsStateProvider Provider for top browser controls state. * @param tabContentManagerSupplier Supplier for the {@link TabContentManager}. * @param layerTitleCacheSupplier Supplier for the {@link LayerTitleCache}. * @param shadowUpdateHost The host to push updates to. */ public void initialize( BrowserControlsStateProvider browserControlsStateProvider, Supplier<TabContentManager> tabContentManagerSupplier, Supplier<LayerTitleCache> layerTitleCacheSupplier, ShadowUpdateHost shadowUpdateHost) { mBrowserControlStateProvider = browserControlsStateProvider; mTabContentManagerSupplier = tabContentManagerSupplier; mLayerTitleCacheSupplier = layerTitleCacheSupplier; mShadowUpdateHost = shadowUpdateHost; int padding = (int) TabUiThemeProvider.getTabCardTopFaviconPadding(getContext()); mFaviconView.setPadding(padding, padding, padding, padding); mCardView.getBackground().mutate(); mTitleView.setTextAppearance(R.style.TextAppearance_TextMedium_Primary); RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mTitleView.getLayoutParams(); layoutParams.setMarginEnd(padding); mTitleView.setLayoutParams(layoutParams); mFaviconUpdateTabObserver = new EmptyTabObserver() { @Override public void onFaviconUpdated(Tab tab, Bitmap icon, GURL iconUrl) { if (icon != null) { mFaviconView.setImageBitmap(icon); } else { mFaviconView.setImageBitmap( mLayerTitleCacheSupplier.get().getOriginalFavicon(tab)); } mShadowUpdateHost.requestUpdate(); } }; } /** * Set state on tab drag start. * * @param tab The {@link Tab} being dragged. */ public void setTab(Tab tab) { mTab = tab; mTab.addObserver(mFaviconUpdateTabObserver); update(); } /** Clear state on tab drag end. */ public void clear() { mTab.removeObserver(mFaviconUpdateTabObserver); mTab = null; } private void update() { // TODO(https://crbug.com/1499119): Unify the shared code for creating the GTS-style card. // Set to final size. Even though the size will be animated, we need to initially set to the // final size, so that we allocate the appropriate amount of space when // #onProvideShadowMetrics is called on drag start. int heightPx = TabUtils.deriveGridCardHeight(mWidthPx, getContext(), mBrowserControlStateProvider); ViewGroup.LayoutParams layoutParams = getLayoutParams(); layoutParams.width = mWidthPx; layoutParams.height = heightPx; setLayoutParams(layoutParams); this.layout(0, 0, mWidthPx, heightPx); // Request the thumbnail. Size cardSize = new Size(mWidthPx, heightPx); Size thumbnailSize = TabUtils.deriveThumbnailSize(cardSize, getContext()); mTabContentManagerSupplier .get() .getTabThumbnailWithCallback( mTab.getId(), thumbnailSize, result -> { if (result != null) { TabUtils.setBitmapAndUpdateImageMatrix( mThumbnailView, result, thumbnailSize); } else { mThumbnailView.setImageDrawable(null); } mShadowUpdateHost.requestUpdate(); }, /* forceUpdate= */ true, /* writeBack= */ true); // Update title and set original favicon. LayerTitleCache layerTitleCache = mLayerTitleCacheSupplier.get(); mTitleView.setText( layerTitleCache.getUpdatedTitle( mTab, getContext().getString(R.string.tab_loading_default_title))); boolean fetchFaviconFromHistory = mTab.isNativePage() || mTab.getWebContents() == null; mFaviconView.setImageBitmap(layerTitleCache.getOriginalFavicon(mTab)); if (fetchFaviconFromHistory) { layerTitleCache.fetchFaviconWithCallback( mTab, (image, iconUrl) -> { if (image != null) { mFaviconView.setImageBitmap(image); mShadowUpdateHost.requestUpdate(); } }); } // Update incognito state. setIncognito(mTab.isIncognito()); } private void setIncognito(boolean incognito) { if (mIncognito == null || mIncognito != incognito) { mIncognito = incognito; mCardView.setBackgroundTintList( ColorStateList.valueOf( TabUiThemeUtil.getTabStripContainerColor( getContext(), mIncognito, /* foreground= */ true, /* isReordering= */ false, /* isPlaceholder= */ false, /* isHovered= */ false))); @ColorInt int textColor = AppCompatResources.getColorStateList( getContext(), mIncognito ? R.color.compositor_tab_title_bar_text_incognito : R.color.compositor_tab_title_bar_text) .getDefaultColor(); mTitleView.setTextColor(textColor); mThumbnailView.updateThumbnailPlaceholder(mIncognito, false); } } protected Tab getTabForTesting() { return mTab; } }
// Copyright 2020 The Prometheus Authors // 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 expfmt import ( "bytes" "math" "strings" "testing" "time" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/model" ) func TestCreateOpenMetrics(t *testing.T) { openMetricsTimestamp := timestamppb.New(time.Unix(12345, 600000000)) if err := openMetricsTimestamp.CheckValid(); err != nil { t.Error(err) } oldDefaultScheme := model.NameEscapingScheme model.NameEscapingScheme = model.NoEscaping defer func() { model.NameEscapingScheme = oldDefaultScheme }() scenarios := []struct { in *dto.MetricFamily options []EncoderOption out string }{ // 0: Counter, timestamp given, no _total suffix. { in: &dto.MetricFamily{ Name: proto.String("name"), Help: proto.String("two-line\n doc str\\ing"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ { Label: []*dto.LabelPair{ { Name: proto.String("labelname"), Value: proto.String("val1"), }, { Name: proto.String("basename"), Value: proto.String("basevalue"), }, }, Counter: &dto.Counter{ Value: proto.Float64(42), }, }, { Label: []*dto.LabelPair{ { Name: proto.String("labelname"), Value: proto.String("val2"), }, { Name: proto.String("basename"), Value: proto.String("basevalue"), }, }, Counter: &dto.Counter{ Value: proto.Float64(.23), }, TimestampMs: proto.Int64(1234567890), }, }, }, out: `# HELP name two-line\n doc str\\ing # TYPE name unknown name{labelname="val1",basename="basevalue"} 42.0 name{labelname="val2",basename="basevalue"} 0.23 1.23456789e+06 `, }, // 1: Dots in name { in: &dto.MetricFamily{ Name: proto.String("name.with.dots"), Help: proto.String("boring help"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ { Label: []*dto.LabelPair{ { Name: proto.String("labelname"), Value: proto.String("val1"), }, { Name: proto.String("basename"), Value: proto.String("basevalue"), }, }, Counter: &dto.Counter{ Value: proto.Float64(42), }, }, { Label: []*dto.LabelPair{ { Name: proto.String("labelname"), Value: proto.String("val2"), }, { Name: proto.String("basename"), Value: proto.String("basevalue"), }, }, Counter: &dto.Counter{ Value: proto.Float64(.23), }, TimestampMs: proto.Int64(1234567890), }, }, }, out: `# HELP "name.with.dots" boring help # TYPE "name.with.dots" unknown {"name.with.dots",labelname="val1",basename="basevalue"} 42.0 {"name.with.dots",labelname="val2",basename="basevalue"} 0.23 1.23456789e+06 `, }, // 2: Dots in name, no labels { in: &dto.MetricFamily{ Name: proto.String("name.with.dots"), Help: proto.String("boring help"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ { Counter: &dto.Counter{ Value: proto.Float64(42), }, }, { Counter: &dto.Counter{ Value: proto.Float64(.23), }, TimestampMs: proto.Int64(1234567890), }, }, }, out: `# HELP "name.with.dots" boring help # TYPE "name.with.dots" unknown {"name.with.dots"} 42.0 {"name.with.dots"} 0.23 1.23456789e+06 `, }, // 3: Gauge, some escaping required, +Inf as value, multi-byte characters in label values. { in: &dto.MetricFamily{ Name: proto.String("gauge_name"), Help: proto.String("gauge\ndoc\nstr\"ing"), Type: dto.MetricType_GAUGE.Enum(), Metric: []*dto.Metric{ { Label: []*dto.LabelPair{ { Name: proto.String("name_1"), Value: proto.String("val with\nnew line"), }, { Name: proto.String("name_2"), Value: proto.String("val with \\backslash and \"quotes\""), }, }, Gauge: &dto.Gauge{ Value: proto.Float64(math.Inf(+1)), }, }, { Label: []*dto.LabelPair{ { Name: proto.String("name_1"), Value: proto.String("Björn"), }, { Name: proto.String("name_2"), Value: proto.String("佖佥"), }, }, Gauge: &dto.Gauge{ Value: proto.Float64(3.14e42), }, }, }, }, out: `# HELP gauge_name gauge\ndoc\nstr\"ing # TYPE gauge_name gauge gauge_name{name_1="val with\nnew line",name_2="val with \\backslash and \"quotes\""} +Inf gauge_name{name_1="Björn",name_2="佖佥"} 3.14e+42 `, }, // 4: Gauge, utf-8, some escaping required, +Inf as value, multi-byte characters in label values. { in: &dto.MetricFamily{ Name: proto.String("gauge.name\""), Help: proto.String("gauge\ndoc\nstr\"ing"), Type: dto.MetricType_GAUGE.Enum(), Metric: []*dto.Metric{ { Label: []*dto.LabelPair{ { Name: proto.String("name.1"), Value: proto.String("val with\nnew line"), }, { Name: proto.String("name*2"), Value: proto.String("val with \\backslash and \"quotes\""), }, }, Gauge: &dto.Gauge{ Value: proto.Float64(math.Inf(+1)), }, }, { Label: []*dto.LabelPair{ { Name: proto.String("name.1"), Value: proto.String("Björn"), }, { Name: proto.String("name*2"), Value: proto.String("佖佥"), }, }, Gauge: &dto.Gauge{ Value: proto.Float64(3.14e42), }, }, }, }, out: `# HELP "gauge.name\"" gauge\ndoc\nstr\"ing # TYPE "gauge.name\"" gauge {"gauge.name\"","name.1"="val with\nnew line","name*2"="val with \\backslash and \"quotes\""} +Inf {"gauge.name\"","name.1"="Björn","name*2"="佖佥"} 3.14e+42 `, }, // 5: Unknown, no help, one sample with no labels and -Inf as value, another sample with one label. { in: &dto.MetricFamily{ Name: proto.String("unknown_name"), Type: dto.MetricType_UNTYPED.Enum(), Metric: []*dto.Metric{ { Untyped: &dto.Untyped{ Value: proto.Float64(math.Inf(-1)), }, }, { Label: []*dto.LabelPair{ { Name: proto.String("name_1"), Value: proto.String("value 1"), }, }, Untyped: &dto.Untyped{ Value: proto.Float64(-1.23e-45), }, }, }, }, out: `# TYPE unknown_name unknown unknown_name -Inf unknown_name{name_1="value 1"} -1.23e-45 `, }, // 6: Summary. { in: &dto.MetricFamily{ Name: proto.String("summary_name"), Help: proto.String("summary docstring"), Type: dto.MetricType_SUMMARY.Enum(), Metric: []*dto.Metric{ { Summary: &dto.Summary{ SampleCount: proto.Uint64(42), SampleSum: proto.Float64(-3.4567), Quantile: []*dto.Quantile{ { Quantile: proto.Float64(0.5), Value: proto.Float64(-1.23), }, { Quantile: proto.Float64(0.9), Value: proto.Float64(.2342354), }, { Quantile: proto.Float64(0.99), Value: proto.Float64(0), }, }, CreatedTimestamp: openMetricsTimestamp, }, }, { Label: []*dto.LabelPair{ { Name: proto.String("name_1"), Value: proto.String("value 1"), }, { Name: proto.String("name_2"), Value: proto.String("value 2"), }, }, Summary: &dto.Summary{ SampleCount: proto.Uint64(4711), SampleSum: proto.Float64(2010.1971), Quantile: []*dto.Quantile{ { Quantile: proto.Float64(0.5), Value: proto.Float64(1), }, { Quantile: proto.Float64(0.9), Value: proto.Float64(2), }, { Quantile: proto.Float64(0.99), Value: proto.Float64(3), }, }, CreatedTimestamp: openMetricsTimestamp, }, }, }, }, options: []EncoderOption{WithCreatedLines()}, out: `# HELP summary_name summary docstring # TYPE summary_name summary summary_name{quantile="0.5"} -1.23 summary_name{quantile="0.9"} 0.2342354 summary_name{quantile="0.99"} 0.0 summary_name_sum -3.4567 summary_name_count 42 summary_name_created 12345.6 summary_name{name_1="value 1",name_2="value 2",quantile="0.5"} 1.0 summary_name{name_1="value 1",name_2="value 2",quantile="0.9"} 2.0 summary_name{name_1="value 1",name_2="value 2",quantile="0.99"} 3.0 summary_name_sum{name_1="value 1",name_2="value 2"} 2010.1971 summary_name_count{name_1="value 1",name_2="value 2"} 4711 summary_name_created{name_1="value 1",name_2="value 2"} 12345.6 `, }, // 7: Histogram { in: &dto.MetricFamily{ Name: proto.String("request_duration_microseconds"), Help: proto.String("The response latency."), Type: dto.MetricType_HISTOGRAM.Enum(), Unit: proto.String("microseconds"), Metric: []*dto.Metric{ { Histogram: &dto.Histogram{ SampleCount: proto.Uint64(2693), SampleSum: proto.Float64(1756047.3), Bucket: []*dto.Bucket{ { UpperBound: proto.Float64(100), CumulativeCount: proto.Uint64(123), }, { UpperBound: proto.Float64(120), CumulativeCount: proto.Uint64(412), }, { UpperBound: proto.Float64(144), CumulativeCount: proto.Uint64(592), }, { UpperBound: proto.Float64(172.8), CumulativeCount: proto.Uint64(1524), }, { UpperBound: proto.Float64(math.Inf(+1)), CumulativeCount: proto.Uint64(2693), }, }, CreatedTimestamp: openMetricsTimestamp, }, }, }, }, options: []EncoderOption{WithCreatedLines(), WithUnit()}, out: `# HELP request_duration_microseconds The response latency. # TYPE request_duration_microseconds histogram # UNIT request_duration_microseconds microseconds request_duration_microseconds_bucket{le="100.0"} 123 request_duration_microseconds_bucket{le="120.0"} 412 request_duration_microseconds_bucket{le="144.0"} 592 request_duration_microseconds_bucket{le="172.8"} 1524 request_duration_microseconds_bucket{le="+Inf"} 2693 request_duration_microseconds_sum 1.7560473e+06 request_duration_microseconds_count 2693 request_duration_microseconds_created 12345.6 `, }, // 8: Histogram with missing +Inf bucket. { in: &dto.MetricFamily{ Name: proto.String("request_duration_microseconds"), Help: proto.String("The response latency."), Type: dto.MetricType_HISTOGRAM.Enum(), Unit: proto.String("microseconds"), Metric: []*dto.Metric{ { Histogram: &dto.Histogram{ SampleCount: proto.Uint64(2693), SampleSum: proto.Float64(1756047.3), Bucket: []*dto.Bucket{ { UpperBound: proto.Float64(100), CumulativeCount: proto.Uint64(123), }, { UpperBound: proto.Float64(120), CumulativeCount: proto.Uint64(412), }, { UpperBound: proto.Float64(144), CumulativeCount: proto.Uint64(592), }, { UpperBound: proto.Float64(172.8), CumulativeCount: proto.Uint64(1524), }, }, }, }, }, }, out: `# HELP request_duration_microseconds The response latency. # TYPE request_duration_microseconds histogram request_duration_microseconds_bucket{le="100.0"} 123 request_duration_microseconds_bucket{le="120.0"} 412 request_duration_microseconds_bucket{le="144.0"} 592 request_duration_microseconds_bucket{le="172.8"} 1524 request_duration_microseconds_bucket{le="+Inf"} 2693 request_duration_microseconds_sum 1.7560473e+06 request_duration_microseconds_count 2693 `, }, // 9: Histogram with missing +Inf bucket but with different exemplars. { in: &dto.MetricFamily{ Name: proto.String("request_duration_microseconds"), Help: proto.String("The response latency."), Type: dto.MetricType_HISTOGRAM.Enum(), Metric: []*dto.Metric{ { Histogram: &dto.Histogram{ SampleCount: proto.Uint64(2693), SampleSum: proto.Float64(1756047.3), Bucket: []*dto.Bucket{ { UpperBound: proto.Float64(100), CumulativeCount: proto.Uint64(123), }, { UpperBound: proto.Float64(120), CumulativeCount: proto.Uint64(412), Exemplar: &dto.Exemplar{ Label: []*dto.LabelPair{ { Name: proto.String("foo"), Value: proto.String("bar"), }, }, Value: proto.Float64(119.9), Timestamp: openMetricsTimestamp, }, }, { UpperBound: proto.Float64(144), CumulativeCount: proto.Uint64(592), Exemplar: &dto.Exemplar{ Label: []*dto.LabelPair{ { Name: proto.String("foo"), Value: proto.String("baz"), }, { Name: proto.String("dings"), Value: proto.String("bums"), }, }, Value: proto.Float64(140.14), }, }, { UpperBound: proto.Float64(172.8), CumulativeCount: proto.Uint64(1524), }, }, }, }, }, }, out: `# HELP request_duration_microseconds The response latency. # TYPE request_duration_microseconds histogram request_duration_microseconds_bucket{le="100.0"} 123 request_duration_microseconds_bucket{le="120.0"} 412 # {foo="bar"} 119.9 12345.6 request_duration_microseconds_bucket{le="144.0"} 592 # {foo="baz",dings="bums"} 140.14 request_duration_microseconds_bucket{le="172.8"} 1524 request_duration_microseconds_bucket{le="+Inf"} 2693 request_duration_microseconds_sum 1.7560473e+06 request_duration_microseconds_count 2693 `, }, // 10: Simple Counter. { in: &dto.MetricFamily{ Name: proto.String("foos_total"), Help: proto.String("Number of foos."), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ { Counter: &dto.Counter{ Value: proto.Float64(42), CreatedTimestamp: openMetricsTimestamp, }, }, }, }, options: []EncoderOption{WithCreatedLines()}, out: `# HELP foos Number of foos. # TYPE foos counter foos_total 42.0 foos_created 12345.6 `, }, // 11: Simple Counter without created line. { in: &dto.MetricFamily{ Name: proto.String("foos_total"), Help: proto.String("Number of foos."), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ { Counter: &dto.Counter{ Value: proto.Float64(42), CreatedTimestamp: openMetricsTimestamp, }, }, }, }, out: `# HELP foos Number of foos. # TYPE foos counter foos_total 42.0 `, }, // 12: No metric. { in: &dto.MetricFamily{ Name: proto.String("name_total"), Help: proto.String("doc string"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{}, }, out: `# HELP name doc string # TYPE name counter `, }, // 13: Simple Counter with exemplar that has empty label set: // ignore the exemplar, since OpenMetrics spec requires labels. { in: &dto.MetricFamily{ Name: proto.String("foos_total"), Help: proto.String("Number of foos."), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ { Counter: &dto.Counter{ Value: proto.Float64(42), Exemplar: &dto.Exemplar{ Label: []*dto.LabelPair{}, Value: proto.Float64(1), Timestamp: openMetricsTimestamp, }, }, }, }, }, out: `# HELP foos Number of foos. # TYPE foos counter foos_total 42.0 `, }, // 14: No metric plus unit. { in: &dto.MetricFamily{ Name: proto.String("name_seconds_total"), Help: proto.String("doc string"), Type: dto.MetricType_COUNTER.Enum(), Unit: proto.String("seconds"), Metric: []*dto.Metric{}, }, options: []EncoderOption{WithUnit()}, out: `# HELP name_seconds doc string # TYPE name_seconds counter # UNIT name_seconds seconds `, }, // 15: Histogram plus unit, but unit not opted in. { in: &dto.MetricFamily{ Name: proto.String("request_duration_microseconds"), Help: proto.String("The response latency."), Type: dto.MetricType_HISTOGRAM.Enum(), Unit: proto.String("microseconds"), Metric: []*dto.Metric{ { Histogram: &dto.Histogram{ SampleCount: proto.Uint64(2693), SampleSum: proto.Float64(1756047.3), Bucket: []*dto.Bucket{ { UpperBound: proto.Float64(100), CumulativeCount: proto.Uint64(123), }, { UpperBound: proto.Float64(120), CumulativeCount: proto.Uint64(412), }, { UpperBound: proto.Float64(144), CumulativeCount: proto.Uint64(592), }, { UpperBound: proto.Float64(172.8), CumulativeCount: proto.Uint64(1524), }, { UpperBound: proto.Float64(math.Inf(+1)), CumulativeCount: proto.Uint64(2693), }, }, }, }, }, }, out: `# HELP request_duration_microseconds The response latency. # TYPE request_duration_microseconds histogram request_duration_microseconds_bucket{le="100.0"} 123 request_duration_microseconds_bucket{le="120.0"} 412 request_duration_microseconds_bucket{le="144.0"} 592 request_duration_microseconds_bucket{le="172.8"} 1524 request_duration_microseconds_bucket{le="+Inf"} 2693 request_duration_microseconds_sum 1.7560473e+06 request_duration_microseconds_count 2693 `, }, // 16: No metric, unit opted in, no unit in name. { in: &dto.MetricFamily{ Name: proto.String("name_total"), Help: proto.String("doc string"), Type: dto.MetricType_COUNTER.Enum(), Unit: proto.String("seconds"), Metric: []*dto.Metric{}, }, options: []EncoderOption{WithUnit()}, out: `# HELP name_seconds doc string # TYPE name_seconds counter # UNIT name_seconds seconds `, }, // 17: No metric, unit opted in, BUT unit == nil. { in: &dto.MetricFamily{ Name: proto.String("name_total"), Help: proto.String("doc string"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{}, }, options: []EncoderOption{WithUnit()}, out: `# HELP name doc string # TYPE name counter `, }, // 18: Counter, timestamp given, unit opted in, _total suffix. { in: &dto.MetricFamily{ Name: proto.String("some_measure_total"), Help: proto.String("some testing measurement"), Type: dto.MetricType_COUNTER.Enum(), Unit: proto.String("seconds"), Metric: []*dto.Metric{ { Label: []*dto.LabelPair{ { Name: proto.String("labelname"), Value: proto.String("val1"), }, { Name: proto.String("basename"), Value: proto.String("basevalue"), }, }, Counter: &dto.Counter{ Value: proto.Float64(42), }, }, { Label: []*dto.LabelPair{ { Name: proto.String("labelname"), Value: proto.String("val2"), }, { Name: proto.String("basename"), Value: proto.String("basevalue"), }, }, Counter: &dto.Counter{ Value: proto.Float64(.23), }, TimestampMs: proto.Int64(1234567890), }, }, }, options: []EncoderOption{WithUnit()}, out: `# HELP some_measure_seconds some testing measurement # TYPE some_measure_seconds counter # UNIT some_measure_seconds seconds some_measure_seconds_total{labelname="val1",basename="basevalue"} 42.0 some_measure_seconds_total{labelname="val2",basename="basevalue"} 0.23 1.23456789e+06 `, }, } for i, scenario := range scenarios { out := bytes.NewBuffer(make([]byte, 0, len(scenario.out))) n, err := MetricFamilyToOpenMetrics(out, scenario.in, scenario.options...) if err != nil { t.Errorf("%d. error: %s", i, err) continue } if expected, got := len(scenario.out), n; expected != got { t.Errorf( "%d. expected %d bytes written, got %d", i, expected, got, ) } if expected, got := scenario.out, out.String(); expected != got { t.Errorf( "%d. expected out=%q, got %q", i, expected, got, ) } } } func BenchmarkOpenMetricsCreate(b *testing.B) { mf := &dto.MetricFamily{ Name: proto.String("request_duration_microseconds"), Help: proto.String("The response latency."), Type: dto.MetricType_HISTOGRAM.Enum(), Metric: []*dto.Metric{ { Label: []*dto.LabelPair{ { Name: proto.String("name_1"), Value: proto.String("val with\nnew line"), }, { Name: proto.String("name_2"), Value: proto.String("val with \\backslash and \"quotes\""), }, { Name: proto.String("name_3"), Value: proto.String("Just a quite long label value to test performance."), }, }, Histogram: &dto.Histogram{ SampleCount: proto.Uint64(2693), SampleSum: proto.Float64(1756047.3), Bucket: []*dto.Bucket{ { UpperBound: proto.Float64(100), CumulativeCount: proto.Uint64(123), }, { UpperBound: proto.Float64(120), CumulativeCount: proto.Uint64(412), }, { UpperBound: proto.Float64(144), CumulativeCount: proto.Uint64(592), }, { UpperBound: proto.Float64(172.8), CumulativeCount: proto.Uint64(1524), }, { UpperBound: proto.Float64(math.Inf(+1)), CumulativeCount: proto.Uint64(2693), }, }, }, }, { Label: []*dto.LabelPair{ { Name: proto.String("name_1"), Value: proto.String("Björn"), }, { Name: proto.String("name_2"), Value: proto.String("佖佥"), }, { Name: proto.String("name_3"), Value: proto.String("Just a quite long label value to test performance."), }, }, Histogram: &dto.Histogram{ SampleCount: proto.Uint64(5699), SampleSum: proto.Float64(49484343543.4343), Bucket: []*dto.Bucket{ { UpperBound: proto.Float64(100), CumulativeCount: proto.Uint64(120), }, { UpperBound: proto.Float64(120), CumulativeCount: proto.Uint64(412), }, { UpperBound: proto.Float64(144), CumulativeCount: proto.Uint64(596), }, { UpperBound: proto.Float64(172.8), CumulativeCount: proto.Uint64(1535), }, }, }, TimestampMs: proto.Int64(1234567890), }, }, } out := bytes.NewBuffer(make([]byte, 0, 1024)) for i := 0; i < b.N; i++ { _, err := MetricFamilyToOpenMetrics(out, mf) if err != nil { b.Fatal(err) } out.Reset() } } func TestOpenMetricsCreateError(t *testing.T) { scenarios := []struct { in *dto.MetricFamily err string }{ // 0: No metric name. { in: &dto.MetricFamily{ Help: proto.String("doc string"), Type: dto.MetricType_UNTYPED.Enum(), Metric: []*dto.Metric{ { Untyped: &dto.Untyped{ Value: proto.Float64(math.Inf(-1)), }, }, }, }, err: "MetricFamily has no name", }, // 1: Wrong type. { in: &dto.MetricFamily{ Name: proto.String("name"), Help: proto.String("doc string"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ { Untyped: &dto.Untyped{ Value: proto.Float64(math.Inf(-1)), }, }, }, }, err: "expected counter in metric", }, } for i, scenario := range scenarios { var out bytes.Buffer _, err := MetricFamilyToOpenMetrics(&out, scenario.in) if err == nil { t.Errorf("%d. expected error, got nil", i) continue } if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { t.Errorf( "%d. expected error starting with %q, got %q", i, expected, got, ) } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Move Div</title> <style> body{ font-family: Verdana, Geneva, Tahoma, sans-serif; } .wrapper { position: absolute; top: 10px; left: 10px; bottom: 10px; right: 10px; background-color: purple; display: flex; justify-content: space-evenly; align-items: baseline; padding-top: 15px; } #my-box { height: 50px; width: 50px; background-color: royalblue; border: 1px solid pink; position: absolute; } button { width: 20%; height: 50px; } </style> </head> <body> <div class="wrapper"> <button id="move-up">Move Up</button> <button id="move-down">Move Down</button> <button id="move-left">Move Left</button> <button id="move-right">Move Right</button> <div id="my-box"></div> </div> <script> 'use strict'; //global variables let box = document.getElementById('my-box'); box.style.top = '115px'; box.style.left = '100px'; function moveUp(){ const theTop = parseInt(box.style.top) //parseInt finds numeric value in the beginning eg 150px -> 150 box.style.top = (theTop - 10)+'px'; } function moveLeft(){ const theLeft = parseInt(box.style.left) box.style.left = (theLeft - 10)+'px'; } function moveRight(){ const theRight = parseInt(box.style.left) box.style.left = (theRight + 10)+'px'; } function moveDown(){ const theDown = parseInt(box.style.top) box.style.top = (theDown + 10)+'px'; } //eventlisteners document.querySelector('#move-up').onclick = moveUp; document.querySelector('#move-left').onclick = moveLeft; document.querySelector('#move-right').onclick = moveRight; document.querySelector('#move-down').onclick = moveDown; </script> </body> </html>
// // UIKit+ Factory.swift // // The MIT License (MIT) // // Copyright (c) 2019 Community Arch // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit // MARK: - UITableView + CellFactory public extension UITableView { /// возвращает повторно используемый объект ячейки табличного представления /// для указанного индикса, и добавляет его в таблицу. /// /// - Parameters: /// - factory: фабрика ячейки (объект содержащий бизнес логику заполнения ячейки) /// - indexPath: индекс пасс, указывающий местоположение ячейки /// - Returns: готовую ячейку для отображения в таблицу func dequeueReusableCell(with factory: AnyCellFactory, for indexPath: IndexPath) -> UITableViewCell { let cell = dequeueReusableCell(withIdentifier: factory.identifier, for: indexPath) factory.setup(cell) return cell } /// возвращает повторно используемый объект ячейки табличного представления /// для указанного индикса, и добавляет его в таблицу. /// /// - Parameter factory: фабрика создание разных тепов ячейк /// - Parameter indexPath: индекс пасс, указывающий местоположение ячейки func dequeueReusableCell(with factory: MultiCellTypeFactory, for indexPath: IndexPath) -> UITableViewCell { let cell = dequeueReusableCell(withIdentifier: factory.identifier, for: indexPath) factory.setup(cell) return cell } /// возвращает повторно используемый объект заголовок/нижний колонтитул /// табличного представления и добавляет его в таблицу. /// /// note: /// используя идентификатор вью вместе индекс пасс /// /// - Parameter factory: фабрика ячейки (объект содержащий бизнес логику заполнения ячейки) /// - Returns: объект со связанным идентификатором или nil, если на повторное использование такого объекта не существует. func dequeueReusableHeaderFooterView(with factory: AnyViewFactory) -> UITableViewHeaderFooterView? { let identifier = String(describing: type(of: factory).wrappedViewType) guard let header = dequeueReusableHeaderFooterView(withIdentifier: identifier) else { return nil } factory.setup(header) return header } /// регистрирует объект фабрики, содержащий бизнес логику заполнения /// ячейки. и под идентификатором совпадает с названием ячейки. /// /// - Parameters: /// - factory: фабрика ячейки (объект содержащий бизнес логику заполнения ячейки) /// - bundle: представление ресурсов, хранящихся на диске. func register(factory: AnyCellFactory.Type, bundle: Bundle? = nil) { let viewName = String(describing: factory.wrappedViewType) let nib = UINib(nibName: viewName, bundle: bundle) register(nib, forCellReuseIdentifier: viewName) } /// регистрирует объект фабрики, содержащий бизнес логику заполнения /// ячейки. и под идентификатором совпадает с названием ячейки. /// /// - Parameters: /// - factory: массив фабрик ячейки (объект содержащий бизнес логику заполнения ячейки) /// - bundle: представление ресурсов, хранящихся на диске. func register(factories: [AnyCellFactory.Type], bundle: Bundle? = nil) { factories.forEach { register(factory: $0, bundle: bundle) } } /// регистрирует объект фабрики, содержащий бизнес логику заполнения /// ячейки. и под идентификатором совпадает с названием ячейки. /// /// - Parameter factory: фабрика создание разных тепов ячейк /// - Parameter bundle: представление ресурсов, хранящихся на диске. func register(factory: MultiCellTypeFactory.Type, bundle: Bundle? = nil) { factory.factories.values.forEach { register(factory: $0, bundle: bundle) } } /// регистрирует объект фабрики заголовок/нижний колонтитул, содержащий бизнес логику заполнения /// заголовок/нижний колонтитул. и под идентификатором совпадает с названием заголовок/нижний колонтитул. /// /// - Parameter factory: фабрика вью func registerHeaderFooter(factory: AnyViewFactory.Type) { registerHeaderFooter(factory: factory, bundle: nil) } /// регистрирует объекты фабрик заголовок/нижний колонтитул, содержащий бизнес логику заполнения /// заголовок/нижний колонтитул. и под идентификатором совпадает с названием заголовок/нижний колонтитул. /// /// - Parameter factories: массив фабрик ячейки (объект содержащий бизнес логику заполнения ячейки) func registerHeaderFooter(factories: [AnyViewFactory.Type]) { registerHeaderFooter(factories: factories, bundle: nil) } /// регистрирует объект фабрики заголовок/нижний колонтитул, содержащий бизнес логику заполнения /// заголовок/нижний колонтитул. и под идентификатором совпадает с названием заголовок/нижний колонтитул. /// /// - Parameters: /// - factory: фабрика вью /// - bundle: представление ресурсов, хранящихся на диске. func registerHeaderFooter(factory: AnyViewFactory.Type, bundle: Bundle?) { let id = String(describing: factory.wrappedViewType) let nib = UINib(nibName: id, bundle: bundle) register(nib, forHeaderFooterViewReuseIdentifier: id) } /// регистрирует объекты фабрик заголовков/нижний колонтитулов, содержащий бизнес логику заполнения /// заголовок/нижний колонтитул. и под идентификатором совпадает с названием заголовок/нижний колонтитул. /// /// - Parameters: /// - factories: массив фабрик вью /// - bundle: представление ресурсов, хранящихся на диске. func registerHeaderFooter(factories: [AnyViewFactory.Type], bundle: Bundle?) { factories.forEach { registerHeaderFooter(factory: $0, bundle: bundle) } } } // MARK: - UICollectionView + CellFactory public extension UICollectionView { /// возвращает многократно используемый объект ячейки, расположенный по его идентификатору /// /// - Parameters: /// - factory: фабрика ячейки (объект содержащий бизнес логику заполнения ячейки) /// - indexPath: indexpath, указывающий местоположение ячейки /// - Returns: готовую ячейку для отображения func dequeueReusableCell(with factory: AnyCellFactory, for indexPath: IndexPath) -> UICollectionViewCell { let cell = dequeueReusableCell(withReuseIdentifier: factory.identifier, for: indexPath) factory.setup(cell) return cell } /// возвращает многократно используемый объект ячейки, расположенный по его идентификатору /// /// - Parameter factory: фабрика создание разных тепов ячейк /// - Parameter indexPath: indexpath, указывающий местоположение ячейки func dequeueReusableCell(with factory: MultiCellTypeFactory, for indexPath: IndexPath) -> UICollectionViewCell { let cell = dequeueReusableCell(withReuseIdentifier: factory.identifier, for: indexPath) factory.setup(cell) return cell } /// возвращает многократно используемый объект view, расположенный по его идентификатору /// /// - Parameters: /// - factory: фабрика вью (объект содержащий бизнес логику заполнения вью) /// - indexPath: indexpath, указывающий местоположение вью /// - Returns: готовую вью для отображения func dequeueReusableSupplementaryView(with factory: AnyReusableSupplementaryViewFactory, for indexPath: IndexPath) -> UICollectionReusableView { let view = dequeueReusableSupplementaryView(ofKind: type(of: factory).viewKind, withReuseIdentifier: factory.reuseIdentifier, for: indexPath) factory.setup(view) return view } /// регистрирует объект фабрики, содержащий бизнес логику заполнения /// ячейки. и под идентификатором совпадает с названием ячейки. /// /// - Parameters: /// - factory: фабрика ячейки (объект содержащий бизнес логику заполнения ячейки) /// - bundle: представление ресурсов, хранящихся на диске. func register(factory: AnyCellFactory.Type, bundle: Bundle? = nil) { let viewName = String(describing: factory.wrappedViewType) let nib = UINib(nibName: viewName, bundle: bundle) register(nib, forCellWithReuseIdentifier: viewName) } /// регистрирует объеки фабрики, содержащий бизнес логику заполнения /// ячейки. и под идентификатором совпадает с названием ячейки. /// /// - Parameters: /// - factories: массив фабрик ячейки (объект содержащий бизнес логику заполнения ячейки) /// - bundle: представление ресурсов, хранящихся на диске. func register(factories: [AnyCellFactory.Type], bundle: Bundle? = nil) { factories.forEach { register(factory: $0, bundle: bundle) } } /// регистрирует объеки фабрики, содержащий бизнес логику заполнения /// ячейки. и под идентификатором совпадает с названием ячейки. /// /// - Parameter factory: фабрика создание разных тепов ячейк /// - Parameter bundle: представление ресурсов, хранящихся на диске. func register(factory: MultiCellTypeFactory.Type, bundle: Bundle? = nil) { factory.factories.values.forEach { register(factory: $0, bundle: bundle) } } /// регистрирует объект фабрики для использования при создании дополнительных представлений /// /// - Parameters: /// - factory: фабрика ячейки (объект содержащий бизнес логику заполнения ячейки) /// - elementKind: вид дополнительного представления для создания. func register(factory: AnyViewFactory.Type, forSupplementaryViewOfKind elementKind: String, bundle: Bundle? = nil) { let viewName = String(describing: factory.wrappedViewType) let nib = UINib(nibName: viewName, bundle: bundle) register(nib, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: viewName) } }
<!DOCTYPE html> <html> <head> <title>To Do List</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body{ background-image:url('to do list.jpg'); background-repeat:no-repeat; background-attachment: fixed; background-size:100% 100% ; } body { margin: 0; padding: 0; min-width: 250px; } /* Include the padding and border in an element's total width and height */ * { box-sizing: border-box; } /* Remove margins and padding from the list */ ul { margin: 0; padding: 0; } /* Style the list items */ ul li { cursor: pointer; position: relative; padding: 12px 8px 12px 40px; list-style-type: none; background: #eee; font-size: 18px; transition: 0.2s; /* make the list items unselectable */ -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } /* Set all odd list items to a different color (zebra-stripes) */ ul li:nth-child(odd) { background: #f9f9f9; } /* Darker background-color on hover */ ul li:hover { background:rgba(48, 158, 185, 0.537); } /* When clicked on, add a background color and strike out text */ ul li.checked { background: rgba(51, 132, 134, 0.671); color: white; text-decoration: line-through; } /* Add a "checked" mark when clicked on */ ul li.checked::before { content: ''; position: absolute; border-color: #fff; border-style: solid; border-width: 0 2px 2px 0; top: 10px; left: 16px; transform: rotate(45deg); height: 15px; width: 7px; } /* Style the close button */ .close { position: absolute; right: 0; top: 0; padding: 12px 16px 12px 16px; } .close:hover { background-color: #f44336; color: grey; } /* Style the header */ .header { background-image: radial-gradient(#2CEAA2,#39CCF4); padding: 30px 40px; color: white; text-align: center; } /* Clear floats after the header */ .header:after { content: ""; display: table; clear: both; } /* Style the input */ input { margin: 0; border: none; border-radius: 0; width: 75%; padding: 10px; float: left; font-size: 16px; } /* Style the "Add" button */ .addBtn { padding: 10px; width: 25%; background: #F1F15F; color: black; float: left; text-align: center; font-weight:bold; font-size: 16px; cursor: pointer; transition: 0.3s; border-radius: 0; } .addBtn:hover { background-color: #bbb; } </style> </head> <body> <div id="myDIV" class="header"> <h1 style="margin:2px" >TO DO LIST</h1> <input type="text" id="myInput" placeholder="Enter your Task.."> <span onclick="newElement()" class="addBtn">Add</span> </div> <ul id="myUL"> </ul> <script> // Create a "close" button and append it to each list item var myNodelist = document.getElementsByTagName("LI"); var i; for (i = 0; i < myNodelist.length; i++) { var span = document.createElement("SPAN"); var txt = document.createTextNode("\u00D7"); span.className = "close"; span.appendChild(txt); myNodelist[i].appendChild(span); } // Click on a close button to hide the current list item var close = document.getElementsByClassName("close"); var i; for (i = 0; i < close.length; i++) { close[i].onclick = function() { var div = this.parentElement; div.style.display = "none"; } } // Add a "checked" symbol when clicking on a list item var list = document.querySelector('ul'); list.addEventListener('click', function(ev) { if (ev.target.tagName === 'LI') { ev.target.classList.toggle('checked'); } }, false); // Create a new list item when clicking on the "Add" button function newElement() { var li = document.createElement("li"); var inputValue = document.getElementById("myInput").value; var t = document.createTextNode(inputValue); li.appendChild(t); if (inputValue === '') { alert("You must write something!"); } else { document.getElementById("myUL").appendChild(li); } document.getElementById("myInput").value = ""; var span = document.createElement("SPAN"); var txt = document.createTextNode("\u00D7"); span.className = "close"; span.appendChild(txt); li.appendChild(span); for (i = 0; i < close.length; i++) { close[i].onclick = function() { var div = this.parentElement; div.style.display = "none"; } } } </script> </body> </html>
import React, { useEffect, useState } from "react"; import { Container, Box, Image, Heading, Center, Flex, Grid, GridItem, } from "@chakra-ui/react"; import { useParams } from "react-router-dom"; import axios from "axios"; import { BASE_API, URL_Image } from "../../../utils/constants"; export default function HeaderSection() { const params = useParams(); const [name, setName] = useState(""); const [image, setImage] = useState(""); useEffect(() => { const GET_USER = `${BASE_API}user/${params.id}`; axios .get(GET_USER) .then((res) => { setName(res.data.data.name); setImage(res.data.data.profile); }) .catch((err) => { console.log(err); }); }); return ( <Container bgColor={"primary.100"} pt={"16"} maxW={"full"} h={"40vh"}> <Center> <Grid gap={{ base: "5", lg: "90" }} h={"40vh"} templateColumns={{ lg: "repeat(1, 1fr)" }} justifyContent="center" > <GridItem margin={{ base: "5", lg: "auto 0" }} my={"auto"}> <Image src={URL_Image + image} width={["14", "20", "28"]} height={["14", "20", "28"]} rounded={"full"} mx={"auto"} /> <Heading color={"white"} fontWeight={"semibold"} textTransform="capitalize" mt={["2", "4"]} > {name} </Heading> </GridItem> </Grid> </Center> </Container> ); }
import React, { useState } from 'react'; import styled from 'styled-components'; import theme from 'styles/theme'; import { useRouter } from 'next/router'; import en from 'locales/en'; import vn from 'locales/vn'; const StyledViewMore = styled.div<StyledShowProps>` text-align: center; color: ${theme.blue}; cursor: pointer; position: absolute; bottom: 0px; font-weight: bold; width: 100%; background-color: rgba(255, 255, 255, 0.9); padding-top: ${(props) => (props.showMore ? '0px' : ' 20px')}; span:hover { opacity: 0.8; } `; interface StyledShowProps { showMore: boolean; } const StyledShow = styled.div<StyledShowProps>` height: ${(props) => (props.showMore ? '100%' : ' 500px')}; overflow: hidden; position: relative; padding-bottom: 30px; `; interface ShowTextProps { text: React.ReactNode; additionalAttr: { code: string; label: string; value: string }[]; } const ShowText: React.FC<ShowTextProps> = ({ text, additionalAttr }) => { const [showMore, setShowMore] = useState(false); const router = useRouter(); const { locale } = router; const t = locale === 'en' ? en : vn; return ( <StyledShow showMore={showMore}> <div className="d-flex justify-content-center"> <div className="d-flex align-items-center flex-column w-50-responsive mb-5 mt-3"> {(additionalAttr ?? []).map((item) => ( <div className="d-flex w-100 item-attribute" key={item.code}> <div className="w-25">{item.label}</div> <div className="w-75">{item.value}</div> </div> ))} </div> </div> <div>{text}</div> <StyledViewMore onClick={() => setShowMore(!showMore)} showMore={showMore} > <span>{showMore ? t.showLess : t.showMore}</span> </StyledViewMore> </StyledShow> ); }; export default ShowText;
package pageObjects.nopCommerce; import org.openqa.selenium.WebDriver; import commons.BasePage; import pageUIs.nopCommerce.RegisterPageUI; public class UserRegisterPageObject extends BasePage{ private WebDriver driver; public UserRegisterPageObject(WebDriver driver) { this.driver = driver; } public void inputToFirstNameTextbox(String firstName) { waitForElementVisible(driver, RegisterPageUI.FIRSTNAME_TEXTBOX); sendkeyToElement(driver, RegisterPageUI.FIRSTNAME_TEXTBOX, firstName); } public void inputToLastNameTextbox(String lastName) { waitForElementVisible(driver, RegisterPageUI.LASTNAME_TEXTBOX); sendkeyToElement(driver, RegisterPageUI.LASTNAME_TEXTBOX, lastName); } public void inputToEmailTextbox(String emailAddress) { waitForElementVisible(driver, RegisterPageUI.EMAIL_TEXTBOX); sendkeyToElement(driver, RegisterPageUI.EMAIL_TEXTBOX, emailAddress); } public String getEmailText() { waitForElementVisible(driver, RegisterPageUI.EMAIL_TEXTBOX); return getElementText(driver, RegisterPageUI.EMAIL_TEXTBOX); } public void inputToPasswordTextbox(String password) { waitForElementVisible(driver, RegisterPageUI.PASSWORD_TEXTBOX); sendkeyToElement(driver, RegisterPageUI.PASSWORD_TEXTBOX, password); } public String getPasswordTex() { waitForElementVisible(driver, RegisterPageUI.PASSWORD_TEXTBOX); return getElementText(driver, RegisterPageUI.PASSWORD_TEXTBOX); } public void inputToConfirmPasswordTextbox(String confirmPassword) { waitForElementVisible(driver, RegisterPageUI.CONFIRM_PASSWORD_TEXTBOX); sendkeyToElement(driver, RegisterPageUI.CONFIRM_PASSWORD_TEXTBOX, confirmPassword); } public void clickToRegisterButton() { waitForElementClickable(driver, RegisterPageUI.REGISTER_BUTTON); clickToElement(driver, RegisterPageUI.REGISTER_BUTTON); } public String getErrorMessageAtFirstnameTextbox() { waitForElementVisible(driver, RegisterPageUI.FIRST_NAME_ERROR_MESSAGE); return getElementText(driver, RegisterPageUI.FIRST_NAME_ERROR_MESSAGE); } public String getErrorMessageAtLastnameTextbox() { waitForElementVisible(driver, RegisterPageUI.LAST_NAME_ERROR_MESSAGE); return getElementText(driver, RegisterPageUI.LAST_NAME_ERROR_MESSAGE); } public String getErrorMessageAtEmailTextbox() { waitForElementVisible(driver, RegisterPageUI.EMAIL_ERROR_MESSAGE); return getElementText(driver, RegisterPageUI.EMAIL_ERROR_MESSAGE); } public String getErrorMessageAtPasswordTextbox() { waitForElementVisible(driver, RegisterPageUI.PASSWORD_ERROR_MESSAGE); return getElementText(driver, RegisterPageUI.PASSWORD_ERROR_MESSAGE); } public String getErrorMessageAtConfirmPasswordTextbox() { waitForElementVisible(driver, RegisterPageUI.CONFRIM_PASSWORD_ERROR_MESSAGE); return getElementText(driver, RegisterPageUI.CONFRIM_PASSWORD_ERROR_MESSAGE); } public String getRegisterSuccessMessage() { waitForElementVisible(driver, RegisterPageUI.REGISTER_SUCCESS_MESSAGE); return getElementText(driver, RegisterPageUI.REGISTER_SUCCESS_MESSAGE); } public UserHomePageObject clickToLogoutLink() { waitForElementClickable(driver, RegisterPageUI.LOGOUT_BUTTON); clickToElement(driver, RegisterPageUI.LOGOUT_BUTTON); return new PageGeneratorManager().getUserHomePage(driver); } public String getErrorExistingEmailMessage() { waitForElementVisible(driver, RegisterPageUI.EXISTING_EMAIL_ERROR_MESSAGE); return getElementText(driver, RegisterPageUI.EXISTING_EMAIL_ERROR_MESSAGE); } public String getSuccessMessageAtEmailTextbox() { // TODO Auto-generated method stub return null; } }
// 定义一个名为 button-counter 的新组件 Vue.component('button-counter', { data: function () {//注意:一个组件的 data 选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝 return { count: 0 } }, template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>' }) 组件是可复用的 Vue 实例,且带有一个名字 <div id="components-demo"> <button-counter></button-counter> <button-counter></button-counter> <button-counter></button-counter> </div> new Vue({ el: '#components-demo' }) 父子组件 一.全局组件 index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>vueproject</title> </head> <body> <!--留坑--> <div id="app"></div> <!-- built files will be auto injected --> </body> </html> 2.main.js import Vue from 'vue' import App from './App' //引入组件作为全局组件 ,使用更为方便,不需要声明,直接用vue.component('组件名',组件对象) import headerVue from "./components/header" import bodyVue from "./components/body" import footerVue from "./components/footer" //声明全局组件 Vue.component('headerVue', headerVue); Vue.component('bodyVue', bodyVue); Vue.component('footerVue', footerVue); new Vue({ el: '#app', //全局组件时用 render:c=>c(App) }) 3.App.vue <!--App.vue组件使用头组件,使用中组件,使用底组件 --> <!-- 谁用谁就是 父组件; 谁被用谁就是子 组件--> <template> <div> <header-vue param1="大大"></header-vue> <body-Vue :param2="param22"></body-Vue> <footer-Vue></footer-Vue> </div> </template> <script> export default { data(){ return{ param22:'我是param22哈哈' } }, methods:{}, } </script> <style> </style> 4.子组件 header.vue: ------接收父组件的常量 <template> <div> 我是{{param1}}头部 </div> </template> <script > export default{ data(){ return{ } }, methods:{ }, //声明根属性props,接收父组件的常量值 props:['param1'] } </script> <style scoped> div{ background-color: green; height:200px; } </style> body.vue:---接收父组件的变量值 <template> <div> 我是中间部,接收父组件的变量值{{param2}} </div> </template> <script > export default{ data(){ return{ } }, methods:{ }, //声明根属性props,接收父组件的值 props:['param2'] } </script> <style scoped> div{ background-color: royalblue; height:200px; } </style> 二:父子组件(局部) 1.index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>vueproject</title> </head> <body> <!--留坑--> <div id="app"></div> <!-- built files will be auto injected --> </body> </html> 2.main.js: import Vue from 'vue' import App from './App' new Vue({//父子组件时用 el: '#app', template: '<App/>', components: { App } }) 3.App.vue <!--App.vue组件使用头组件,使用中组件,使用底组件 --> <!-- 谁用谁就是 父组件; 谁被用谁就是子 组件--> <template> <div> <header-vue param1="大大"></header-vue> <body-Vue :param2="param22"></body-Vue> <footer-Vue></footer-Vue> </div> </template> <script> //父子组件使用,使用的是父,被用的是子,在main.js里面为全局 //父需要声明子组件,引入子组件对象 import 子组件对象 from "./xxx.vue"; import headerVue from "./components/header" import bodyVue from "./components/body" import footerVue from "./components/footer" export default { data(){ return{ param22:'我是param22哈哈' } }, methods:{}, //父子组件使用必须声明 components:{ //组件名(自己定义,在模板中使用) : 组件对象(import 后面的那个值) headerVue:headerVue, bodyVue, footerVue, } } </script> <style> </style> 4.子组件 header.vue: <template> <div> 我是{{param1}}头部 </div> </template> <script > export default{ data(){ return{ } }, methods:{ }, //接收父组件的值,在页面中{{param1}} props:['param1'] } </script> <style scoped> div{ background-color: green; height:200px; } </style> body.vue: <template> <div> 我是中间部,接收父组件的值{{param2}} <button @click="show"> 从js中获取父组件值</button> </div> </template> <script > export default{ data(){ return{ } }, methods:{ show(){ alert(this.param2) } }, //接收父组件的值再页面中世界使用{{param2}} ,在js中 使用this.param2 props:['param2'] } </script> <style scoped> div{ background-color: royalblue; height:200px; } </style>
/* GameBase.h Author: Tong Wu Email: [email protected] Purpose: Declaration for all the functions and member variables for the Game base class */ #pragma once #include "helper.h" class GameBase{ public: //this function will prints the game board and repeatedly calls turn() done() and draw() virtual int play(); static GameBase* set_game(int num, char* arr[]); virtual ~GameBase(); protected: // constructor GameBase(int width_, int height_, int board_width_, int piece_length_); virtual void print() = 0; virtual bool done() = 0; virtual bool draw() = 0; virtual int turn() = 0; // This function checks user inputs and stores it virtual int prompt(unsigned int & hor, unsigned int& ver); // array of pairs to store the game moves std::vector<std::pair<int,int> >storeO; std::vector<std::pair<int,int> >storeX; // remembers whose turn it is bool whos_turn; // remembers the current player std::string current_player; // remember who wins std::string who_wins; // remember the number of turns int num_turn ; int width; // total width and height int height; int board_width; // actual board's width and height // 2-D array to store the game board of the game std::string** position; // longest display string length int piece_length; };
//entry import express, { Request, Response, NextFunction } from "express"; import bodyParser from "body-parser"; import * as http from "http"; import config from "./core/config"; import { Me } from "./models/me"; import session from "express-session"; import userRoutes from './routes/user' import professorRoutes from "./routes/professor"; import MongoStore from "connect-mongo"; import cors from "cors"; import { UserError } from "./core/errors/base"; interface MainOptions { port: number; } //express session declare module "express-session" { interface SessionData { Me: Me; } } //main entry export async function main(options: MainOptions) { try { const app = express(); //Mongo store for session in db const mongoStore = MongoStore.create({ mongoUrl: config.server.mongoConnect, collectionName: "sessions", }) //set body parser and limit size for attacks app.use(bodyParser.json({ limit: "5mb" })); // for parsing application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ limit: "5mb", extended: false })); const sess = session({ secret: config.server.secret, resave: false, saveUninitialized: false, cookie: { secure: false, maxAge: 86400000 }, //call mongo store for session store: mongoStore }); //set up cors app.use( cors({ origin: config.corsOrigin, credentials: true, }) ); console.log( config.corsOrigin ); //set session app.use(sess); //set routes app.use("/user", userRoutes); //professor routes app.use("/professor", professorRoutes); app.use((err: Error, req: Request, res: Response, next: NextFunction) => { console.log('err',err); if (err instanceof UserError) { //Need to send the error down to the user res.status(err.statusCode).send({ message: err.message }); } else { res.status(500).send({message: err.message}); } const errMsg = err.message; }); //sample hello world route app.get("/", (req: Request, res: Response, next: NextFunction) => { res.json("Hello world, Root route"); }); //start server const server = http.createServer(app); server.listen(options.port); } catch (err) {} } if (require.main === module) { const PORT = 7000; main({ port: PORT }) .then(() => { console.log(`Server is running at http://localhost:${PORT}`); }) .catch((err) => { console.log("Something went wrong"); }); }
/* eslint-disable react/jsx-wrap-multilines */ import React from 'react' import { Typography, ListItemAvatar, ListItemText, Avatar, ListItem, IconButton } from '@mui/material' import * as datefns from 'date-fns' import { enUS, ptBR } from 'date-fns/locale' import { MdCheckCircleOutline as CheckIcon, MdRemoveCircleOutline as CloseIcon, MdOutlineSendToMobile as MobileIcon } from 'react-icons/md' import { dateFormat } from 'constants/date-format' import { ILocale, useIntl } from 'hooks' import { Notification } from 'services/entities' import { capitalizeLetter } from 'utils/capitalize-letter' import { ActionContainer, ClockIcon } from './NotificationItem.styled' import { renderAvatar } from './renderAvatar' interface NotificationItemProps { notification: Notification handleConfirm: (id: string, scheduleId: number) => void handleReject: (id: string, scheduleId: number) => void handleEnter: (id: string, scheduleId: number) => void } export const NotificationItem = ({ notification, handleConfirm, handleEnter, handleReject }: NotificationItemProps) => { const { id, avatar, createdAt, scheduleId, name, when, type, isConfirmed, isFinished } = notification const intl = useIntl() const formatDate = () => when && `${datefns.format(when, dateFormat)}` const notificationData = ((): { title: string; description: string } => { if (type === 'appointment_new' && when) { const message: Record<'title' | 'desc', keyof ILocale> = { title: 'notification.newAppointment.title', desc: 'notification.newAppointment.description' } if (!isConfirmed) { message.desc = 'notification.newAppointment.description' } if (typeof isConfirmed === 'boolean') { if (!isConfirmed) { message.desc = 'notification.rejectedAppointment.description.specialist' } else { message.desc = 'notification.confirmedAppointment.description.specialist' } } return { title: intl.formatMessage({ id: message.title }), description: intl.formatMessage({ id: message.desc }, { name, date: formatDate() }) } } if (type === 'appointment_confirmation' && when) { return { title: intl.formatMessage({ id: 'notification.confirmedAppointment.title' }), description: intl.formatMessage( { id: 'notification.confirmedAppointment.description' }, { date: formatDate() } ) } } if (type === 'appointment_call' && isFinished) { return { title: intl.formatMessage({ id: 'notification.callAppointment.title' }), description: intl.formatMessage({ id: 'notification.callAppointment.description.ended' }) } } return { title: intl.formatMessage({ id: 'notification.callAppointment.title' }), description: intl.formatMessage({ id: 'notification.callAppointment.description' }) } })() const { avatar: messageAvatar } = renderAvatar({ name, avatar, type }) return ( <ListItem disableGutters secondaryAction={ type === 'appointment_new' && typeof isConfirmed === 'undefined' ? ( <ActionContainer> <IconButton onClick={() => handleConfirm(id, scheduleId)} color="success" sx={{ p: 0.5 }} > <CheckIcon /> </IconButton> <IconButton onClick={() => handleReject(id, scheduleId)} color="error" sx={{ p: 0.5 }} > <CloseIcon /> </IconButton> </ActionContainer> ) : ( type === 'appointment_call' && !isFinished && ( <ActionContainer> <IconButton onClick={() => handleEnter(id, scheduleId)}> <MobileIcon /> </IconButton> </ActionContainer> ) ) } > <ListItemAvatar> <Avatar sx={{ bgcolor: 'background.neutral' }}>{messageAvatar}</Avatar> </ListItemAvatar> <ListItemText sx={{ maxWidth: '200px' }} primary={<Typography variant="subtitle2">{notificationData?.title}</Typography>} secondary={ <> <Typography component="span" variant="body2" sx={{ color: 'text.secondary' }}> {capitalizeLetter(notificationData?.description)} </Typography> <Typography variant="caption" sx={{ mt: 0.5, display: 'flex', color: 'text.disabled' }} > <ClockIcon /> {datefns.formatDistanceToNow(new Date(createdAt), { includeSeconds: true, addSuffix: true, locale: intl.locale === 'pt-BR' ? ptBR : enUS })} </Typography> </> } /> </ListItem> ) } export default NotificationItem
% ldpcut.m % % David Rowe 18 Dec 2013 % % Octave LDPC unit test script, based on simulation by Bill Cowley VK5DSP % % Start CML library (see CML set up instructions in ldpc.m) currentdir = pwd; addpath '/home/david/Desktop/cml/mat' % assume the source files stored here cd /home/david/Desktop/cml CmlStartup % note that this is not in the cml path! cd(currentdir) % Our LDPC library ldpc; qpsk; function sim_out = run_simulation(sim_in) rate = sim_in.rate; framesize = sim_in.framesize; Ntrials = sim_in.Ntrials; EsNodBvec = sim_in.EsNodBvec; verbose = sim_in.verbose; % Start simulation mod_order = 4; modulation = 'QPSK'; mapping = 'gray'; demod_type = 0; decoder_type = 0; max_iterations = 100; code_param = ldpc_init(rate, framesize, modulation, mod_order, mapping); for ne = 1:length(EsNodBvec) EsNodB = EsNodBvec(ne); EsNo = 10^(EsNodB/10); variance = 1/EsNo; Tbits = Terrs = Ferrs = 0; tx_bits = []; tx_symbols = []; rx_symbols = []; % Encode a bunch of frames for nn = 1: Ntrials atx_bits = round(rand( 1, code_param.data_bits_per_frame)); tx_bits = [tx_bits atx_bits]; [tx_codeword atx_symbols] = ldpc_enc(atx_bits, code_param); tx_symbols = [tx_symbols atx_symbols]; end % Add AWGN noise, 0.5 factor ensures var(noise) == variance , i.e. splits power between Re & Im noise = sqrt(variance*0.5)*(randn(1,length(tx_symbols)) + j*randn(1,length(tx_symbols))); rx_symbols = tx_symbols + noise; % Decode a bunch of frames for nn = 1: Ntrials st = (nn-1)*code_param.symbols_per_frame + 1; en = (nn)*code_param.symbols_per_frame; arx_codeword = ldpc_dec(code_param, max_iterations, demod_type, decoder_type, rx_symbols(st:en), EsNo, ones(1,code_param.symbols_per_frame)); st = (nn-1)*code_param.data_bits_per_frame + 1; en = (nn)*code_param.data_bits_per_frame; error_positions = xor(arx_codeword(1:code_param.data_bits_per_frame), tx_bits(st:en)); Nerrs = sum( error_positions); if verbose == 2 % print "." if frame decoded without errors, 'x' if we can't decode if Nerrs > 0, printf('x'), else printf('.'), end if (rem(nn, 50)==0), printf('\n'), end end if Nerrs > 0, Ferrs = Ferrs + 1; end Terrs = Terrs + Nerrs; Tbits = Tbits + code_param.data_bits_per_frame; end if verbose printf("\nEsNodB: %3.2f BER: %f Tbits: %d Terrs: %d Ferrs: %d\n", EsNodB, Terrs/Tbits, Tbits, Terrs, Ferrs) end sim_out.Tbits(ne) = Tbits; sim_out.Terrs(ne) = Terrs; sim_out.Ferrs(ne) = Ferrs; sim_out.BER(ne) = Terrs/Tbits; sim_out.FER(ne) = Ferrs/Ntrials; end endfunction % START SIMULATIONS --------------------------------------------------------------- more off; % 1/ Simplest possible one frame simulation --------------------------------------- printf("Test 1\n------\n"); mod_order = 4; modulation = 'QPSK'; mapping = 'gray'; framesize = 576; % CML library has a bunch of different framesizes available rate = 1/2; demod_type = 0; decoder_type = 0; max_iterations = 100; EsNo = 10; % decoder needs an estimated channel EsNo (linear ratio, not dB) code_param = ldpc_init(rate, framesize, modulation, mod_order, mapping); tx_bits = round(rand(1, code_param.data_bits_per_frame)); [tx_codeword, qpsk_symbols] = ldpc_enc(tx_bits, code_param); rx_codeword = ldpc_dec(code_param, max_iterations, demod_type, decoder_type, qpsk_symbols, EsNo); errors_positions = xor(tx_bits, rx_codeword(1:framesize*rate)); Nerr = sum(errors_positions); printf("Nerr: %d\n\n", Nerr); % 2/ Run a bunch of trials at just one EsNo point -------------------------------------- printf("Test 2\n------\n"); sim_in.rate = 0.5; sim_in.framesize = 2*576; sim_in.verbose = 2; sim_in.Ntrials = 100; sim_in.EsNodBvec = 5; run_simulation(sim_in); % 3/ Lets draw a Eb/No versus BER curve ------------------------------------------------- printf("\n\nTest 3\n------\n"); sim_in.EsNodBvec = -2:10; sim_out = run_simulation(sim_in); EbNodB = sim_in.EsNodBvec - 10*log10(2); % QPSK has two bits/symbol uncoded_BER_theory = 0.5*erfc(sqrt(10.^(EbNodB/10))); figure(1) clf semilogy(EbNodB, uncoded_BER_theory,'r;uncoded QPSK theory;') hold on; semilogy(EbNodB-10*log10(sim_in.rate), sim_out.BER+1E-10,'g;LDPC coded QPSK simulation;'); hold off; grid('minor') xlabel('Eb/No (dB)') ylabel('BER') axis([min(EbNodB) max(EbNodB) min(uncoded_BER_theory) 1])
import { Op, Sequelize } from 'sequelize'; import { HttpErrorString } from '../constants/http-error-string'; import Team from '../models/sequelize/team'; import TeamSprint from '../models/sequelize/team-sprint'; import TeamUser from '../models/sequelize/team-user'; import Ticket from '../models/sequelize/ticket'; import TicketStatus from '../models/sequelize/ticket-status'; import TicketStatusTransition from '../models/sequelize/ticket-status-transition'; import User from '../models/sequelize/user'; import UserRole from '../models/sequelize/user-role'; import { getTicketIncludeOptions } from './utils/query-options'; import { createUUID, ensureQueryResult, ensureUserPermissionByQuery, userExcludedAttributes, } from './utils/query-utils'; export type TeamSprintUpdate = Pick<TeamSprint, 'name' | 'description'>; const getTeamUserCanEditSprintsPermissionQuery = ( userId: string, teamId: string, ) => { return TeamUser.findOne({ where: { userId, teamId, canEditSprints: true, }, }); }; const getTeamUserCanDeleteSprintsPermissionQuery = ( userId: string, teamId: string, ) => { return TeamUser.findOne({ where: { userId, teamId, canDeleteSprints: true, }, }); }; const getUserCanEditTeamsPermissionQuery = (userId: string) => { return User.findOne({ where: { id: userId, }, include: [ { model: UserRole, required: true, where: { canEditTeams: true, }, }, ], }); }; export default class TeamService { getTeamDetailsForUser( userId: string, teamId: string, ): Promise<TeamUser | null> { return TeamUser.findOne({ where: { userId, teamId, }, include: [ { model: Team, include: [ { model: TeamSprint, include: [ { model: Ticket, ...getTicketIncludeOptions(), }, ], }, { model: User, }, ], }, ], }); } getAllTeamsByUser(userId: string): Promise<TeamUser[]> { return TeamUser.findAll({ include: [Team], where: { userId, }, attributes: { exclude: ['teamId', 'userId', 'id'], }, }); } getAllUsersInTeam(teamId: string, searchValue: string): Promise<User[]> { if (searchValue === '') { // TODO consider returning recently/most used users return Promise.resolve([]); } return User.findAll({ where: Sequelize.where( Sequelize.fn( 'concat', Sequelize.col('first_name'), ' ', Sequelize.col('last_name'), ), { [Op.like]: `%${searchValue}%` }, ), include: [ { model: Team, where: { id: teamId, }, }, ], attributes: { exclude: userExcludedAttributes, }, }); } createTeam( userId: string, name: string, description?: string, ): Promise<Team> { return ensureUserPermissionByQuery( getUserCanEditTeamsPermissionQuery(userId), ).then(() => { return ensureQueryResult( TicketStatus.findOne({ attributes: ['id'], where: { name: 'Open', }, }), { statusCode: 500, errorMessage: HttpErrorString.INVALID_STATE, }, ).then(({ id: initialTicketStatusId }) => { const id = createUUID(); return Team.create({ id, name, description, initialTicketStatusId, }); }); }); } createSprint( teamId: string, userId: string, name: string, description?: string, ): Promise<TeamSprint> { return ensureUserPermissionByQuery( getTeamUserCanEditSprintsPermissionQuery(userId, teamId), ).then(() => { const id = createUUID(); return TeamSprint.create({ id, teamId, name, description, active: false, }); }); } deleteSprint( teamId: string, sprintId: string, userId: string, ): Promise<number> { return ensureUserPermissionByQuery( getTeamUserCanDeleteSprintsPermissionQuery(userId, teamId), ).then(() => { return TeamSprint.destroy({ where: { id: sprintId, }, }); }); } editSprint( teamId: string, sprintId: string, userId: string, updateObject: TeamSprintUpdate, ): Promise<[number, TeamSprint[]]> { return ensureUserPermissionByQuery( getTeamUserCanEditSprintsPermissionQuery(userId, teamId), ).then(() => { return TeamSprint.update(updateObject, { where: { id: sprintId }, }); }); } activateSprint( teamId: string, sprintId: string, userId: string, ): Promise<[number, TeamSprint[]]> { return ensureUserPermissionByQuery( getTeamUserCanEditSprintsPermissionQuery(userId, teamId), ).then(() => { return TeamSprint.update( { active: true }, { where: { id: sprintId } }, ).then(() => { return TeamSprint.update( { active: false }, { where: { id: { [Op.not]: sprintId } } }, ); }); }); } getStatusTransitionInfo(teamId: string): Promise<TicketStatus[]> { return TicketStatus.findAll({ where: { teamId: { [Op.or]: [teamId, null], }, }, include: [ { model: TicketStatusTransition, foreignKey: 'previousStatusId', as: 'transitionsFrom', attributes: { exclude: ['previousStatusId', 'nextStatusId'] }, include: [ { model: TicketStatus, foreignKey: 'nextStatusId', as: 'nextStatus', }, ], }, { model: TicketStatusTransition, foreignKey: 'nextStatusId', as: 'transitionsTo', attributes: { exclude: ['previousStatusId', 'nextStatusId'] }, include: [ { model: TicketStatus, foreignKey: 'previousStatusId', as: 'previousStatus', }, ], }, ], }); } }
package by.chototam.zhukovich.pmisall.screens import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.TabRowDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import by.chototam.zhukovich.pmisall.R import by.chototam.zhukovich.pmisall.data.WeatherModel import by.chototam.zhukovich.pmisall.ui.theme.Bluelight import by.chototam.zhukovich.pmisall.ui.theme.BluelightDarker import coil.compose.AsyncImage import com.google.accompanist.pager.ExperimentalPagerApi import com.google.accompanist.pager.HorizontalPager import com.google.accompanist.pager.pagerTabIndicatorOffset import com.google.accompanist.pager.rememberPagerState import kotlinx.coroutines.launch import org.json.JSONArray import org.json.JSONObject // @Preview(showBackground = true) @Composable fun MainCard(currentDay: MutableState<WeatherModel>, onClickSync: () -> Unit, onClickSearch: () -> Unit) { Column( modifier = Modifier .padding(5.dp) ) { Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(10.dp), colors = CardDefaults.cardColors( containerColor = Bluelight ) ) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text( modifier = Modifier.padding(top = 1.dp, start = 8.dp), text = currentDay.value.time, style = TextStyle(fontSize = 15.sp), color = Color.DarkGray ) AsyncImage( model = "https:" + currentDay.value.icon, contentDescription = "img2", modifier = Modifier .size(36.dp) .padding(top = 1.dp, end = 8.dp) ) } } Text( text = currentDay.value.city, style = TextStyle(fontSize = 26.sp), color = Color.DarkGray ) Text( text = if(currentDay.value.currentTemp.isNotEmpty()) "${currentDay.value.currentTemp.toFloat().toInt()} C" else "${currentDay.value.maxTemp.toFloat().toInt()} C / ${currentDay.value.minTemp.toFloat().toInt()} C" , style = TextStyle(fontSize = 55.sp), color = Color.DarkGray ) Text( text = currentDay.value.condition, style = TextStyle(fontSize = 20.sp), color = Color.DarkGray ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { IconButton( onClick = { onClickSearch.invoke() } ) { Icon( painter = painterResource(id = R.drawable.ic_search), contentDescription = "img3", tint = Color.DarkGray ) } Text( text = "${currentDay.value.maxTemp.toFloat().toInt()} C/${currentDay.value.minTemp.toFloat().toInt()} C", style = TextStyle(fontSize = 20.sp), color = Color.DarkGray ) IconButton( onClick = { onClickSync.invoke() } ) { Icon( painter = painterResource(id = R.drawable.ic_sync), contentDescription = "img3", tint = Color.DarkGray ) } } } } } } @OptIn(ExperimentalPagerApi::class) @Composable fun TabLayout(daysList: MutableState<List<WeatherModel>>, currentDay: MutableState<WeatherModel>) { val tabList = listOf("HOURS", "DAYS") val pagerState = rememberPagerState() val tabIndex = pagerState.currentPage val coroutineScope = rememberCoroutineScope() Column( modifier = Modifier .padding(start = 5.dp, end = 5.dp, top = 8.dp) .clip(RoundedCornerShape(5.dp)) ) { TabRow( selectedTabIndex = tabIndex, // indicator = { pos -> // androidx.compose.material.TabRowDefaults.Indicator( // Modifier.pagerTabIndicatorOffset(pagerState, pos), // ) // }, containerColor = BluelightDarker ) { tabList.forEachIndexed { index, text -> Tab( selected = false, onClick = { coroutineScope.launch { pagerState.animateScrollToPage(index) } }, text = { Text(text = text) } ) } } HorizontalPager( count = tabList.size, state = pagerState, modifier = Modifier.weight(1.0f) ) {index -> val list = when(index){ 0 -> getWeatherByHours(currentDay.value.hours) 1 -> daysList.value else -> daysList.value // значение по умолчанию } MainList(list, currentDay) } } } private fun getWeatherByHours(hours: String): List<WeatherModel>{ if(hours.isEmpty()) return listOf() val hoursArray = JSONArray(hours) val list = ArrayList<WeatherModel>() for(i in 0 until hoursArray.length()){ val item = hoursArray[i] as JSONObject list.add( WeatherModel( "", item.getString("time"), item.getString("temp_c").toFloat().toInt().toString() + " C", item.getJSONObject("condition").getString("text"), item.getJSONObject("condition").getString("icon"), "", "", "", ) ) } return list }
import 'dart:io'; import 'package:face_camera_example/src/features/auth/login_screen.dart'; import 'package:face_camera_example/src/features/home/presentation/screens/home_screen.dart'; import 'package:face_camera_example/src/features/home/presentation/screens/images_screen.dart'; import 'package:face_camera_example/src/features/home/presentation/screens/initial_screen.dart'; import 'package:face_camera_example/src/features/home/presentation/screens/settings/settings_screen.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; export 'package:go_router/go_router.dart'; /// This line declares a global key variable which is used to access the [NavigatorState] object associated with a widget. final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); /// This function returns a [CustomTransitionPage] widget with default fade animation. CustomTransitionPage buildPageWithDefaultTransition<T>({ required BuildContext context, required GoRouterState state, required Widget child, }) { return CustomTransitionPage<T>( key: state.pageKey, child: child, transitionsBuilder: (context, animation, secondaryAnimation, child) { return FadeTransition(opacity: animation, child: child); }, ); } String? getCurrentPath() { if (navigatorKey.currentContext != null) { final GoRouterDelegate routerDelegate = GoRouter.of(navigatorKey.currentContext!).routerDelegate; final RouteMatch lastMatch = routerDelegate.currentConfiguration.last; final RouteMatchList matchList = lastMatch is ImperativeRouteMatch ? lastMatch.matches : routerDelegate.currentConfiguration; final String location = matchList.uri.toString(); return location; } else { return null; } } /// This function returns a [NoTransitionPage] widget with no animation. CustomTransitionPage buildPageWithNoTransition<T>({ required BuildContext context, required GoRouterState state, required Widget child, }) { return NoTransitionPage<T>( key: state.pageKey, child: child, ); } /// This function returns a dynamic [Page] widget based on the input parameters. /// It uses the '[buildPageWithDefaultTransition]' function to create a page with a default [fade animation]. Page<dynamic> Function(BuildContext, GoRouterState) defaultPageBuilder<T>(Widget child) => (BuildContext context, GoRouterState state) { return buildPageWithDefaultTransition<T>( context: context, state: state, child: child, ); }; /// [createRouter] is a factory function that creates a [GoRouter] instance with all routes. GoRouter createRouter() => GoRouter( initialLocation: InitialScreen.routeName, debugLogDiagnostics: true, navigatorKey: navigatorKey, observers: [ HeroController(), ], routes: [ GoRoute( name: InitialScreen.name, path: InitialScreen.routeName, builder: (context, pathParameters) => const InitialScreen(), ), GoRoute( name: HomeScreen.name, path: HomeScreen.routeName, builder: (context, pathParameters) { return const HomeScreen(); }, routes: [ GoRoute( name: SettingsScreen.name, path: SettingsScreen.routeName, builder: (context, pathParameters) { return const SettingsScreen(); }, ), GoRoute( name: ImagesScreen.name, path: ImagesScreen.routeName, builder: (context, pathParameters) { Map<String, dynamic>? args = pathParameters.extra as Map<String, dynamic>?; return ImagesScreen( images: args?[ImagesScreen.paramImages] as List<File>? ?? <File>[], ); }, ), ], ), /// --------------------------- `Auth` --------------------------- GoRoute( name: LoginScreen.name, path: LoginScreen.routeName, builder: (context, pathParameters) { Map<String, dynamic>? args = pathParameters.extra as Map<String, dynamic>?; return LoginScreen( isInitial: args?[LoginScreen.paramIsInitial] as bool? ?? false, ); }, ), ], );
## uninitialized variables ``` int i, j, k; ``` F# wants you to initialize everything and also doesn't need the type declared (usually). So this would be ``` let i = 0.0 let j = 0.0 let k = 0.0 ``` ## pointers ``` void SENNA_nn_temporal_max_convolution(float *output, float *bias, ``` If the pointer is to an array, you can consider it as "pass by reference" of the array, which is default in F#. So you don't need to do anything except change the syntax a bit. ``` let SENNA_nn_temporal_max_convolution (output: float array) ( bias : array<float> ) = ``` both type syntaxes should be OK ## constants ``` float maxval = -FLT_MAX; ``` Constants in C are usually in an include file for the whole project. Likewise this could be done in F#, but you could also just put at top of current F# file ``` let FLT_MAX = 3.0 ``` Assuming 3.0 was the value in the C include file ## convert from single dimension array to multi dimension array Typically you'll want to leave this alone b/c single dimension will be faster, but conceptually, what's going on: a[row][column] = b[row * columns + column]
import { NgModule } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { EffectsModule } from '@ngrx/effects'; import { StoreModule, Store } from '@ngrx/store'; import { readFirst } from '@nx/angular/testing'; import * as CommunityActions from './community.actions'; import { CommunityEffects } from './community.effects'; import { CommunityFacade } from './community.facade'; import { CommunityEntity } from './community.models'; import { COMMUNITY_FEATURE_KEY, CommunityState, initialCommunityState, communityReducer, } from './community.reducer'; import * as CommunitySelectors from './community.selectors'; interface TestSchema { community: CommunityState; } describe('CommunityFacade', () => { let facade: CommunityFacade; let store: Store<TestSchema>; const createCommunityEntity = (id: string, name = ''): CommunityEntity => ({ id, name: name || `name-${id}`, }); describe('used in NgModule', () => { beforeEach(() => { @NgModule({ imports: [ StoreModule.forFeature(COMMUNITY_FEATURE_KEY, communityReducer), EffectsModule.forFeature([CommunityEffects]), ], providers: [CommunityFacade], }) class CustomFeatureModule {} @NgModule({ imports: [ StoreModule.forRoot({}), EffectsModule.forRoot([]), CustomFeatureModule, ], }) class RootModule {} TestBed.configureTestingModule({ imports: [RootModule] }); store = TestBed.inject(Store); facade = TestBed.inject(CommunityFacade); }); /** * The initially generated facade::loadAll() returns empty array */ it('loadAll() should return empty list with loaded == true', async () => { let list = await readFirst(facade.allCommunity$); let isLoaded = await readFirst(facade.loaded$); expect(list.length).toBe(0); expect(isLoaded).toBe(false); facade.init(); list = await readFirst(facade.allCommunity$); isLoaded = await readFirst(facade.loaded$); expect(list.length).toBe(0); expect(isLoaded).toBe(true); }); /** * Use `loadCommunitySuccess` to manually update list */ it('allCommunity$ should return the loaded list; and loaded flag == true', async () => { let list = await readFirst(facade.allCommunity$); let isLoaded = await readFirst(facade.loaded$); expect(list.length).toBe(0); expect(isLoaded).toBe(false); store.dispatch( CommunityActions.loadCommunitySuccess({ community: [ createCommunityEntity('AAA'), createCommunityEntity('BBB'), ], }) ); list = await readFirst(facade.allCommunity$); isLoaded = await readFirst(facade.loaded$); expect(list.length).toBe(2); expect(isLoaded).toBe(true); }); }); });
#include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> /** * main - program that copies the content of a file to another file * @ac: number of arguments given to program * @av: pointer to first string argument provided * Return: 0 if success */ int main(int ac, char **av) { int fd_to, fd_from, r, w; char *buf; buf = malloc(sizeof(char) * 1024); if (buf == NULL) return (0); if (ac != 3) { dprintf(2, "Usage: cp file_from file_to\n"); exit(97); } fd_from = open(av[1], O_RDONLY); if (fd_from < 0) { dprintf(2, "Error: Can't read from file %s\n", av[1]); exit(98); } fd_to = open(av[2], O_WRONLY | O_CREAT | O_TRUNC, 0664); if (fd_to < 0) { dprintf(2, "Error: Can't write to %s\n", av[2]); exit(99); } while (1) { r = read(fd_from, buf, 1024); if (r < 0) { dprintf(2, "Error: Can't read from file %s\n", av[1]); exit(98); } w = write(fd_to, buf, r); if (w < 0) { dprintf(2, "Error: Can't write to %s\n", av[2]); exit(99); } if (r < 1024) break; } if (close(fd_from) < 0) { dprintf(2, "Error: Can't close fd %i\n", fd_from); exit(100); } if (close(fd_to) < 0) { dprintf(2, "Error: Can't close fd %i\n", fd_to); exit(100); } free(buf); return (0); }
/** * Copyright (c) 2018-2023, Ouster, Inc. * All rights reserved. * * @file lidar_packet_handler.h * @brief ... */ #pragma once // prevent clang-format from altering the location of "ouster_ros/os_ros.h", the // header file needs to be the first include due to PCL_NO_PRECOMPILE flag // clang-format off #include "ouster_ros/os_ros.h" // clang-format on #include <pcl_conversions/pcl_conversions.h> #include "lock_free_ring_buffer.h" #include <thread> namespace { template <typename T, typename UnaryPredicate> int find_if_reverse(const Eigen::Array<T, -1, 1>& array, UnaryPredicate predicate) { auto p = array.data() + array.size() - 1; do { if (predicate(*p)) return p - array.data(); } while (p-- != array.data()); return -1; } uint64_t linear_interpolate(int x0, uint64_t y0, int x1, uint64_t y1, int x) { uint64_t min_v, max_v; double sign; if (y1 > y0) { min_v = y0; max_v = y1; sign = +1; } else { min_v = y1; max_v = y0; sign = -1; } return y0 + (x - x0) * sign * (max_v - min_v) / (x1 - x0); } template <typename T> uint64_t ulround(T value) { T rounded_value = std::round(value); if (rounded_value < 0) return 0ULL; if (rounded_value > ULLONG_MAX) return ULLONG_MAX; return static_cast<uint64_t>(rounded_value); } } // namespace namespace ouster_ros { namespace sensor = ouster::sensor; using LidarScanProcessor = std::function<void(const ouster::LidarScan&, uint64_t, const rclcpp::Time&)>; class LidarPacketHandler { using LidarPacketAccumlator = std::function<bool(const uint8_t*)>; public: using HandlerOutput = ouster::LidarScan; using HandlerType = std::function<void(const uint8_t*)>; public: LidarPacketHandler(const ouster::sensor::sensor_info& info, const std::vector<LidarScanProcessor>& handlers, const std::string& timestamp_mode, int64_t ptp_utc_tai_offset) : ring_buffer(LIDAR_SCAN_COUNT), lidar_scan_handlers{handlers} { // initialize lidar_scan processor and buffer scan_batcher = std::make_unique<ouster::ScanBatcher>(info); lidar_scans.resize(LIDAR_SCAN_COUNT); mutexes.resize(LIDAR_SCAN_COUNT); for (size_t i = 0; i < lidar_scans.size(); ++i) { lidar_scans[i] = std::make_unique<ouster::LidarScan>( info.format.columns_per_frame, info.format.pixels_per_column, info.format.udp_profile_lidar); mutexes[i] = std::make_shared<std::mutex>(); // make_unique? } lidar_scans_processing_thread = std::make_unique<std::thread>([this]() { while (lidar_scans_processing_active) { process_scans(); } // TODO: NODELET_DEBUG("lidar_scans_processing_thread done."); }); // initalize time handlers scan_col_ts_spacing_ns = compute_scan_col_ts_spacing_ns(info.mode); compute_scan_ts = [this](const auto& ts_v) { return compute_scan_ts_0(ts_v); }; const sensor::packet_format& pf = sensor::get_format(info); if (timestamp_mode == "TIME_FROM_ROS_TIME") { lidar_packet_accumlator = LidarPacketAccumlator{[this, pf](const uint8_t* lidar_buf) { return lidar_handler_ros_time(pf, lidar_buf); }}; } else if (timestamp_mode == "TIME_FROM_PTP_1588") { lidar_packet_accumlator = LidarPacketAccumlator{ [this, pf, ptp_utc_tai_offset](const uint8_t* lidar_buf) { return lidar_handler_sensor_time_ptp(pf, lidar_buf, ptp_utc_tai_offset); }}; } else { lidar_packet_accumlator = LidarPacketAccumlator{[this, pf](const uint8_t* lidar_buf) { return lidar_handler_sensor_time(pf, lidar_buf); }}; } } LidarPacketHandler(const LidarPacketHandler&) = delete; LidarPacketHandler& operator=(const LidarPacketHandler&) = delete; ~LidarPacketHandler() = default; void register_lidar_scan_handler(LidarScanProcessor handler) { lidar_scan_handlers.push_back(handler); } void clear_registered_lidar_scan_handlers() { lidar_scan_handlers.clear(); } public: static HandlerType create_handler( const ouster::sensor::sensor_info& info, const std::vector<LidarScanProcessor>& handlers, const std::string& timestamp_mode, int64_t ptp_utc_tai_offset) { auto handler = std::make_shared<LidarPacketHandler>( info, handlers, timestamp_mode, ptp_utc_tai_offset); return [handler](const uint8_t* lidar_buf) { if (handler->lidar_packet_accumlator(lidar_buf)) { handler->ring_buffer_has_elements.notify_one(); } }; } const std::string getName() const { return "lidar_packet_hander"; } void process_scans() { { std::unique_lock<std::mutex> index_lock(ring_buffer_mutex); ring_buffer_has_elements.wait(index_lock, [this] { return !ring_buffer.empty(); }); } std::unique_lock<std::mutex> lock(*mutexes[ring_buffer.read_head()]); for (auto h : lidar_scan_handlers) { h(*lidar_scans[ring_buffer.read_head()], lidar_scan_estimated_ts, lidar_scan_estimated_msg_ts); } size_t read_step = 1; if (ring_buffer.size() > 7) { // TODO: NODELET_WARN("lidar_scans full, THROTTLING"); read_step = 2; } ring_buffer.read(read_step); } // time interpolation methods uint64_t impute_value(int last_scan_last_nonzero_idx, uint64_t last_scan_last_nonzero_value, int curr_scan_first_nonzero_idx, uint64_t curr_scan_first_nonzero_value, int scan_width) { assert(scan_width + curr_scan_first_nonzero_idx > last_scan_last_nonzero_idx); double interpolated_value = linear_interpolate( last_scan_last_nonzero_idx, last_scan_last_nonzero_value, scan_width + curr_scan_first_nonzero_idx, curr_scan_first_nonzero_value, scan_width); return ulround(interpolated_value); } uint64_t extrapolate_value(int curr_scan_first_nonzero_idx, uint64_t curr_scan_first_nonzero_value) { double extrapolated_value = curr_scan_first_nonzero_value - scan_col_ts_spacing_ns * curr_scan_first_nonzero_idx; return ulround(extrapolated_value); } // compute_scan_ts_0 for first scan uint64_t compute_scan_ts_0( const ouster::LidarScan::Header<uint64_t>& ts_v) { auto idx = std::find_if(ts_v.data(), ts_v.data() + ts_v.size(), [](uint64_t h) { return h != 0; }); assert(idx != ts_v.data() + ts_v.size()); // should never happen int curr_scan_first_nonzero_idx = idx - ts_v.data(); uint64_t curr_scan_first_nonzero_value = *idx; uint64_t scan_ns = curr_scan_first_nonzero_idx == 0 ? curr_scan_first_nonzero_value : extrapolate_value(curr_scan_first_nonzero_idx, curr_scan_first_nonzero_value); last_scan_last_nonzero_idx = find_if_reverse(ts_v, [](uint64_t h) { return h != 0; }); assert(last_scan_last_nonzero_idx >= 0); // should never happen last_scan_last_nonzero_value = ts_v(last_scan_last_nonzero_idx); compute_scan_ts = [this](const auto& ts_v) { return compute_scan_ts_n(ts_v); }; return scan_ns; } // compute_scan_ts_n applied to all subsequent scans except first one uint64_t compute_scan_ts_n( const ouster::LidarScan::Header<uint64_t>& ts_v) { auto idx = std::find_if(ts_v.data(), ts_v.data() + ts_v.size(), [](uint64_t h) { return h != 0; }); assert(idx != ts_v.data() + ts_v.size()); // should never happen int curr_scan_first_nonzero_idx = idx - ts_v.data(); uint64_t curr_scan_first_nonzero_value = *idx; uint64_t scan_ns = curr_scan_first_nonzero_idx == 0 ? curr_scan_first_nonzero_value : impute_value(last_scan_last_nonzero_idx, last_scan_last_nonzero_value, curr_scan_first_nonzero_idx, curr_scan_first_nonzero_value, static_cast<int>(ts_v.size())); last_scan_last_nonzero_idx = find_if_reverse(ts_v, [](uint64_t h) { return h != 0; }); assert(last_scan_last_nonzero_idx >= 0); // should never happen last_scan_last_nonzero_value = ts_v(last_scan_last_nonzero_idx); return scan_ns; } uint16_t packet_col_index(const sensor::packet_format& pf, const uint8_t* lidar_buf) { return pf.col_measurement_id(pf.nth_col(0, lidar_buf)); } rclcpp::Time extrapolate_frame_ts(const sensor::packet_format& pf, const uint8_t* lidar_buf, const rclcpp::Time current_time) { auto curr_scan_first_arrived_idx = packet_col_index(pf, lidar_buf); auto delta_time = rclcpp::Duration( 0, std::lround(scan_col_ts_spacing_ns * curr_scan_first_arrived_idx)); return current_time - delta_time; } bool lidar_handler_sensor_time(const sensor::packet_format&, const uint8_t* lidar_buf) { if (ring_buffer.full()) { // TODO: NODELET_WARN("lidar_scans full, DROPPING PACKET"); return false; } std::unique_lock<std::mutex> lock(*(mutexes[ring_buffer.write_head()])); if (!(*scan_batcher)(lidar_buf, *lidar_scans[ring_buffer.write_head()])) return false; lidar_scan_estimated_ts = compute_scan_ts(lidar_scans[ring_buffer.write_head()]->timestamp()); lidar_scan_estimated_msg_ts = rclcpp::Time(lidar_scan_estimated_ts); ring_buffer.write(); return true; } bool lidar_handler_sensor_time_ptp(const sensor::packet_format&, const uint8_t* lidar_buf, int64_t ptp_utc_tai_offset) { if (ring_buffer.full()) { // TODO: NODELET_WARN("lidar_scans full, DROPPING PACKET"); return false; } std::unique_lock<std::mutex> lock( *(mutexes[ring_buffer.write_head()])); if (!(*scan_batcher)(lidar_buf, *lidar_scans[ring_buffer.write_head()])) return false; auto ts_v = lidar_scans[ring_buffer.write_head()]->timestamp(); for (int i = 0; i < ts_v.rows(); ++i) ts_v[i] = impl::ts_safe_offset_add(ts_v[i], ptp_utc_tai_offset); lidar_scan_estimated_ts = compute_scan_ts(ts_v); lidar_scan_estimated_msg_ts = rclcpp::Time(lidar_scan_estimated_ts); ring_buffer.write(); return true; } bool lidar_handler_ros_time(const sensor::packet_format& pf, const uint8_t* lidar_buf) { auto packet_receive_time = rclcpp::Clock(RCL_ROS_TIME).now(); if (!lidar_handler_ros_time_frame_ts_initialized) { lidar_handler_ros_time_frame_ts = extrapolate_frame_ts( pf, lidar_buf, packet_receive_time); // first point cloud time lidar_handler_ros_time_frame_ts_initialized = true; } if (ring_buffer.full()) { // TODO: NODELET_WARN("lidar_scans full, DROPPING PACKET"); return false; } std::unique_lock<std::mutex> lock( *(mutexes[ring_buffer.write_head()])); if (!(*scan_batcher)(lidar_buf, *lidar_scans[ring_buffer.write_head()])) return false; lidar_scan_estimated_ts = compute_scan_ts(lidar_scans[ring_buffer.write_head()]->timestamp()); lidar_scan_estimated_msg_ts = lidar_handler_ros_time_frame_ts; // set time for next point cloud msg lidar_handler_ros_time_frame_ts = extrapolate_frame_ts(pf, lidar_buf, packet_receive_time); ring_buffer.write(); return true; } static double compute_scan_col_ts_spacing_ns(sensor::lidar_mode ld_mode) { const auto scan_width = sensor::n_cols_of_lidar_mode(ld_mode); const auto scan_frequency = sensor::frequency_of_lidar_mode(ld_mode); const double one_sec_in_ns = 1e+9; return one_sec_in_ns / (scan_width * scan_frequency); } private: std::unique_ptr<ouster::ScanBatcher> scan_batcher; const int LIDAR_SCAN_COUNT = 10; LockFreeRingBuffer ring_buffer; std::mutex ring_buffer_mutex; std::vector<std::unique_ptr<ouster::LidarScan>> lidar_scans; std::vector<std::shared_ptr<std::mutex>> mutexes; uint64_t lidar_scan_estimated_ts; rclcpp::Time lidar_scan_estimated_msg_ts; bool lidar_handler_ros_time_frame_ts_initialized = false; rclcpp::Time lidar_handler_ros_time_frame_ts; int last_scan_last_nonzero_idx = -1; uint64_t last_scan_last_nonzero_value = 0; double scan_col_ts_spacing_ns; // interval or spacing between columns of a // scan std::function<uint64_t(const ouster::LidarScan::Header<uint64_t>&)> compute_scan_ts; std::vector<LidarScanProcessor> lidar_scan_handlers; LidarPacketAccumlator lidar_packet_accumlator; bool lidar_scans_processing_active = true; std::unique_ptr<std::thread> lidar_scans_processing_thread; std::condition_variable ring_buffer_has_elements; }; } // namespace ouster_ros
%(BEGIN_QUESTION) % Copyright 2007, Tony R. Kuphaldt, released under the Creative Commons Attribution License (v 1.0) % This means you may do almost anything with this work of mine, so long as you give me proper credit {\it Ethernet} actually encompasses several similar network standards, varying by cable type and bit rate (speed). The IEEE has designated special identifier names to denote each variety of Ethernet media. Identify which type of Ethernet each of these names refers to: \begin{itemize} \item{} 10BASE2: \vskip 5pt \item{} 10BASE5: \vskip 5pt \item{} 10BASE-T: \vskip 5pt \item{} 10BASE-F: \vskip 5pt \item{} 100BASE-TX: \vskip 5pt \item{} 100BASE-FX: \vskip 5pt \item{} 1000BASE-T: \vskip 5pt \item{} 1000BASE-SX: \vskip 5pt \item{} 1000BASE-LX: \end{itemize} \vskip 20pt \vbox{\hrule \hbox{\strut \vrule{} {\bf Suggestions for Socratic discussion} \vrule} \hrule} \begin{itemize} \item{} Ethernet networks are considered ``baseband'' rather than ``broadband.'' Explain the distinction between these two terms. \end{itemize} \underbar{file i02209} %(END_QUESTION) %(BEGIN_ANSWER) \begin{itemize} \item{} 10BASE2: 10 Mbps, thin coaxial cable, 185 meters length maximum \vskip 5pt \item{} 10BASE5: 10 Mbps, thick coaxial cable, 500 meters length maximum \vskip 5pt \item{} 10BASE-T: 10 Mbps, two twisted wire pairs, Category 3 cable or better \vskip 5pt \item{} 10BASE-F: 10 Mbps, two optical fibers (includes 10BASE-FB, 10BASE-FP, and 10BASE-FL) \vskip 5pt \item{} 100BASE-TX: 100 Mbps, two twisted wire pairs, Category 5 cable or better \vskip 5pt \item{} 100BASE-FX: 100 Mbps, two optical fibers, multimode \vskip 5pt \item{} 1000BASE-T: 1 Gbps, four twisted wire pairs, Category 5 cable or better \vskip 5pt \item{} 1000BASE-SX: 1 Gbps, two optical fibers, short-wavelength \vskip 5pt \item{} 1000BASE-LX: 1 Gbps, two optical fibers, long-wavelength \end{itemize} %(END_ANSWER) %(BEGIN_NOTES) %INDEX% Networking, Ethernet: different versions of %(END_NOTES)
using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; using RestSharp; namespace WatsonAI { //Need to pass the URL for class's constructor that is responsible for making the call, or an instance of RestSharp for it to use. public class WatsonAssistant { /// <summary> /// A class constructor for all of the Watson Assistant Message API methods. /// </summary> public WatsonAssistant() { } //One instance of client. public static RestClient client = new RestClient(); static readonly string watsonMsgUrl = "https://gateway.watsonplatform.net/assistant/api/v1/workspaces/042db9d3-4484-497d-a117-475c549cd866/message?version=2018-09-20"; //Watson Assist "message" API //string sampleInput = "{\"input\": {\"text\": \"i want some pizza\"}, \"alternate_intents\": true}"; /// <summary> /// Takes List of string inputs and string apiKey, uses Utilities method to convert apiKey to Base64, uses JObject to format /// parameters for RestSharp to form request foreach input, executes POST request, parses each response to JObject, adds JObject /// to list foreach, and then returns list of JObjects. /// </summary> /// <param name="inputs"></param> /// <param name="apiKey"></param> /// <returns></returns> public List<JObject> Message(List<string> inputs, string apiKey) //Watson Assistant Message API { if (inputs == null) throw new ArgumentNullException("List<string> inputs"); if (apiKey == null) throw new ArgumentNullException("string apiKey"); //Take UTF8 text apiKey and convert to Base64. var util = new Utilities(); string byteKey = util.Base64Encode(apiKey); //Console.WriteLine(byteKey); string auth = "Basic " + byteKey; List<JObject> objList = new List<JObject>(); foreach (string input in inputs) { //Format payload parameter for RestSharp request. JObject payLoad = new JObject( new JProperty("input", new JObject( new JProperty("text", input), new JProperty("alternate_intents", true) ) ) ); var client = new RestClient(watsonMsgUrl); var request = new RestRequest(Method.POST); //Add headers request.AddHeader("cache-control", "no-cache"); request.AddHeader("Connection", "keep-alive"); request.AddHeader("content-length", "67"); request.AddHeader("accept-encoding", "gzip, deflate"); request.AddHeader("Host", "gateway.watsonplatform.net"); request.AddHeader("Postman-Token", "177ef4df-df0d-466f-a278-b0b860700b36,440bad6c-01c2-4b4a-800d-c314abcc7e05"); request.AddHeader("Accept", "*/*"); request.AddHeader("User-Agent", "PostmanRuntime/7.15.0"); request.AddHeader("Authorization", auth); request.AddHeader("Cache-Control", "no-cache"); request.AddHeader("Content-Type", "application/json"); request.AddParameter("undefined", payLoad.ToString(), ParameterType.RequestBody); IRestResponse response = client.Execute(request); //Test //Console.WriteLine(response.Content.ToString()); //Console.WriteLine(); //Convert to JSON. JObject obj = JObject.Parse(response.Content.ToString()); objList.Add(obj); } return objList; } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> // 确认对话框 confirm 取消false 确认true // var res = confirm('今天星期六?'); // console.log(res); // 输入弹出框 取消 null 确认 文本的内容 // var res = prompt('请输入手机号'); // console.log(res); //案例1:今天晚上吃什么? //案例2:根据用户输入的分数进行评级 使用if //0-60 不及格 60-70 合格 70-85 良好 85以上优秀 // var res = prompt('请输入分数'); // console.log(res); // if (res >= 0 && res < 60) { // alert('不及格'); // } else if (res < 70) { // alert('合格'); // } else if (res < 85) { // alert('良好'); // } else if (res <= 100) { // alert('优秀'); // } else { // alert('输入有误'); // } /* *弹出输入框判断用户是否输入值, *没输入内容:弹出提示框“请刷新页面重新输入动作” *输入内容:再判断是不是数字: *不是数字:弹出提示框“只允许输入数字” *是数字:弹出第二个输入框要求输入运算的第二个值,依次再判断是否输入内容,是否为数字,与第一个值判断一致 *当第1及第2个值都输入后再弹出第三个输入框,要求输入运算符,通过switch语句分别判断: *如果是”+”号,则执行加法运算并alert运算结果 *如果是”-”号,则执行减法运算并alert运算结果 *如果是”*”号,则执行乘法运算并alert运算结果 *如果是”/”号,则执行除法运算并alert运算结果 *其它符号,则alert “很遗憾,你输入的运算超出了运算范围 */ var a = prompt('请输入数字'); if (a) { //有内容 if (isNaN(a)) { //不是数字 alert('只允许输入数字'); } else { //是数字 var b = prompt('请输入数字'); if (b) { //有内容 if (isNaN(b)) { //不是数字 alert('只允许输入数字'); } else { //是数字 var c = prompt('请输入运算符'); if (c == '+') { alert(+a + Number(b)); } else if (c == '-') { alert(a - b); } else if (c == '*') { alert(a * b); } else if (c == '/') { alert(a / b); } else { alert('很遗憾,你输入的运算超出了运算范围'); } } } else { //没有内容 alert('请刷新页面重新输入动作'); } } } else { //没有内容 alert('请刷新页面重新输入动作'); } </script> </body> </html>