text
stringlengths
184
4.48M
// Includes //========= #include "cFinalGame.h" #include <Engine/Asserts/Asserts.h> #include <Engine/UserInput/UserInput.h> #include "Engine/Graphics/Graphics.h" // Inherited Implementation // Run //---- void eae6320::cFinalGame::SubmitDataToBeRendered(const float i_elapsedSecondCount_systemTime, const float i_elapsedSecondCount_sinceLastSimulationUpdate) { //get all gameObjects int count = 0; for(size_t i=0; i<levelBlocksCount; i++) { count += level_blocks[i].blockCount+1; } count++; //player allGameObjects = new Components::GameObject[count]; int index = 0; for(size_t i=0; i<levelBlocksCount; i++) { level_blocks[i].GetGameObjects(allGameObjects, index); index += level_blocks->blockCount+1; } allGameObjects[count-1] = ship; eae6320::Graphics::SetBgColor(bg_Color); eae6320::Graphics::SetMeshEffectData(camera, allGameObjects, count); bgAudio.SubmitAudioSource(); moveAudio.SubmitAudioSource(); collisionAudio.SubmitAudioSource(); } void eae6320::cFinalGame::UpdateSimulationBasedOnInput() { //player movement if (UserInput::IsKeyPressed('A') && !isLeftKeyPressed) { //move left moveAudio.PlayIndependent(); isTargetSet = true; isLeftKeyPressed = true; currentTargetXPos -= (currentTargetXPos-movementDistance >= -(movementDistance*lanesOnEachSide)) ? movementDistance : 0; } else if (UserInput::IsKeyPressed('D') && !isRightKeyPressed) { //move right moveAudio.PlayIndependent(); isTargetSet = true; isRightKeyPressed = true; currentTargetXPos += (currentTargetXPos+movementDistance <= (movementDistance*lanesOnEachSide)) ? movementDistance : 0; } else if (UserInput::IsKeyPressed('W') && !movementStarted) { //move up camera.SetVelocity(Math::sVector(0, 0, -shipSpeed)); movementStarted = true; } else if (UserInput::IsKeyPressed(UserInput::KeyCodes::Space)) { //Jump moveAudio.PlayIndependent(); JumpStart(); } else { isLeftKeyPressed = false; isRightKeyPressed = false; camera.GetRigidBodyReference()->acceleration = Math::sVector(0,0,0); if (!movementStarted || isStopped) { camera.SetVelocity(Math::sVector(0, 0, 0)); } else if (!isStopped && movementStarted) { camera.SetVelocity(Math::sVector(0, 0, -shipSpeed)); } } if (!bgAudio.IsPlaying()) { bgAudio.Play(); } } void eae6320::cFinalGame::UpdateBasedOnInput() { // Is the user pressing the ESC key? if ( UserInput::IsKeyPressed( UserInput::KeyCodes::Escape ) ) { // Exit the application const auto result = Exit( EXIT_SUCCESS ); EAE6320_ASSERT( result ); } } void eae6320::cFinalGame::UpdateBasedOnTime(const float i_elapsedSecondCount_sinceLastUpdate) { Physics::sRigidBodyState* cameraRigidBody = camera.GetRigidBodyReference(); //move player if target is set if(isTargetSet) { if(abs(cameraRigidBody->position.x - currentTargetXPos) < 0.1f) { isTargetSet = false; camera.SetVelocity(Math::sVector(0, 0, cameraRigidBody->velocity.z)); } else if(cameraRigidBody->position.x > currentTargetXPos) { camera.SetVelocity(Math::sVector(-100, 0, cameraRigidBody->velocity.z)); } else { camera.SetVelocity(Math::sVector(100, 0, cameraRigidBody->velocity.z)); } } JumpUpdate(i_elapsedSecondCount_sinceLastUpdate); ship.GetRigidBodyReference()->position = Math::sVector(cameraRigidBody->position.x, cameraRigidBody->position.y - 5, cameraRigidBody->position.z - 15); ship.Update(i_elapsedSecondCount_sinceLastUpdate); camera.Update(i_elapsedSecondCount_sinceLastUpdate); for(size_t i=0; i<levelBlocksCount; i++) { if(level_blocks[i].plane.GetRigidBodyReference()->position.z - ship.GetRigidBodyReference()->position.z > 80) { level_blocks[i].UpdatePosition(level_blocks[i].plane.GetRigidBodyReference()->position.z - (150.0f*(float)levelBlocksCount)); } level_blocks[i].Update(i_elapsedSecondCount_sinceLastUpdate); } } // Initialize / Clean Up //---------------------- eae6320::cResult eae6320::cFinalGame::Initialize() { eae6320::Logging::OutputMessage("Initializing Game..."); auto result = eae6320::Results::Success; //init gameObjects { if (!(result = ship.InitializeMeshEffect("data/Meshes/ship.json", "data/Shaders/Fragment/standard.shader"))) { EAE6320_ASSERTF(false, "Failed Initializing GameObject") return result; } } shipCollider = Collision::cCollider(ship.GetRigidBodyReference(), Math::sVector(5,7,5)); shipCollider.SetOnCollisionEnterCallback(OnCollisionEnter); shipCollider.SetOnCollisionExitCallback(OnCollisionExit); float zDist = -75; for(size_t i=0; i<levelBlocksCount; i++) { if (!(result = level_blocks[i].Initialize(zDist))) { EAE6320_ASSERTF(false, "Failed Initializing Level block") return result; } zDist -= 150; } bgAudio.CreateAudioData("data/Audios/bgm.mp3", "bgm", 1000, true); moveAudio.CreateAudioData("data/Audios/move.mp3", "move", 750, false); collisionAudio.CreateAudioData("data/Audios/collide.mp3", "collide", 1000, false); return result; } eae6320::cResult eae6320::cFinalGame::CleanUp() { eae6320::Logging::OutputMessage("Cleaning up Game..."); ship.CleanUp(); for(size_t i=0; i<levelBlocksCount; i++) { level_blocks[i].CleanUp(); } return Results::Success; } void eae6320::cFinalGame::JumpStart() { if(!isJumping) { Physics::sRigidBodyState* rigidBody = camera.GetRigidBodyReference(); isJumping = true; currentJumpTime = 0; rigidBody->acceleration = Math::sVector(0,69,0); } } void eae6320::cFinalGame::JumpUpdate(const float i_elapsedSecondCount_sinceLastUpdate) { Physics::sRigidBodyState* rigidBody = camera.GetRigidBodyReference(); if(isJumping) { if(currentJumpTime < jumpTime) { currentJumpTime += i_elapsedSecondCount_sinceLastUpdate; rigidBody->acceleration = Math::sVector(0,69,0); } else { if(rigidBody->position.y <= 0) { isJumping = false; } rigidBody->acceleration = Math::sVector(0,-400,0); } } else { rigidBody->acceleration = Math::sVector(0,0,0); } } bool eae6320::cFinalGame::OnCollisionEnter(Collision::cCollider* self, Collision::cCollider* other) { eae6320::Logging::OutputMessage("Collision Enter"); other->GetRigidBodyReference()->angularVelocity_axis_local = Math::sVector(0,1,0); other->GetRigidBodyReference()->angularSpeed = 20; self->GetRigidBodyReference()->velocity = Math::sVector(0,0,0); isStopped = true; collisionAudio.PlayIndependent(); return true; } bool eae6320::cFinalGame::OnCollisionExit(Collision::cCollider* self,Collision::cCollider* other) { eae6320::Logging::OutputMessage("Collision Exit"); other->GetRigidBodyReference()->angularVelocity_axis_local = Math::sVector(0,1,0); other->GetRigidBodyReference()->angularSpeed = 0; isStopped = false; return true; }
/* eslint-disable react/jsx-no-bind */ /* eslint-disable react/prop-types */ /* eslint-disable react/destructuring-assignment */ /* eslint-disable eqeqeq */ /* eslint-disable no-shadow */ /* eslint-disable no-underscore-dangle */ /* eslint-disable camelcase */ import React, { useEffect, useState } from 'react'; import { Column } from 'rbx'; import '../../styles/notes.scss'; import { push as Menu } from 'react-burger-menu'; import List from './list'; import Editor from './editor'; import Search from './search'; import NotesService from '../../services/notes'; function Notes(props) { const [notes, setNotes] = useState([]); const [current_note, setCurrentNote] = useState({ title: '', body: '', id: '' }); async function fetchNotes() { const response = await NotesService.index(); if (response.data.length >= 1) { setNotes(response.data.reverse()); setCurrentNote(response.data[0]); } else { setNotes([]); } } const createNote = async () => { await NotesService.create(); fetchNotes(); }; const deleteNote = async (note) => { await NotesService.delete(note._id); fetchNotes(); }; const updateNote = async (oldNote, params) => { const updatedNote = await NotesService.update(oldNote._id, params); const index = notes.indexOf(oldNote); const newNotes = notes; newNotes[index] = updatedNote.data; setNotes(newNotes); setCurrentNote(updatedNote.data); }; const searchNotes = async (query) => { const response = await NotesService.search(query); setNotes(response.data); }; const selectNote = (id) => { const note = notes.find((note) => note._id == id); setCurrentNote(note); }; useEffect(() => { fetchNotes(); }, []); return ( <> <Column.Group className="notes" id="notes"> <Menu pageWrapId="notes-editor" isOpen={props.isOpen} onStateChange={(state) => props.setIsOpen(state.isOpen)} disableAutoFocus outerContainerId="notes" customBurgerIcon={false} customCrossIcon={false} > <Column.Group> <Column size={10} offset={1}> <Search searchNotes={searchNotes} fetchNotes={fetchNotes} /> </Column> </Column.Group> <List notes={notes} selectNote={selectNote} current_note={current_note} deleteNote={deleteNote} createNote={createNote} /> </Menu> <Column size={12} className="notes-editor" id="notes-editor"> <Editor note={current_note} updateNote={updateNote} /> </Column> </Column.Group> </> ); } export default Notes;
<button class="go-back-button" routerLink="/cart">Go back</button> <div class="main-container"> <div class="cart-at-checkout"> <h2 class="your-cart-text">Your cart</h2> <ul> <li *ngFor="let product of cartProductsAtcheckout"> {{ product.title }} - {{ product.productQuantity }} - {{ product.id }} </li> </ul> <div class="subtotal-div"> <h3 class="subtotal"> Subtotal : <span>{{ totalCartSubtotal.toFixed(2) }}</span> </h3> </div> </div> <div class="container"> <h2 class="heading" *ngIf="userData"> Confirm Your order {{ userData.name }}! </h2> <h2 *ngIf="!userData">Confirm Your Order!</h2> <form class="checkout-form-main" [formGroup]="checkOutForm" (ngSubmit)="onSubmittingCheckout(checkOutForm)" > <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Card Number</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" formControlName="cardNumber" /> <small *ngIf=" checkOutForm.controls['cardNumber'].dirty && checkOutForm.hasError('required', 'cardNumber') " class="text-danger" >*Enter valid Card Number</small > <br /> <small *ngIf=" checkOutForm.controls['cardNumber'].dirty && checkOutForm.hasError('pattern', 'cardNumber') " class="text-danger" >*Enter valid Card Number</small > <!-- <small *ngIf=" checkOutForm.controls['cardNumber'].dirty && checkOutForm.hasError('pattern', 'firstname') " class="text-danger" >*firstname must be alphabet</small > --> </div> <div class="mb-3"> <label for="exampleInputEmail2" class="form-label">Pincode</label> <input type="text" class="form-control" id="exampleInputEmail2" formControlName="pincode" /> <small *ngIf=" checkOutForm.controls['pincode'].dirty && checkOutForm.hasError('required', 'pincode') " class="text-danger" >*Enter valid pincode</small > <br /> <small *ngIf=" checkOutForm.controls['pincode'].dirty && checkOutForm.hasError('pattern', 'pincode') " class="text-danger" >*Enter valid pincode pattern</small > </div> <div class="mb-3"> <label for="exampleInputEmail3" class="form-label">State</label> <input type="text" class="form-control" id="exampleInputEmail3" formControlName="state" /> <small *ngIf=" checkOutForm.controls['state'].dirty && checkOutForm.hasError('required', 'state') " class="text-danger" >*State is required</small > <br /> <small *ngIf=" checkOutForm.controls['state'].dirty && checkOutForm.hasError('pattern', 'state') " class="text-danger" >*Enter valid state value </small> </div> <div class="mb-3"> <label for="exampleInputEmail4" class="form-label">Country</label> <input type="text" class="form-control" id="exampleInputEmail4" formControlName="country" /> <small *ngIf=" checkOutForm.controls['country'].dirty && checkOutForm.hasError('required', 'country') " class="text-danger" >*Country is required</small > <br /> <small *ngIf=" checkOutForm.controls['country'].dirty && checkOutForm.hasError('pattern', 'country') " class="text-danger" >*Enter valid Country value</small > </div> <div class="mb-3"> <label for="exampleInputEmail15" class="form-label">Address</label> <input type="text" class="form-control" id="exampleInputEmail15" formControlName="address" /> <small *ngIf=" checkOutForm.controls['address'].dirty && checkOutForm.hasError('required', 'address') " class="text-danger" >*Address is required</small > <br /> </div> <button type="submit" class="btn btn-primary">Confirm Order</button> </form> </div> </div>
package jobber import ( "context" "fmt" "github.com/qdm12/reprint" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" ) type gvkKey string type resourceName string func gvkKeyFromGroupVersionKind(gvk schema.GroupVersionKind) gvkKey { return gvkKey(fmt.Sprintf("%s\t%s\t%s", gvk.Group, gvk.Version, gvk.Kind)) } func gvkKeyFromGVKStrings(group, version, kind string) gvkKey { return gvkKey(fmt.Sprintf("%s\t%s\t%s", group, version, kind)) } type PipelineRuntimeNamespace struct { Name string } type PipelineRuntimeValues struct { DefaultNamespace *PipelineRuntimeNamespace createdAssets map[gvkKey]map[resourceName]*GenericK8sResource client *Client } func NewEmptyPipelineRuntimeValues(client *Client) *PipelineRuntimeValues { return &PipelineRuntimeValues{ DefaultNamespace: &PipelineRuntimeNamespace{ Name: "", }, createdAssets: make(map[gvkKey]map[resourceName]*GenericK8sResource), client: client, } } func (values *PipelineRuntimeValues) Add(resource *GenericK8sResource) *PipelineRuntimeValues { key := gvkKeyFromGroupVersionKind(resource.ApiObject().GroupVersionKind()) if values.createdAssets[key] == nil { values.createdAssets[key] = make(map[resourceName]*GenericK8sResource) } values.createdAssets[key][resourceName(resource.Name)] = resource return values } func (values *PipelineRuntimeValues) CreatedAsset(group string, version string, kind string, name string) *GenericK8sResource { return values.createdAssets[gvkKeyFromGVKStrings(group, version, kind)][resourceName(name)] } func (values *PipelineRuntimeValues) CreatedPod(podName string) (*TransitivePod, error) { if resource := values.CreatedAsset("", "v1", "Pod", podName); resource == nil { return nil, fmt.Errorf("no created pod named (%s)", podName) } else { return resource.AsAPod(), nil } } func (values *PipelineRuntimeValues) ServiceAccount(inNamespace string, accountName string) (*TransitiveServiceAccount, error) { apiObject, err := values.client.Set().CoreV1().ServiceAccounts(inNamespace).Get(context.Background(), accountName, metav1.GetOptions{}) if err != nil { return nil, err } return &TransitiveServiceAccount{ apiObject: apiObject, client: values.client, }, nil } type PipelineVariablesValues struct { Global map[string]any Unit map[string]any Case map[string]any } type PipelineVariablesContext struct { TestUnitName string TestCaseName string TestCaseRetrievedAssetsDirectoryPath string } type PipelineVariables struct { Values *PipelineVariablesValues Context *PipelineVariablesContext Runtime *PipelineRuntimeValues } func NewEmptyPipelineVariables(client *Client) *PipelineVariables { return &PipelineVariables{ Values: &PipelineVariablesValues{ Global: make(map[string]any), Unit: make(map[string]any), Case: make(map[string]any), }, Context: &PipelineVariablesContext{ TestUnitName: "", TestCaseName: "", TestCaseRetrievedAssetsDirectoryPath: "", }, Runtime: NewEmptyPipelineRuntimeValues(client), } } func (v *PipelineVariables) DeepCopy() *PipelineVariables { return reprint.This(v).(*PipelineVariables) } func (v *PipelineVariables) WithGlobalValues(globalValues map[string]any) *PipelineVariables { v.Values.Global = globalValues return v } func (v *PipelineVariables) SetDefaultNamespaceNameTo(generatedNamespaceName string) *PipelineVariables { v.Runtime.DefaultNamespace.Name = generatedNamespaceName return v } func (v *PipelineVariables) AndUsingDefaultNamespaceNamed(generatedNamespaceName string) *PipelineVariables { return v.SetDefaultNamespaceNameTo(generatedNamespaceName) } func (v *PipelineVariables) RescopedToUnitNamed(testUnitName string) *PipelineVariables { vCopy := v.DeepCopy() vCopy.Values.Unit = map[string]any{} vCopy.Values.Case = map[string]any{} vCopy.Context = &PipelineVariablesContext{ TestUnitName: testUnitName, } return vCopy } func (v *PipelineVariables) WithUnitValues(unitValues map[string]any) *PipelineVariables { v.Values.Unit = unitValues return v } func (v *PipelineVariables) RescopedToCaseNamed(testCaseName string) *PipelineVariables { vCopy := v.DeepCopy() vCopy.Values.Case = map[string]any{} vCopy.Context = &PipelineVariablesContext{ TestUnitName: v.Context.TestUnitName, TestCaseName: testCaseName, } return vCopy } func (v *PipelineVariables) WithCaseValues(caseValues map[string]any) *PipelineVariables { v.Values.Case = caseValues return v } func (v *PipelineVariables) SetTestCaseRetrievedAssetsDirectoryPath(path string) *PipelineVariables { v.Context.TestCaseRetrievedAssetsDirectoryPath = path return v } func (v *PipelineVariables) AndTestCaseRetrievedAssetsDirectoryAt(path string) *PipelineVariables { return v.SetTestCaseRetrievedAssetsDirectoryPath(path) }
# node.js와 socket.io를 활용한 채팅 server/client 구현 개발 기간 : `2022/06/16` <br> ## 1. 프로젝트 목표 node.js 웹 소켓 라이브러리인 socket.io를 활용하여 간단한 채팅 서버를 구현해본다. - socket.io 라이브러리를 활용하여 채팅 서버를 구현한다. - 사용에 불편함이 없도록 클라이언트 화면을 구현한다. <br> ## 2. 프로젝트 소개 ### 1) 프로젝트 프리뷰 <br> <img src="https://raw.githubusercontent.com/JaeKP/image_repo/main/img/socketIo_readMe_02.gif" width="500px"> <br> --- ### 2) 상세 화면 <br> ![mini-toy-projects-02-00](https://raw.githubusercontent.com/JaeKP/image_repo/main/img/mini-toy-projects-02-00.jpg) #### 닉네임 설정 - 접속시, 닉네임을 설정하는 modal창이 뜬다. - 닉네임을 설정해야 채팅방에 입장이 가능하다. - 닉네임은 최대 15글자이다. <br> #### 채팅 - 입장, 퇴장 시 채팅창 위에 알림이 뜬다. - 채팅 입력시, 입력한 시간과 입력한 사람의 닉네임에 대한 정보를 볼 수 있다. - 채팅 입력시, fadeIn효과와 함께 말풍선이 올라온다. - 채팅 입력시, 그에 맞게 화면이 자동으로 스크롤 된다. <br> ![mini-toy-projects-02-01](https://raw.githubusercontent.com/JaeKP/image_repo/main/img/mini-toy-projects-02-01.jpg) #### 이모지 - 😍을 누르면 이모지를 선택하여 입력하는 창이 서서히 올라온다. - 이모지를 선택하는 창에서 이모지를 클릭 시, 해당 이모지가 채팅을 입력하는 칸에 추가된다. - 채팅창을 누르면 이모지를 선택하여 입력하는 창이 서서히 내려간다. <br> ![mini-toy-projects-02-02](https://raw.githubusercontent.com/JaeKP/image_repo/main/img/mini-toy-projects-02-02.jpg) #### 알럿창 - 빈 값을 입력한 뒤, 채팅을 보내려고 하면 `메시지를 입력해주세요.`라는 알럿이 뜬다. - 욕설로 설정된 단어를 입력한 뒤, 채팅을 보내려고 하면 알럿이 뜬다. <br> ## 3. 학습내용 ### 서버 (server.js ) [참고한 블로그](https://codevkr.tistory.com/58?category=719250) 위의 블로그가 socket.io에 대해 설명이 잘되어있어 서버는 이를 토대로 개발했다. 설명도 엄청 자세하다. 😊 #### (1) 모듈 불러오기 ```javascript // Node.js 기본 내장 모듈 불러온다.(파일과 관련된 처리) const fs = require("fs"); // 설치한 express 모듈 불러온다. const express = require("express"); // express객체를 생성한다. const app = express(); // Node.js기본 내장 모듈("http")를 불러온 뒤, express 서버를 생성한다. const server = require("http").createServer(app); // 설치한 socket.io 모듈 불러온 뒤, socket.io에 바인딩한다. const io = require("socket.io")(server); ``` - **fs**: 파일의 입출력을 처리하는 모듈 (후에 html 파일을 불러오기 위해 사용한다. ) - **express**: 서버를 생성하기 위해 사용된다. - [**socket.io**](https://jangstory.tistory.com/12) - `socket` - 떨어져 있는 두 호스트를 연결해주는 도구로써 인터페이스 역할을 한다. => 데이터를 주고 받을 수 있는 구조체로 소켓을 통해 통로가 만들어진다. - 즉, 프로토콜과 ip주소, 포트넘버로 떨어져있는 두 디바이스를 연결해준다. - Websocket을 기반으로 실시간 웹 애플리케이션을 위한 자바스크립트 라이브러리이다. - 클라이언트와 서버 간의 실시간 양방향 통신을 가능하게 해준다. - 이벤트기반으로 서버 소켓과 클라이언트 소켓을 연결하여서 실시간으로 양방향 통신이 가능하게 한다. <br> #### (2) 정적 파일을 제공한다. (자바스크립트, CSS 파일) ```javascript // 정적 파일을 제공한다. app.use("/css", express.static("./static/css")); app.use("/js", express.static("./static/js")); ``` - 정적 파일을 제공하기 위해 미들웨어(MiddleWare)를 사용한다. (여기서는 기본 제공 미들웨어를 사용한다. ) - 예시: `app.use('/test', express.static('./image/'))` - 서버: image 폴더의 파일들을 제공(액세스 가능) - 클라이언트: http://서버주소/test 로 액세스한다. - 미들웨어: 클라이언트에게 요청이 온 뒤, 요청을 보내기 위해 응답하려는 중간에서 목적에 맞게 처리를 하는 함수이다. <br> #### (3) 화면 구성 ```javascript // client가 최초 접속 시 보여지는 화면 // get(경로, 함수): 경로를 get방식으로 접속하면 함수를 호출한다. // 함수는 request와 response객체를 받는다. // request는 클라이언트에서 전달된 데이터와 정보들이 담겨 있다. // response에는 클라이언트에게 응답을 위한 정보가 들어있다. /* Get 방식으로 / 경로에 접속하면 실행 됨 */ app.get('/', function(request, response) { fs.readFile('./static/index.html', function(err, data) { if(err) { response.send('에러') } else { // HTML 파일라는 것을 알려야 하기때문에 해당 내용을 작성해서 보내준다. response.writeHead(200, {'Content-Type':'text/html'}) // HTML 데이터를 보내준다. response.write(data) // 모두 보냈으면 완료되었음을 알린다. response.end() } }) }) ``` - fs 모듈을 사용하여 index.html파일을 읽고 클라이언트로 해당 내용을 전달한다. - `readFIle()`메서드는 지정된 파일을 읽어서 데이터를 가져온다. <br> #### (4) 소켓 이벤트 ```javascript // io.sockets: 접속되는 모든 소켓들 // on (수신이벤트, 콜백함수): 콜백으로 전달되는 변수에는 상대가 전송한 데이터가 담겨져 온다. // 콜백함수에 의해 전달되는 소켓은 접속된 소켓을 의미한다. io.sockets.on('connection', function(socket){ // 새로운 유저가 접속했을 경우 다른 소캣에게도 알려준다. socket.on("join", function(name){ console.log(name + "님이 접속하였습니다.") // 소켓에 이름을 저장한다. socket.name = name // 모든 소켓에게 전송한다. io.sockets.emit("update", {type: "connect", name: "SERVER", message: `${name}님이 접속하였습니다.`}) }) // 유저 메시지 전달 socket.on('send', function(data){ // 받은 데이터에 누가 보냈는 지 이름을 추가한다. data.name = socket.name console.log(data) // 보낸 사람을 제외한 나머지 유저에게 메시지를 전송한다. socket.broadcast.emit("update", data) }); // 접속 종료 socket.on('disconnect', function(data){ // 이름이 없으면, 로그인을 하지 않은 것이기 때문에 종료 메시지를 보내지 않는다. if (socket.name === undefined) {return} console.log(socket.name + "님이 나가셨습니다.") // 나가는 사람을 제외한 나머지 유저에게 메시지를 전송한다. socket.broadcast.emit("update", {type: "disconnect", name: "SERVER", message: `${socket.name}님이 나가셨습니다.`}) }); }); ``` - `io.socket`: 전체 소켓 / `socket`: 접속된 소켓 (콜백함수에 의해 전달되었음) / `socket.broadcast`: 나를 제외한 소켓 - `on`: 수신, `emit`: 전송 - 접속된 모든 소켓에게 데이터 전달: `io.sockets.emit('이벤트명', 데이터)` - 나를 제외한 모든 소켓에게 데이터 전달: `socket.broadcast.emit('이벤트명', 데이터)` <br> #### (5) 서버 실행 ```javascript //서버 실행 (서버를 3000포트로 listen한다) server.listen(3000, function () { console.log("server listening on port : http://localhost:3000/"); }); ``` - `listen()`메서드를 통해, 원하는 포트번호로 서버를 시작할 수 있다. <br>
<template> <div> <!-- END: Top Bar --> <div class="intro-y flex flex-col sm:flex-row items-center mt-8"> <h2 class="text-lg font-medium mr-auto">Chat</h2> </div> <div class="intro-y chat grid grid-cols-12 gap-5 mt-5"> <!-- BEGIN: Chat Side Menu --> <div class="col-span-12 lg:col-span-4 2xl:col-span-3"> <div class="intro-y pr-1"> <div class="box p-2"> <ul class="nav nav-pills" role="tablist"> <li id="chats-tab" class="nav-item flex-1" role="presentation"> <button class="nav-link w-full py-2 active" type="button"> Chats </button> </li> </ul> </div> </div> <div class="tab-content"> <div id="chats" class="tab-pane active" role="tabpanel" aria-labelledby="chats-tab" > <!-- <div class="pr-1"> <div class="box px-5 pt-5 pb-5 lg:pb-0 mt-5"> <div class="relative text-slate-500"> <input type="text" class="form-control py-3 px-4 border-transparent bg-slate-100 pr-10" placeholder="Search for messages or users..." /> <i class="w-4 h-4 hidden sm:absolute my-auto inset-y-0 mr-3 right-0" data-lucide="search" ></i> </div> </div> </div> --> <div class="chat__chat-list overflow-y-auto scrollbar-hidden pr-1 pt-1 mt-4" > <div v-for="user in users" :key="user._id" @click="selectChat(user)" class="intro-x cursor-pointer box relative flex items-center p-5 mt-5" > <div class="w-12 h-12 flex-none image-fit mr-1"> <img v-if="user.avatar" class="tooltip rounded-full" :title=" user.avatarUploadDate ? 'Uploaded at ' + user.avatarUploadDate : 'Avatar Image' " alt="partner logo" :src="`${axiosBaseUrl}/${user.avatar}`" @error="handleAvatarError" @load="handleAvatarLoad" /> <img v-else src="../../../dist/images/logow.png" alt="profilecustomer" class="rounded-full" /> <div class="w-3 h-3 rounded-full absolute bottom-0 right-0 bg-success" v-if="user.isOnline" ></div> </div> <div class="ml-2 overflow-hidden"> <div class="flex items-center"> <a href="javascript:;" class="font-medium"> {{ user.firstName }} {{ user.lastName }}</a > <div class="text-xs text-slate-400 ml-auto"> <!-- 01:10 PM --> </div> </div> <div class="w-full truncate text-slate-500 mt-0.5"> {{ user.contact1 }} </div> </div> <div class="w-5 h-5 text-white text-center rounded-full bg-primary font-medium absolute top-0 right-0 -mt-1 -mr-1" v-if="user.unreadCount > 0" > {{ user.unreadCount }} </div> </div> </div> </div> </div> </div> <!-- END: Chat Side Menu --> <!-- BEGIN: Chat Content --> <div class="intro-y col-span-12 lg:col-span-8 2xl:col-span-9"> <div class="chat__box box"> <!-- BEGIN: Chat Active --> <div class="h-full flex flex-col"> <div class="flex flex-col sm:flex-row border-b border-slate-200/60 dark:border-darkmode-400 px-5 py-4" > <div class="flex items-center"> <div class="w-10 h-10 sm:w-12 sm:h-12 flex-none image-fit relative" > <img v-if="avatarCustomer" class="tooltip rounded-full" :title=" avatarCustomer.avatarUploadDate ? 'Uploaded at ' + avatarCustomer.avatarUploadDate : 'Avatar Image' " alt="Company logo" :src="`${axiosBaseUrl}/${avatarCustomer}`" @error="handleAvatarError" @load="handleAvatarLoad" /> </div> <!-- --> <div class="ml-3 mr-auto"> <div class="font-medium text-base"> {{ firstName }} {{ lastName }} </div> <div class="text-slate-500 text-xs sm:text-sm"> <!-- Hey, I am using chat <span class="mx-1">•</span> Online --> </div> </div> </div> </div> <div class="overflow-y-scroll scrollbar-hidden px-5 pt-5 flex-1" id="chat-container" > <div v-for="(message, index) in messages" :key="index" class="clear-both" > <div v-if="isCurrentUser(message)" class="chat__box__text-box flex items-end float-right mb-4" > <!-- <label>message: {{ message.receiverId._id }} and profile: {{ profileId }}</label> --> <div class="hidden sm:block dropdown mr-3 my-auto"> <a href="javascript:;" class="dropdown-toggle w-4 h-4 text-slate-500" aria-expanded="false" data-tw-toggle="dropdown" > <i data-lucide="more-vertical" class="w-4 h-4"></i> </a> </div> <div class="bg-primary px-4 py-3 text-white rounded-l-md rounded-t-md" > {{ message.text }} <div class="mt-1 text-xs text-white text-opacity-80"> {{ formatTimestamp(message.timestamp) }} </div> </div> <div class="w-10 h-10 hidden sm:block flex-none image-fit relative ml-5 rounded-full" > <img v-if="message.senderId && message.senderId.avatar" class="rounded-full" :title=" message.avatarUploadDate ? 'Uploaded at ' + message.avatarUploadDate : 'Avatar Image' " alt="Company logo" :src="`${axiosBaseUrl}/${message.senderId.avatar}`" @error="handleAvatarError" @load="handleAvatarLoad" /> <img v-else src="../../../dist/images/logow.png" alt="profilecustomer" class="rounded-full" /> </div> </div> <div v-else class="chat__box__text-box flex items-end float-left mb-4" > <div class="w-10 h-10 hidden sm:block flex-none image-fit relative mr-5" > <img v-if="message.senderId && message.receiverId.avatar" class="rounded-full" :title=" message.avatarUploadDate ? 'Uploaded at ' + message.avatarUploadDate : 'Avatar Image' " alt="Company logo" :src="`${axiosBaseUrl}/${message.senderId.avatar}`" @error="handleAvatarError" @load="handleAvatarLoad" /> <img v-else src="../../../dist/images/logow.png" alt="profilecustomer" class="rounded-full" /> </div> <div class="bg-slate-100 dark:bg-darkmode-400 px-4 py-3 text-slate-500 rounded-r-md rounded-t-md" > {{ message.text }} <div class="mt-1 text-xs text-slate-500"> {{ formatTimestamp(message.timestamp) }} </div> </div> </div> </div> </div> <div v-if="activechat" class="pt-4 pb-10 sm:py-4 flex items-center border-t border-slate-200/60 dark:border-darkmode-400" > <textarea class="chat__box__input form-control dark:bg-darkmode-600 h-16 resize-none border-transparent px-5 py-3 shadow-none focus:border-transparent focus:ring-0" rows="1" placeholder="Type your message..." v-model="newMessage" ></textarea> <div class="flex absolute sm:static left-0 bottom-0 ml-5 sm:ml-0 mb-5 sm:mb-0" > <div class="dropdown mr-3 sm:mr-5"> <a href="javascript:;" class="dropdown-toggle w-4 h-4 sm:w-5 sm:h-5 block text-slate-500" aria-expanded="false" data-tw-toggle="dropdown" > <i data-lucide="smile" class="w-full h-full"></i> </a> <div class="chat-dropdown dropdown-menu"> <div class="dropdown-content"></div> </div> </div> <div class="w-4 h-4 sm:w-5 sm:h-5 relative text-slate-500 mr-3 sm:mr-5" > <i data-lucide="paperclip" class="w-full h-full"></i> <input type="file" class="w-full h-full top-0 left-0 absolute opacity-0" /> </div> </div> <a href="javascript:;" @click="sendMessage" class="w-8 h-8 sm:w-10 sm:h-10 block bg-primary text-white rounded-full flex-none flex items-center justify-center mr-5" > <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-send-horizontal w-4 h-4" > <path d="m3 3 3 9-3 9 19-9Z" /> <path d="M6 12h16" /> </svg> </a> </div> </div> <!-- END: Chat Active --> <!-- BEGIN: Chat Default --> <div class="h-full flex items-center"> <div class="mx-auto text-center"> <div class="w-16 h-16 flex-none image-fit rounded-full overflow-hidden mx-auto" > <img alt="Midone - HTML Admin Template" src="dist/images/profile-13.jpg" /> </div> <div class="mt-3"> <div class="font-medium">Hey, Charlize Theron!</div> <div class="text-slate-500 mt-1"> Please select a chat to start messaging. </div> </div> </div> </div> <!-- END: Chat Default --> </div> </div> <!-- END: Chat Content --> </div> </div> <!-- END: Content --> </template> <script> import Cookies from "js-cookie"; import axios from "axios"; // Import Axios library export default { components: { // Picker, }, data() { return { activechat: false, firstName: "", lastName: "", avatarCustomer: "", users: [], messages: [], newMessage: "", profileId: "", showEmojiPicker: false, currentUser: { _id: this.profileId, // Replace with the logged-in user's ID }, receiverId: "", // receiverUser: { // _id: "RECEIVER_USER_ID", // Replace with the ID of the chat partner // }, selectedChat: null, // axiosBaseUrl: axios.defaults.baseURL, }; }, computed: { axiosBaseUrl() { return axios.defaults.baseURL; }, }, mounted() {}, created() { this.axios = axios; // Create a reference to axios this.fetchUsers(); this.getProfile(); // Connect to the socket server this.$socket.connect(); // Listen for the 'user-online' event from the server this.$socket.on("user-online", (userId) => { // Update online status for the specific user const user = this.users.find((user) => user._id === userId); if (user) { user.isOnline = true; } }); this.$socket.on("chat message", (message) => { console.log("ENTROU"); console.log("Received chat message:", message); this.fetchChatMessages(this.receiverUser); this.scrollToBottom(); }); // // Listen for the "notification" event // this.$socket.on("notification", (notificationMessage) => { // // Handle the received notification // // alert("Notification: " + notificationMessage); // console.log("Received notification:", notificationMessage); // // You can push the notification message to the notifications array // this.notifications.push(notificationMessage); // }); // Listen for the 'chat message read' event from the server this.$socket.on("chat-message-read", (receiverId) => { // Reset unread count for the specific user const user = this.users.find((user) => user._id === receiverId); if (user) { user.unreadCount = 0; } }); }, methods: { incrementUnreadCount(userId) { // Emit a socket event to increment unread count on the server this.$socket.emit("increment-unread-count", userId); }, resetUnreadCount(userId) { // Emit a socket event to reset unread count on the server this.$socket.emit("reset-unread-count", userId); }, isCurrentUser(message) { const isCurrent = message.senderId._id === this.profileId; return isCurrent; }, getProfile() { this.loading = true; const token = Cookies.get("token"); axios .get(`/api/me`, { headers: { token: token, }, }) .then((response) => { this.loading = false; // Update the component's data with the received response // console.log("Plano", response.data.user.plan[0].planName); this.profileId = response.data.user._id; console.log(this.profileId); }) .catch((error) => { this.errorMessage = "Error retrieving this user. Please try again."; // Set the error message console.error("Error retrieving plan:", error); }); }, fetchUsers() { this.loading = true; const token = Cookies.get("token"); axios .get("/api/user/manager/allcustomersfromlogedmanager", { headers: { token: token, }, }) .then((response) => { this.users = response.data.users; console.log("Usuarios: ", response.data.users); }) .catch((error) => { this.errorMessage = "Error retrieving this user. Please try again."; // Set the error message console.error("Error retrieving plan:", error); }); }, openEmojiPicker() { this.showEmojiPicker = true; }, addEmoji(emoji) { this.newMessage += emoji.native; }, closeEmojiPicker() { this.showEmojiPicker = false; }, openFilePicker() { this.$refs.fileInput.click(); }, attachFile(event) { const file = event.target.files[0]; // Perform necessary actions with the attached file (upload, etc.) console.log("Attached file:", file); }, selectChat(user) { this.selectedChat = user; this.receiverUser = user._id; this.firstName = user.firstName; this.lastName = user.lastName; this.avatarCustomer = user.avatar; this.activechat = true; this.fetchChatMessages(this.receiverUser); this.scrollToBottom(); }, async fetchChatMessages(receiverId) { const token = Cookies.get("token"); try { // Fetch messages from the server const response = await axios.get( `/api/chat/getmessages?senderId=${this.profileId}&receiverId=${receiverId}`, { headers: { token: token }, } ); // Update messages and emit socket event to mark messages as read this.messages = response.data.sort((a, b) => { return ( new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime() ); }); // Emit the 'chat-message-read' event to mark messages as read on the server this.$socket.emit("chat-message-read", receiverId); // Reset unread count locally const user = this.users.find((user) => user._id === receiverId); if (user) { user.unreadCount = 0; } // Scroll to the bottom of the chat container this.scrollToBottom(); } catch (error) { console.error("Error fetching chat messages:", error); } }, async sendMessage() { if (this.newMessage.trim() !== "") { const message = { text: this.newMessage, senderId: this.profileId, receiverId: this.receiverUser, }; const token = Cookies.get("token"); try { await axios.post("/api/chat/message", message, { headers: { token: token, }, }); if (message.receiverId === this.selectedChat._id) { // If the receiver is currently selected, push to the left side (receiver's side) this.messages.push({ ...message, senderId: this.selectedChat }); } else { // If not, push to the right side (sender's side) this.messages.push(message); } // Clear the new message input this.newMessage = ""; // Emit the chat message event this.$socket.emit("chat message", message); // Emit the notification event this.$socket.emit("notification", { receiverId: this.receiverUser, // message: "You have a new message", }); // Increment unread count this.incrementUnreadCount(message.receiverId); // Scroll to the bottom of the chat this.scrollToBottom(); } catch (error) { console.error("Error sending chat message:", error); } } }, scrollToBottom() { this.$nextTick(() => { const chatContainer = document.getElementById("chat-container"); if (chatContainer) { chatContainer.scrollTop = chatContainer.scrollHeight; } }); }, formatTimestamp(timestamp) { const currentTime = new Date(); const messageTime = new Date(timestamp); const timeDifference = currentTime - messageTime; const seconds = Math.floor(timeDifference / 1000); if (seconds < 60) { return `${seconds} seconds ago`; } const minutes = Math.floor(seconds / 60); if (minutes < 60) { return `${minutes} minutes ago`; } const hours = Math.floor(minutes / 60); if (hours < 24) { return `${hours} hours ago`; } const days = Math.floor(hours / 24); return `${days} days ago`; }, }, }; </script>
class WeatherModel { String lat; String lon; Current current; List<Daily> daily; WeatherModel({ required this.lat, required this.lon, required this.current, required this.daily, }); factory WeatherModel.fromJson(Map<String, dynamic> json) { final lat = json['lat'].toString(); final lon = json['lon'].toString(); final current = Current.fromJson(json['current']); final daily = <Daily>[]; if (json['daily'] != null) { json['daily'].forEach((v) { daily.add(Daily.fromJson(v)); }); } return WeatherModel( lat: lat, lon: lon, current: current, daily: daily, ); } } class Daily { String temp; String humidity; String dt; String windSpeed; String clouds; List<Weather> weatherDetail; Daily({ required this.temp, required this.dt, required this.humidity, required this.windSpeed, required this.weatherDetail, required this.clouds, }); factory Daily.fromJson(Map<String, dynamic> json) { final temp = json['temp']['max'].toString(); final humidity = json['humidity'].toString(); final dt = json['dt'].toString(); final windSpeed = json['wind_speed'].toString(); final clouds = json['clouds'].toString(); final weatherDetail = <Weather>[]; if (json['weather'] != null) { json['weather'].forEach((v) { weatherDetail.add(Weather.fromJson(v)); }); } return Daily( dt: dt, temp: temp, humidity: humidity, windSpeed: windSpeed, weatherDetail: weatherDetail, clouds: clouds, ); } } class Current { String temp; String humidity; String dt; String windSpeed; String clouds; List<Weather> weatherDetail; Current({ required this.temp, required this.dt, required this.humidity, required this.windSpeed, required this.weatherDetail, required this.clouds, }); factory Current.fromJson(Map<String, dynamic> json) { final temp = json['temp'].toString(); final humidity = json['humidity'].toString(); final dt = json['dt'].toString(); final windSpeed = json['wind_speed'].toString(); final clouds = json['clouds'].toString(); final weatherDetail = <Weather>[]; if (json['weather'] != null) { json['weather'].forEach((v) { weatherDetail.add(Weather.fromJson(v)); }); } return Current( dt: dt, temp: temp, humidity: humidity, windSpeed: windSpeed, weatherDetail: weatherDetail, clouds: clouds, ); } } class Weather { String main; String icon; Weather({ required this.main, required this.icon, }); factory Weather.fromJson(Map<String, dynamic> json) { final main = json['main']; final icon = json['icon']; return Weather( main: main, icon: icon, ); } }
import { tailwind, dark } from '@theme-ui/presets' const theme = { ...tailwind, containers: { card: { boxShadow: '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)', border: '1px solid', borderColor: 'muted', borderRadius: '4px', p: 2 }, page: { width: '100%', maxWidth: '1080px', m: 0, mx: 'auto' } }, styles: { ...tailwind.styles, footer: { width: '100%', m: 0, mx: 'auto', bg: 'muted' }, hr: { color: 'primary', width: '30%', mx: 'auto', my: '3' }, navBullet: { ml: 3, py: 2, cursor: 'pointer', textDecoration: 'none', ':hover': { color: 'primary' } }, nav: { ml: 1, py: 2, fontWeight: 'bold', cursor: 'pointer', textDecoration: 'none', color: 'text', ':hover': { color: 'primary' } }, navlink: { ml: 3, py: 2, cursor: 'pointer', fontWeight: 'bold', color: 'text', textDecoration: 'none', ':hover': { color: 'primary' } } }, buttons: { muted: { color: 'background', bg: 'muted' }, secondary: { color: 'muted', bg: 'text', '&:hover': { bg: 'secondary' } } }, links: { bold: { fontWeight: 'bold' } }, images: { ...tailwind.colors, avatar: { width: 48, height: 48, borderRadius: 99999 } }, colors: { transparent: 'transparent', black: '#000', white: '#fff', grayDark: '#2d3748', text: '#2d3748', background: '#fff', primary: '#2b6cb0', primaryHover: '#2c5282', secondary: '#718096', muted: '#F6FCFF', success: '#9ae6b4', info: '#63b3ed', warning: '#faf089', danger: '#feb2b2', light: '#f7fafc', dark: '#2d3748', index: '#4c4f52', textMuted: '#718096', modes: { dark: { ...dark.colors, index: '#9ea1a3' } } } } export default theme
import React from 'react'; import { act, fireEvent, render, renderHook, screen } from '@testing-library/react'; import history from 'history/browser'; import { DataModel } from '../context/DataModel'; import { EDIT_REPORT_PERMISSION, Permissions } from '../context/Permissions'; import * as fetch_server_api from '../api/fetch_server_api'; import { mockGetAnimations } from '../dashboard/MockAnimations'; import { ReportsOverview } from './ReportsOverview'; import { useHiddenTagsURLSearchQuery } from '../app_ui_settings'; import { createTestableSettings } from '../__fixtures__/fixtures'; beforeEach(() => { fetch_server_api.fetch_server_api = jest.fn().mockReturnValue({ then: jest.fn().mockReturnValue({ finally: jest.fn() }) }); mockGetAnimations() history.push("") }) afterEach(() => jest.restoreAllMocks()); const datamodel = { subjects: { subject_type: { name: "Subject type", metrics: ["metric_type"] } }, metrics: { metric_type: { name: "Metric type", tags: [] } } } function renderReportsOverview( { hiddenTags = null, reportDate = null, reports = [], reportsOverview = {}, } = {} ) { let settings = createTestableSettings() if (hiddenTags) { settings.hiddenTags = hiddenTags } render( <Permissions.Provider value={[EDIT_REPORT_PERMISSION]}> <DataModel.Provider value={datamodel}> <ReportsOverview dates={[reportDate || new Date()]} measurements={[{ status: "target_met" }]} report_date={reportDate} reports={reports} reports_overview={reportsOverview} settings={settings} /> </DataModel.Provider> </Permissions.Provider> ) } it('shows an error message if there are no reports at the specified date', async () => { renderReportsOverview({ reportDate: new Date() }) expect(screen.getAllByText(/Sorry, no reports existed at/).length).toBe(1); }); it('shows the reports overview', async () => { const reports = [{ subjects: {} }] const reportsOverview = { title: "Overview", permissions: {} } renderReportsOverview({ reports: reports, reportsOverview: reportsOverview }) expect(screen.getAllByText(/Overview/).length).toBe(1); }); it('shows the comment', async () => { const reports = [{ subjects: {} }] const reportsOverview = { title: "Overview", comment: "Commentary", permissions: {} } renderReportsOverview({ reports: reports, reportsOverview: reportsOverview }) expect(screen.getAllByText(/Commentary/).length).toBe(1); }); const reports = [ { report_uuid: "report_uuid", subjects: { subject_uuid: { metrics: { metric_uuid: { recent_measurements: [], tags: ["Foo"], type: "metric_type" }, metric_uuid2: { recent_measurements: [], tags: ["Bar"], type: "metric_type" } }, type: "subject_type", } } } ] const reportsOverview = { title: "Overview", permissions: {} } it('hides the report tag cards', async () => { const { result } = renderHook(() => useHiddenTagsURLSearchQuery()) renderReportsOverview({ reports: reports, reportsOverview: reportsOverview, hiddenTags: result.current }) expect(screen.getAllByText(/Foo/).length).toBe(2) expect(screen.getAllByText(/Bar/).length).toBe(2) fireEvent.click(screen.getAllByText(/Foo/)[0]) expect(result.current.value).toStrictEqual(["Bar"]) }) it('shows the report tag cards', async () => { history.push("?hidden_tags=Bar") const { result } = renderHook(() => useHiddenTagsURLSearchQuery()) renderReportsOverview({ reports: reports, reportsOverview: reportsOverview, hiddenTags: result.current }) expect(screen.getAllByText(/Foo/).length).toBe(2) expect(screen.queryAllByText(/Bar/).length).toBe(0) fireEvent.click(screen.getAllByText(/Foo/)[0]) expect(result.current.value).toStrictEqual([]) }) it('adds a report', async () => { fetch_server_api.fetch_server_api = jest.fn().mockResolvedValue({ ok: true }); renderReportsOverview(); fireEvent.click(screen.getByText(/Add report/)); expect(fetch_server_api.fetch_server_api).toHaveBeenLastCalledWith("post", "report/new", {}); }); it('copies a report', async () => { fetch_server_api.fetch_server_api = jest.fn().mockResolvedValue({ ok: true }); const reports = [{ report_uuid: "uuid", subjects: {}, title: "Existing report" }] renderReportsOverview({ reports: reports }) fireEvent.click(screen.getByText(/Copy report/)); await act(async () => { fireEvent.click(screen.getByRole("option")); }); expect(fetch_server_api.fetch_server_api).toHaveBeenLastCalledWith("post", "report/uuid/copy", {}); });
import numpy as np from VLMP.components.modelExtensions import modelExtensionBase class plates(modelExtensionBase): """ Component name: plates Component type: modelExtension Author: Pablo Ibáñez-Freire Date: 17/06/2023 Common epsilon, sigma plates for particles in the system. :param platesSeparation: Distance between plates. :param epsilon: Energy parameter for the plates. :param sigma: Length parameter for the plates. :param compressionVelocity: Velocity at which the plates are compressed. :param minPlatesSeparation: Minimum distance between plates. :param maxPlatesSeparation: Maximum distance between plates. """ def __init__(self,name,**params): super().__init__(_type = self.__class__.__name__, _name = name, availableParameters = {'platesSeparation', 'epsilon','sigma', 'compressionVelocity', 'minPlatesSeparation','maxPlatesSeparation'}, requiredParameters = {"platesSeparation", "epsilon","sigma"}, availableSelections = {"selection"}, requiredSelections = set(), **params) ############################################################ ############################################################ ############################################################ platesSeparation = params.get("platesSeparation","auto") epsilon = params["epsilon"] sigma = params["sigma"] compressionVelocity = params.get("compressionVelocity",0.0) minPlatesSeparation = params.get("minPlatesSeparation",None) maxPlatesSeparation = params.get("maxPlatesSeparation",None) parameters = {"platesEpsilon":epsilon, "platesSigma":sigma, "compressionVelocity":compressionVelocity} if "selection" in params and platesSeparation != "auto": self.logger.warning("Selection is ignored when platesSeparation is not set to 'auto'") if platesSeparation == "auto": # Check if selection is defined if "selection" not in params: self.logger.error("Selection must be defined when platesSeparation is set to 'auto'") raise ValueError("No selection defined") else: selectedIds = self.getSelection("selection") idsPositions = self.getIdsState(selectedIds,"position") if len(idsPositions) == 0: self.logger.error("Selection is empty") raise ValueError("Empty selection") platesSeparation = np.max(np.abs(np.array(idsPositions)[:,2]))+sigma platesSeparation = 2*platesSeparation self.logger.info("Plates separation set to {}".format(platesSeparation)) parameters["platesSeparation"] = platesSeparation else: parameters["platesSeparation"] = float(platesSeparation) if minPlatesSeparation is not None: parameters["minPlatesSeparation"] = minPlatesSeparation if maxPlatesSeparation is not None: parameters["maxPlatesSeparation"] = maxPlatesSeparation extension = {} extension[name] = {} extension[name]["type"] = ["External","Plates"] extension[name]["parameters"] = parameters ############################################################ self.setExtension(extension)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> // array destructuring let user = ["murat", "baran", "kocaeli", "izmit",43591]; // let [firstname,lastname,city,town ] = user; let [firstname,lastname,...adress ] = user; // console.log(firstname,lastname,city,town); // console.log(firstname,lastname,town); // console.log(firstname,town); console.log(firstname,lastname,adress); // let colors = ["blue", "red", "yellow", "black"]; // let[color1, color2, ,color4] = colors; // console.log(color1,color2,color4); //object destructuring let urun = { marka : "Apple", model : "iPhone 13" } function urunGoster(obj){ let {marka, model, fiyat=0, satisDurumu = false} = urun; console.log(marka, model, fiyat, satisDurumu); } urunGoster(urun); </script> </body> </html>
<template> <div class="header"> <div class="container"> <div class="header-wrapper"> <div class="header-left"> <div class="top-menu"> <ul> <li><nuxt-link to="/">Главная</nuxt-link></li> <li><nuxt-link to="/clothes">Магазин</nuxt-link></li> </ul> </div> </div> <div class="logo"> <nuxt-link to="/" ><img src="~/static/assets/images/logo.png" alt="" /></nuxt-link> </div> <div class="header-right"> <!-- <div class="currency"> <a href="#"><i class="c1"></i></a> <a class="active" href="#"><i class="c2"></i></a> <a href="#"><i class="c3"></i></a> <a href="#"><i class="c4"></i></a> </div> --> <div class="signin"> <div class="cart-sec"> <button class="cart-length" @click="showModal"> <img src="~/static/assets/images/cart.png" alt="cart" /><span>{{ `(${cartItemCount})` }}</span> </button> </div> <ul v-if="!this.checkAuthUser"> <li> <nuxt-link to="auth/registration">Регистрация</nuxt-link> <span>/</span> &nbsp; </li> <li><nuxt-link to="auth/login">Вход</nuxt-link></li> </ul> <v-btn @click="logoutUser" v-else class="ma-2 signout" text icon large left color="white"> <v-icon>mdi-logout-variant</v-icon> Выйти </v-btn> </div> </div> <!-- <div class="clearfix"></div> --> </div> </div> <cart-modal /> </div> </template> <script> import { mapGetters } from "vuex"; import CartModal from "~/components/Cart/CartModal.vue"; export default { data() { return { // cart: [] }; }, components: { CartModal, }, computed: { ...mapGetters("cart", ["getCart", "getCartModal"]), ...mapGetters("user", ["checkAuthUser"]), cartItemCount() { return this.getCart.length || 0; }, }, methods: { showModal() { this.$store.dispatch("cart/openModal"); }, logoutUser() { this.$store.dispatch("user/logoutUser") .then(()=>{this.$router.push('/')}) } }, // mounted() { // let cart = JSON.parse(localStorage.getItem('cart')); // this.cart = cart || [] // console.log(cart) // // let cartObj = JSON.parse(localStorage.getItem('cart')); // // let cart = cartObj.find((c) => c.key === 'cart'); // // this.cart = cart // }, }; </script>
<?php function generateJWT($user) { // Definir el header del token $header = [ 'alg' => 'HS256', // Algoritmo de encriptación 'typ' => 'JWT' // Tipo de token ]; // Convertir el header a JSON y codificarlo en Base64 $encoded_header = base64_encode(json_encode($header)); // Definir el payload del token $payload = [ 'user_id' => $user['id'], 'email' => $user['email'], 'exp' => time() + (60 * 60) // Expiración del token en 1 hora ]; // Convertir el payload a JSON y codificarlo en Base64 $encoded_payload = base64_encode(json_encode($payload)); // Crear la parte de la firma (sin firmar aún) $signature = hash_hmac('sha256', $encoded_header . '.' . $encoded_payload, 'tu_clave_secreta', true); // Codificar la firma en Base64 $encoded_signature = base64_encode($signature); // Concatenar el header, el payload y la firma para formar el token completo $jwt_token = $encoded_header . '.' . $encoded_payload . '.' . $encoded_signature; return $jwt_token; } function jwt_decode($token) { // Verificar si el token está vacío if (empty($token)) { return false; } // Dividir el token en sus partes (encabezado, carga útil y firma) $token_parts = explode('.', $token); // Verificar si hay tres partes if (count($token_parts) !== 3) { return false; } // Decodificar la carga útil (parte del token que contiene los datos) $payload = base64_decode($token_parts[1]); // Convertir la carga útil decodificada en un array asociativo $decoded_payload = json_decode($payload, true); // Verificar si el token ha expirado if (isset($decoded_payload['exp']) && $decoded_payload['exp'] < time()) { return false; // Token expirado } // Devolver true si todas las verificaciones pasan, de lo contrario, false return true; }
import { type FC, useState, useMemo, useCallback, useRef } from "react"; import { DndProvider } from "react-dnd"; import { HTML5Backend } from "react-dnd-html5-backend"; import { EditorFieldComponentsTemplateSection } from "./component-template"; import { EditorDatasetSection } from "./dataset"; import { EditorInspectorEmphasisPropertyTemplateSection } from "./emphasis-property-template"; import { EditorBar, EditorPanel } from "./ui-components"; import { EditorNotice, EditorNoticeRef } from "./ui-components/editor/EditorNotice"; import useCache from "./useCache"; export const PLATEAUVIEW_EDITOR_DOM_ID = "__plateauview_editor__"; export const Editor: FC = () => { const [editorType, setEditorType] = useState("dataset"); const editorTypes = useMemo( () => [ { title: "Dataset Editor", value: "dataset", }, { title: "Field Components Template Editor", value: "fieldComponentsTemplate", }, { title: "Inspector Emphasis Property Template Editor", value: "inspectorEmphasisPropertyTemplate", }, ], [], ); const handleEditorTypeChange = useCallback((editorType: string) => { setEditorType(editorType); }, []); const cache = useCache(); const editorNoticeRef = useRef<EditorNoticeRef>(null); return ( <div id={PLATEAUVIEW_EDITOR_DOM_ID}> <DndProvider backend={HTML5Backend}> <EditorBar editorTypes={editorTypes} editorType={editorType} onEditorTypeChange={handleEditorTypeChange} /> <EditorPanel> {editorType === "dataset" ? ( <EditorDatasetSection cache={cache} editorNoticeRef={editorNoticeRef} /> ) : editorType === "fieldComponentsTemplate" ? ( <EditorFieldComponentsTemplateSection editorNoticeRef={editorNoticeRef} /> ) : editorType === "inspectorEmphasisPropertyTemplate" ? ( <EditorInspectorEmphasisPropertyTemplateSection editorNoticeRef={editorNoticeRef} /> ) : null} <EditorNotice ref={editorNoticeRef} /> </EditorPanel> </DndProvider> </div> ); };
/* 3243 - FlattenDepth ------- by jiangshan (@jiangshanmeta) #medium #array ### Question Recursively flatten array up to depth times. For example: ```typescript type a = FlattenDepth<[1, 2, [3, 4], [[[5]]]], 2> // [1, 2, 3, 4, [5]]. flattern 2 times type b = FlattenDepth<[1, 2, [3, 4], [[[5]]]]> // [1, 2, 3, 4, [[5]]]. Depth defaults to be 1 ``` If the depth is provided, it's guaranteed to be positive integer. > View on GitHub: https://tsch.js.org/3243 */ /* _____________ Your Code Here _____________ */ // 제 3의 파라미터 R의 length를 이용해 count type Flatten<T extends unknown[]> = T extends [infer A, ...infer B] ? A extends unknown[] ? [...A, ...Flatten<B>] : [A, ...Flatten<B>] : []; type FlattenDepth< T extends unknown[], C extends number = 1, R extends unknown[] = [] > = T extends Flatten<T> ? T : C extends R["length"] ? T : FlattenDepth<Flatten<T>, C, [unknown, ...R]>; /* _____________ Test Cases _____________ */ import type { Equal, Expect } from "@type-challenges/utils"; type cases = [ Expect<Equal<FlattenDepth<[]>, []>>, Expect<Equal<FlattenDepth<[1, 2, [[3]], 4]>, [1, 2, [3], 4]>>, Expect<Equal<FlattenDepth<[1, [2]]>, [1, 2]>>, Expect<Equal<FlattenDepth<[1, 2, [3, 4], [[[5]]]], 2>, [1, 2, 3, 4, [5]]>>, Expect<Equal<FlattenDepth<[1, 2, [3, 4], [[[5]]]]>, [1, 2, 3, 4, [[5]]]>>, Expect<Equal<FlattenDepth<[1, [2, [3, [4, [5]]]]], 3>, [1, 2, 3, 4, [5]]>>, Expect< Equal<FlattenDepth<[1, [2, [3, [4, [5]]]]], 19260817>, [1, 2, 3, 4, 5]> > ]; /* _____________ Further Steps _____________ */ /* > Share your solutions: https://tsch.js.org/3243/answer > View solutions: https://tsch.js.org/3243/solutions > More Challenges: https://tsch.js.org */
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeContentPadding import androidx.compose.material.MaterialTheme import androidx.compose.material.SnackbarHost import androidx.compose.material.SnackbarHostState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import moe.tlaster.precompose.PreComposeApp import moe.tlaster.precompose.navigation.NavHost import moe.tlaster.precompose.navigation.rememberNavigator @Composable fun App() { PreComposeApp { MaterialTheme { val scope = rememberCoroutineScope() val snackBarState by remember { mutableStateOf(SnackbarHostState()) } val navigator = rememberNavigator() Box(modifier = Modifier.fillMaxSize()) { NavHost( navigator = navigator, initialRoute = "pageA" ) { scene("pageA") { PageA(scope, snackBarState, navigator) } scene("pageB") { PageB(scope, snackBarState, navigator) } scene("pageC") { PageC(scope, snackBarState, navigator, "TEST") } } SnackbarHost( hostState = snackBarState, modifier = Modifier.safeContentPadding() .align(Alignment.TopCenter).padding(top = 56.dp) ) } } } }
package com.hads.digicom.ui.screens.home import android.util.Log import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid import androidx.compose.foundation.lazy.grid.itemsIndexed import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.hads.digicom.R import com.hads.digicom.data.model.home.AmazingItem import com.hads.digicom.data.remote.NetworkResult import com.hads.digicom.ui.theme.darkText import com.hads.digicom.ui.theme.spacing import com.hads.digicom.utils.DigitHelper import com.hads.digicom.viewmodel.HomeViewModel @Composable fun MostVisitedOfferSection( viewModel: HomeViewModel = hiltViewModel() ) { var mostVisitedList by remember { mutableStateOf<List<AmazingItem>>(emptyList()) } var loading by remember { mutableStateOf(false) } val mostVisitedResult by viewModel.mostVisitedItems.collectAsState() when (mostVisitedResult) { is NetworkResult.Success -> { mostVisitedList = mostVisitedResult.data ?: emptyList() loading = false } is NetworkResult.Error -> { loading = false Log.e("3636", "MostVisitedOfferSection error : ${mostVisitedResult.message}") } is NetworkResult.Loading -> { loading = true } } Column( modifier = Modifier .fillMaxSize() .padding(MaterialTheme.spacing.small) ){ Text( text = stringResource(id = R.string.most_visited_products), modifier = Modifier .fillMaxWidth(), textAlign = TextAlign.Start, style = MaterialTheme.typography.h3, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colors.darkText, ) LazyHorizontalGrid( rows = GridCells.Fixed(3), modifier = Modifier .padding(top = MaterialTheme.spacing.medium) .height(250.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), verticalArrangement = Arrangement.spacedBy(4.dp) ){ itemsIndexed(mostVisitedList){index, item -> ProductHorizontalCard( name = item.name, id = DigitHelper.digitByLocate((index+1).toString()), imageUrl = item.image ) } } } }
class ReschedulableTimeout { private timeout: NodeJS.Timeout | undefined = undefined; constructor(public readonly intervalMs: number) {} public schedule(cb: () => void) { this.stop(); this.timeout = setTimeout(() => { this.stop(); cb(); }, this.intervalMs); } public stop() { if (this.timeout) { clearTimeout(this.timeout); this.timeout = undefined; } } } export class HeartbeatWebSocket extends WebSocket { private clientSendingDataTimer = new ReschedulableTimeout(25_000); private clientReceivingDataTimer = new ReschedulableTimeout(10_000); private heartbeatTimeoutTimer = new ReschedulableTimeout(5_000); constructor(url: string) { super(url); this.addEventListener("open", () => { this.afterReceivingData(); setTimeout(() => { this.afterSendingData(); }, 1000); }); this.addEventListener("close", () => this.afterDisconnecting()); this.addEventListener("message", () => this.afterReceivingData()); } public send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void { super.send(data); this.afterSendingData(); } private afterSendingData() { this.clientSendingDataTimer.schedule(() => this.send("ping")); } private afterReceivingData() { this.heartbeatTimeoutTimer.stop(); this.clientReceivingDataTimer.schedule(() => { this.send("ping"); this.heartbeatTimeoutTimer.schedule(() => this.terminate()); }); } private afterDisconnecting() { this.clientReceivingDataTimer.stop(); this.clientSendingDataTimer.stop(); this.heartbeatTimeoutTimer.stop(); } private terminated: boolean = false; private terminate() { this.dispatchEvent( new CloseEvent("close", { reason: "heartbeat failed", code: 1000, wasClean: false, }) ); this.terminated = true; this.close(); } public addEventListener<K extends keyof WebSocketEventMap>( type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined ): void; public addEventListener( type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined ): void; public addEventListener( type: any, listener: any, options?: any ): void { super.addEventListener( type, (...args: any[]) => { if (this.terminated) { return; } else { return listener(...args); } }, options ); } }
import React, { useContext } from "react"; import { FaGithub } from "react-icons/fa"; import { Link, NavLink } from "react-router-dom"; import { AuthContext } from "../../Providers/AuthProvider"; const Header = () => { const { user, logout } = useContext(AuthContext); // console.log(user?.email); // console.log(user?.displayName); // console.log(user?.photoURL); const photoURL = user && user.photoURL; const userName = user && user.displayName; const handleLogout = () => { logout() .then() .catch((err) => { console.log(err); }); }; const activeNaveStyles = ({ isActive }) => { return { fontWeight: isActive ? "bold" : "normal", textDecoration: isActive ? "none" : "underline", }; }; return ( <div className="ms-8 me-8 mt-0"> <div className="navbar bg-secondary rounded-br-lg rounded-bl-lg py-6"> <div className="navbar-start flex flex-col lg:flex-row"> <div className="dropdown mb-3 lg:mb-0"> <label tabIndex={0} className="btn btn-ghost text-primary lg:hidden" > <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 6h16M4 12h8m-8 6h16" /> </svg> </label> <ul tabIndex={0} className="menu menu-sm dropdown-content mt-3 p-2 shadow bg-base-100 rounded-box w-52" > <li> <Link to={"/"}> <p className="">Home</p> </Link> </li> <li> <Link to={"/blogs"}> <p>Blogs</p> </Link> </li> <li> <Link to={"/orderonline"}> <p>Order Online</p> </Link> </li> </ul> </div> <div className="flex content-center"> <a className="normal-case text-4xl font-bold text-primary ms-8 flex hover:scale-110 transition-transform duration-300"> Baratie Restaurant </a> </div> </div> <div className="navbar-center hidden lg:flex"> <div className="menu menu-horizontal px-1"> <NavLink style={activeNaveStyles} className="text-primary hover:scale-110 transition-transform duration-300 underline" to={"/"} > Home </NavLink> <NavLink style={activeNaveStyles} className="me-8 ms-8 text-primary hover:scale-110 transition-transform duration-300 underline" to={"/blogs"} > Blogs </NavLink> <NavLink style={activeNaveStyles} className="text-primary hover:scale-110 transition-transform duration-300 underline" to={"/orderonline"} > Order Online </NavLink> </div> </div> <div className="navbar-end"> <ul className="flex me-8 align-middle items-center"> {user?.photoURL ? ( <div className="tooltip tooltip-left" data-tip={userName}> <img className="w-10 rounded-full text-white text-3xl hover:scale-110 transition-transform duration-300" src={photoURL} alt="User Photo" /> </div> ) : ( <div className="tooltip tooltip-left" data-tip="Guest"> <img className="w-10 rounded-full ring-offset-base-100 ring-offset-2 bg-white text-3xl hover:scale-110 transition-transform duration-300" src="https://i.ibb.co/m6k8XWR/Pngtree-user-avatar-placeholder-black-6796227.png" alt="User Photo" /> </div> )} {user?.email ? ( <Link to={"/"}> <div onClick={handleLogout} className="text-primary text-m ms-4 hover:scale-110 transition-transform duration-300" > Logout </div> </Link> ) : ( <Link to={"/login"}> <div className="text-primary text-m ms-4 hover:scale-110 transition-transform duration-300"> Login </div> </Link> )} </ul> </div> </div> </div> ); }; export default Header;
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ByCapitalComponent } from './country/pages/by-capital/by-capital.component'; import { ByCountryComponent } from './country/pages/by-country/by-country.component'; import { ByRegionComponent } from './country/pages/by-region/by-region.component'; import { ViewCountryComponent } from './country/pages/view-country/view-country.component'; const routes: Routes = [ { path: '', component: ByCountryComponent, pathMatch: 'full', }, { path: 'region', component: ByRegionComponent, }, { path: 'capital', component: ByCapitalComponent, }, { path: 'country/:countryId', component: ViewCountryComponent, }, { path: '**', redirectTo: '', }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
// Problem Statement: Create a JavaScript library for managing authentication tokens in a web application. // Ensure that these tokens are stored securely and cannot be accessed directly or tampered with. const TokenManager = (function () { // Symbol to store token securely const tokenSymbol = Symbol('authToken'); // Private function to generate a random token function generateToken() { return Math.random().toString(36).substr(2); } // Public API for token management return { // Method to set token for a user object setToken(userObject, token) { // Store token using symbol to make it inaccessible from outside userObject[tokenSymbol] = token; }, // Method to get token for a user object getToken(userObject) { // Retrieve token using the symbol return userObject[tokenSymbol]; }, // Method to generate and set a new token for a user object generateAndSetToken(userObject) { // Generate a new token const token = generateToken(); // Set the generated token for the user object this.setToken(userObject, token); }, }; })(); // Usage example const user = { username: 'john_doe' }; // Generate and set token for the user TokenManager.generateAndSetToken(user); console.log(user); // { username: 'john_doe' } console.log(TokenManager.getToken(user)); // <random token>
<template> <td :class="cellData['class'] ? cellData['class'] : null"> <!-- Sorting key --> <span v-if="cellData['sort']" class="hidden"> {{ cellData["sort"] }} </span> <!-- Icons or Emoji --> <span v-if="cellData['icon']" class="glyphicon" :class="cellData['icon']"> </span> <span v-if="cellData['emoji']" class="emoji" > {{ cellData["emoji"] }} </span> <!-- Tooltip/Popovers Hovers Wrapper --> <span :title="cellData['tooltip']" :data-toggle="cellData['popover'] || cellData['tooltip'] ? 'tooltip' : ''" v-on:mouseover="checkForPopover"> <!-- Links and modals --> <span v-if="cellData['link'] || cellData['modal']"> <a v-if="cellData['link']" :href="cellData['link']" > <span v-html="cellData['text']"></span> </a> <a v-if="cellData['modal']" :data-target="cellData['modal']" > <span v-html="cellData['text']"></span> </a> </span> <span v-else> <span v-html="cellData['text']"></span> </span> </span> <span v-if="cellData['subtext']"> <br><span class="small" v-html="cellData['subtext']"></span> </span> <div class="popover-raw hide" v-if="canSupportPopover"> <li v-for="popItem in popOverContent" class="list-group-item"> <a v-if="popItem['link']" :href="popItem['link']"> {{{ popItem['text'] }}} </a> <span v-else> {{{ popItem['text'] }}} </span> </li> </div> </td> </template> <script> import PopoverMixin from '../mixins/PopoverMixin.vue' export default { mixins: [PopoverMixin], props: { cellData: Object, }, computed: { canSupportPopover: function() { if (typeof this.cellData['popover'] !== 'undefined') { if (this.cellData['popover'].hasOwnProperty('content')) { return true } } return false }, popOverContent: function () { if (this.canSupportPopover === true) { return this.cellData['popover']['content'].filter(function(key){ return key['text'] !== "" }); } return false } }, methods: { getPopOverTitle: function() { return this.cellData['popover']['title']; }, checkForPopover: function(event) { // Need to check the data exists for a popover before constructing it if (this.canSupportPopover === true) { this.setupPopover(event); } }, emitSignal: function(signalName, signalData) { this.$dispatch(signalName, signalData) } } } </script>
/* Name: Orhun Ege Çelik Section: 3 Student Number: 22202321 */ #ifndef EMPLOYEE_H #define EMPLOYEE_H #include <iostream> #include <string> #include "Issue.h" using namespace std; class Employee{ public: Employee(); Employee(const string name, const string title); Employee(const Employee& prevEmployee); Employee& operator=(const Employee& rightEmployee); ~Employee(); bool addIssue(Issue* newIssue); bool removeIssue(const int issueId); string getName() const; string getTitle() const; int getIssueCount() const; void setIssueCount(int count); void setName(const string name); void setTitle(const string title); void increaseIssueCount(); void decreaseIssueCount(); Issue*& getIssues(); string showEmployee() const; private: Issue* issues; int issueCount; string name; string title; }; #endif
using App.Test._4_Infrastructure.Context; using Data.Repository; using Domain.Entities; using Microsoft.EntityFrameworkCore; using Xunit; namespace Data.Tests.Repository { public class ClienteRepositoryTests { private readonly MySQLContextTests _context; private readonly ClienteRepository _repository; public ClienteRepositoryTests() { var optionsBuilder = new DbContextOptionsBuilder<MySQLContextTests>(); optionsBuilder.UseInMemoryDatabase(databaseName: "TestDatabase"); var options = optionsBuilder.Options; _context = new MySQLContextTests(options); _repository = new ClienteRepository(_context); } [Trait("Categoria", "ClienteRepository")] [Fact(DisplayName = "GetClientes_DeveRetornarTodosOsClientes")] public async Task GetClientes_DeveRetornarTodosOsClientes() { // Arrange var clientes = new List<Cliente> { new Cliente { IdCliente = 1, Nome = "Cliente 1", Sobrenome= "Teste1", CPF = "12345678901", Email = "teste1@email.com" }, new Cliente { IdCliente = 2, Nome = "Cliente 2", Sobrenome= "Teste2", CPF = "98765432109", Email = "teste2@email.com" }, new Cliente { IdCliente = 3, Nome = "Cliente 3", Sobrenome= "Teste3", CPF = "45678912345", Email = "teste3@email.com" } }; _context.Cliente.AddRange(clientes); await _context.SaveChangesAsync(); // Act var result = await _repository.GetClientes(); // Assert Assert.Equal(clientes, result); } [Trait("Categoria", "ClienteRepository")] [Fact(DisplayName = "GetClientes_DeveRetornarNuloQuandoNaoHaClientes")] public async Task GetClientes_DeveRetornarNuloQuandoNaoHaClientes() { // Arrange _context.Cliente.RemoveRange(_context.Cliente); await _context.SaveChangesAsync(); // Act var result = await _repository.GetClientes(); // Assert Assert.NotNull(result); Assert.Empty(result); } [Trait("Categoria", "ClienteRepository")] [Fact(DisplayName = "GetClienteById_DeveRetornarClientePorId")] public async Task GetClienteById_DeveRetornarClientePorId() { // Arrange _context.Cliente.RemoveRange(_context.Cliente); var cliente = new Cliente { IdCliente = 5, Nome = "Cliente 10", Sobrenome = "Teste10", CPF = "12345678901", Email = "teste@email.com" }; _context.Cliente.Add(cliente); await _context.SaveChangesAsync(); // Act var result = await _repository.GetClienteById(cliente.IdCliente); // Assert Assert.Equal(cliente, result); } [Trait("Categoria", "ClienteRepository")] [Fact(DisplayName = "GetClienteById_DeveRetornarNuloQuandoClienteNaoExiste")] public async Task GetClienteById_DeveRetornarNuloQuandoClienteNaoExiste() { // Arrange _context.Cliente.RemoveRange(_context.Cliente); var cliente = new Cliente { IdCliente = 10, Nome = "Cliente 10", Sobrenome = "Teste10", CPF = "12345678901", Email = "teste@email.com.br" }; _context.Cliente.Add(cliente); await _context.SaveChangesAsync(); // Act var result = await _repository.GetClienteById(20); // Assert Assert.Null(result); } [Trait("Categoria", "ClienteRepository")] [Fact(DisplayName = "GetClienteByCpf_DeveRetornarClientePorCpf")] public async Task GetClienteByCpf_DeveRetornarClientePorCpf() { // Arrange _context.Cliente.RemoveRange(_context.Cliente); var cliente = new Cliente { IdCliente = 101, Nome = "Cliente 101", Sobrenome = "Teste101", CPF = "12345678901", Email = "teste@email.com" }; _context.Cliente.Add(cliente); await _context.SaveChangesAsync(); // Act var result = await _repository.GetClienteByCpf(cliente.CPF); // Assert Assert.Equal(cliente, result); } [Trait("Categoria", "ClienteRepository")] [Fact(DisplayName = "GetClienteByCpf_DeveRetornarNuloQuandoClienteNaoExiste")] public async Task GetClienteByCpf_DeveRetornarNuloQuandoClienteNaoExiste() { // Arrange _context.Cliente.RemoveRange(_context.Cliente); var cliente = new Cliente { IdCliente = 102, Nome = "Cliente 102", Sobrenome = "Teste101", CPF = "12345678901", Email = "teste@email.com.br" }; _context.Cliente.Add(cliente); await _context.SaveChangesAsync(); // Act var result = await _repository.GetClienteByCpf("12345678902"); // Assert Assert.Null(result); } [Trait("Categoria", "ClienteRepository")] [Fact(DisplayName = "PostCliente_DeveAdicionarCliente")] public async Task PostCliente_DeveAdicionarCliente() { // Arrange _context.Cliente.RemoveRange(_context.Cliente); var cliente = new Cliente { IdCliente = 10, Nome = "Cliente 10", Sobrenome = "Teste10", CPF = "12345678901", Email = "teste@email.com.br" }; // Act var result = await _repository.PostCliente(cliente); // Assert Assert.Equal(cliente, result); } [Trait("Categoria", "ClienteRepository")] [Fact(DisplayName = "UpdateCliente_DeveAtualizarCliente")] public async Task UpdateCliente_DeveAtualizarCliente() { // Arrange _context.Cliente.RemoveRange(_context.Cliente); var cliente = new Cliente { IdCliente = 103, Nome = "Cliente 103", Sobrenome = "Teste103", CPF = "12345678901", Email = "teste@email.com.br" }; _context.Cliente.Add(cliente); await _context.SaveChangesAsync(); // Act cliente.Nome = "Cliente 113"; var result = await _repository.UpdateCliente(cliente); // Assert Assert.Equal(1, result); } [Trait("Categoria", "ClienteRepository")] [Fact(DisplayName = "DeleteCliente_DeveExcluirCliente")] public async Task DeleteCliente_DeveExcluirCliente() { // Arrange _context.Cliente.RemoveRange(_context.Cliente); var cliente = new Cliente { IdCliente = 10, Nome = "Cliente 10", Sobrenome = "Teste10", CPF = "12345678901", Email = "teste@email.com.br" }; _context.Cliente.Add(cliente); await _context.SaveChangesAsync(); // Act var result = await _repository.DeleteCliente(cliente.IdCliente); // Assert Assert.Equal(1, result); } #region [Dispose] [Trait("Categoria", "ClienteRepository")] [Fact(DisplayName = "Dispose_DeveDescartarContexto")] public void Dispose_DeveDescartarContexto() { // Arrange _context.Cliente.RemoveRange(_context.Cliente); var cliente = new Cliente { IdCliente = 106, Nome = "Cliente 106", Sobrenome = "Teste107", CPF = "12345678901", Email = "teste1@email.com" }; _context.Cliente.Add(cliente); _context.SaveChanges(); // Act _repository.Dispose(); // Assert Assert.NotNull(_context); } [Trait("Categoria", "ClienteRepository")] [Fact(DisplayName = "Dispose")] public void Dispose() { //act _repository.Dispose(); Assert.NotNull(_context); } #endregion } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { EducacionComponent } from './components/educacion/educacion.component'; import { ExperienciaComponent } from './components/experiencia/experiencia.component'; import { HabilidadesComponent } from './components/habilidades/habilidades.component'; import { ProyectosComponent } from './components/proyectos/proyectos.component'; import { HomePageComponent } from './pages/homepage/homepage.component'; import { RegisterComponent } from './pages/register/register.component'; import { LoginComponent } from './pages/login/login.component'; import { ContactPageComponent} from './pages/contactpage/contactpage.component' import { Error404Component } from './pages/error404/error404.component'; const routes: Routes = [ { path:'', component: HomePageComponent }, { path:'login', component: LoginComponent }, { path:'registro', component: RegisterComponent }, { path:'404', component: Error404Component }, { path:'contact', component: ContactPageComponent } /* { path:'jobs', component: ExperienciaComponent }, { path:'education', component: EducacionComponent }, { path:'skills', component: HabilidadesComponent }, { path:'proyects', component: ProyectosComponent } */ ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
<div class="container-fluid"> <div class="row"> <div class="col-xl-12 p-2 bg-primary text-white"> <h4 class="float-left">{{"supervisor.management" | translate}}</h4> <div class="float-right"> <button style="background-color: #fff;color: #3A7CEC;" pButton pRipple type="button" label="{{ 'add.new' | translate }}" icon="pi pi-plus" (click)="openDialog()"></button> </div> </div> </div> <div class="row my-3"> <div class="col-xl-12"> {{"action" | translate}} : <p-dropdown class="Super_Vis" placeholder="Select action" [options]="action" [(ngModel)]="selectedAction" optionLabel="name" [showClear]="true"></p-dropdown> <button pButton pRipple type="button" label="{{ 'apply' | translate }}" class="p-button-sm p-button-outlined ml-2" (click)="openDialogBox()"></button> <p-button label="{{ 'filter' | translate }}" class="float-right" (click)="onFilterOpen()"><i class="fa fa-filter mr-1"></i></p-button> </div> </div> <div class="row"> <div class="col-xl-12"> <div class="card bg-grey2" *ngIf="isFilterOpened"> <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="p-field"> <label for="email">{{ "email.address" | translate }} : </label> <input type="text" id="email_searchbox" class="form-control" [(ngModel)]="emailFilterValue" placeholder="{{'type.to.filter' | translate}}" /> </div> </div> <div class="col-md-6 d-flex align-items-center d-inline-block" mt-> <button pButton type="button" class="p-button-outlined mr-2" (click)="filter()" label="{{ 'apply' | translate}}"></button> <button pButton pRipple type="button" label="{{'clear' |translate}}" (click)="onFilterClear()" class="p-button-danger"></button> </div> </div> </div> </div> </div> </div> <div class="Dialog_Common"> <p-dialog [(visible)]="supervisorDialog" [style]="{width: '450px'}" header="{{dialogHeader}}" [modal]="true" styleClass="p-fluid" (onHide)="hideDialog()"> <ng-template pTemplate="content"> <form [formGroup]="supervisorForm"> <div class="p-fluid p-formgrid p-grid"> <div class="p-field p-col"> <label for="firstName">{{ "first.name" | translate }}*</label> <input class="form-control" type="text" pInputText id="firstName" placeholder="Enter first name" formControlName="firstName" required [pKeyFilter]="blockSpecial" maxlength="30" /> <div class="p-invalid" *ngIf="supervisorForm.controls['firstName'].touched && (supervisorForm.controls['firstName'].hasError('required') && !supervisorForm.controls['firstName'].valid) || (submitted && (supervisorForm.controls['firstName'].hasError('required') && !supervisorForm.controls['firstName'].valid))"> {{'required' | translate}}</div> <div class="p-invalid" *ngIf="supervisorForm.controls['firstName'].touched && (supervisorForm.controls['firstName'].hasError('maxlength') && !supervisorForm.controls['firstName'].valid)"> {{'firstName.maxLength' | translate}}</div> </div> <div class="p-field p-col"> <label for="lastName">{{ "last.name" | translate }}*</label> <input class="form-control" type="text" pInputText id="lastName" placeholder="Enter last name" formControlName="lastName" required [pKeyFilter]="blockSpecial" maxlength="30" /> <div class="p-invalid" *ngIf="supervisorForm.controls['lastName'].touched && (supervisorForm.controls['lastName'].hasError('required') && !supervisorForm.controls['lastName'].valid) || (submitted && (supervisorForm.controls['lastName'].hasError('required') && !supervisorForm.controls['lastName'].valid))"> {{'required' | translate}}</div> <div class="p-invalid" *ngIf="supervisorForm.controls['lastName'].touched && (supervisorForm.controls['lastName'].hasError('maxlength') && !supervisorForm.controls['lastName'].valid)"> {{'lastName.maxLength' | translate}}</div> </div> </div> <div class="p-field"> <label for="email">{{ "email.address" | translate }}*</label> <input class="form-control" type="text" pInputText id="email" placeholder="Enter email" formControlName="email" [attr.disabled]="isInEditMode?'':null" required maxlength="50" /> <div id="username-help" class="p-invalid" *ngIf=" supervisorForm.controls['email'].touched && (supervisorForm.controls['email'].hasError('required') && !supervisorForm.controls['email'].valid) || (submitted && (supervisorForm.controls['email'].hasError('required') && !supervisorForm.controls['email'].valid))"> {{'required' | translate}} </div> <div class="p-invalid" *ngIf=" (!supervisorForm.get('email').valid) "> <div *ngIf="supervisorForm.get('email').dirty && (supervisorForm.get('email').errors.incorrectEmailFormat && !supervisorForm.get('email').errors.required)"> {{'invalid.email' | translate}} </div> </div> <div id="username-help" class="p-invalid" *ngIf=" supervisorForm.controls['email'].touched && (supervisorForm.controls['email'].hasError('maxlength') && !supervisorForm.controls['email'].valid)"> {{'email.maxLength' | translate}} </div> </div> <div class="p-fluid p-formgrid p-grid"> <div class="p-field p-col"> <label for="workPhone">{{ "work.phone" | translate }}*</label> <p-inputMask id="workPhone" mask="(999) 999-9999" formControlName="workPhone" placeholder="Enter work Phone" required></p-inputMask> <div id="username-help" class="p-invalid" *ngIf=" supervisorForm.controls['workPhone'].touched && (supervisorForm.controls['workPhone'].hasError('required') && !supervisorForm.controls['workPhone'].valid) || (submitted && (supervisorForm.controls['workPhone'].hasError('required') && !supervisorForm.controls['workPhone'].valid))"> {{'required' | translate}} </div> <div id="username-help" class="p-invalid" *ngIf=" supervisorForm.controls['workPhone'].touched && (supervisorForm.controls['workPhone'].hasError('minlength') && !supervisorForm.controls['workPhone'].valid)"> {{'contact.length' | translate}} </div> <div id="username-help" class="p-invalid" *ngIf=" supervisorForm.controls['workPhone'].touched && (supervisorForm.controls['workPhone'].hasError('maxlength') && !supervisorForm.controls['workPhone'].valid)"> {{'contact.length' | translate}} </div> </div> <div class="p-field p-col"> <label for="mobilePhone">{{ "mobile.phone" | translate }}*</label> <p-inputMask id="mobilePhone" mask="(999) 999-9999" formControlName="mobilePhone" placeholder="Enter Mobile Phone"></p-inputMask> <div id="username-help" class="p-invalid" *ngIf=" supervisorForm.controls['mobilePhone'].touched && (supervisorForm.controls['mobilePhone'].hasError('required') && !supervisorForm.controls['mobilePhone'].valid) || (submitted && (supervisorForm.controls['mobilePhone'].hasError('required') && !supervisorForm.controls['mobilePhone'].valid))"> {{'required' | translate}} </div> <div id="username-help" class="p-invalid" *ngIf=" supervisorForm.controls['mobilePhone'].touched && (supervisorForm.controls['mobilePhone'].hasError('minlength') && !supervisorForm.controls['mobilePhone'].valid)"> {{'contact.length' | translate}} </div> <div id="username-help" class="p-invalid" *ngIf=" supervisorForm.controls['mobilePhone'].touched && (supervisorForm.controls['mobilePhone'].hasError('maxlength') && !supervisorForm.controls['mobilePhone'].valid)"> {{'contact.length' | translate}} </div> </div> </div> <div class="p-field p-col"> <label for="allowToPostProject">{{"is.allow.to.post.project" | translate}}</label> <br> <div style="display: inline;"> <input type="radio" [value]="true" formControlName="isAllowToPostProject"> <label class="radio-label">{{"yes" | translate}}</label> <input type="radio" [value]="false" formControlName="isAllowToPostProject"> <label class="radio-label">{{"no" | translate}}</label> </div> </div> </form> </ng-template> <ng-template pTemplate="footer"> <button pButton pRipple type="button" icon="pi pi-times-circle" label="{{'cancel' | translate}}" class="p-button-outlined p-button-danger" (click)="hideDialog()" style="margin-left: 16px;"></button> <p-button *ngIf="!isInEditMode" label="{{ 'add.new' | translate }}" type="button" (click)="onSupervisorFormSubmit()" icon="pi pi-check-circle"></p-button> <p-button *ngIf="isInEditMode" label="{{ 'update' | translate }}" type="button" (click)="onSupervisorFormSubmit()" icon="pi pi-check-circle"></p-button> </ng-template> </p-dialog> </div> <div class="row mt-3"> <div class="col-xl-12"> <div class="card datatable-card"> <p-table #dt [columns]="selectedColumns" [value]="data" [(selection)]="selectedSupervisor" [lazy]="true" (onLazyLoad)="onLazyLoad($event)" [paginator]="true" [rows]="size" [totalRecords]="totalRecords" [resizableColumns]="true" [loading]="loading" [showCurrentPageReport]="true" currentPageReportTemplate="Showing {first} to {last} of {totalRecords} supervisors" [rowsPerPageOptions]="rowsPerPageOptions" styleClass="p-datatable-striped" styleClass="p-datatable-responsive-demo" styleClass="p-datatable-gridlines" [scrollable]="true" [style]="{width:'100%'}" scrollHeight="400px"> <ng-template pTemplate="caption"> <p-multiSelect [options]="columns" [(ngModel)]="selectedColumns" optionLabel="label" selectedItemsLabel="{0} columns selected" [style]="{minWidth: '200px'}" placeholder="Choose Columns"></p-multiSelect> </ng-template> <ng-template pTemplate="colgroup" let-columns> <colgroup> <col style="width:50px"> <col style="width:220px" *ngFor="let col of columns"> <col style="width:120px"> </colgroup> </ng-template> <ng-template pTemplate="header" let-columns> <tr> <th style="width: 3rem"> <p-tableHeaderCheckbox></p-tableHeaderCheckbox> </th> <th id="column_{{col.value}}" *ngFor="let col of columns" [pSortableColumn]="col.sortable?col.value:null" pResizableColumn> {{col.label}} <p-sortIcon *ngIf="col.sortable" field="{{col.value}}"> </p-sortIcon> </th> <th pResizableColumn>{{ "action" | translate }}</th> </tr> </ng-template> <ng-template pTemplate="body" let-i="rowIndex" let-supervisor let-columns="columns"> <tr> <td> <p-tableCheckbox [value]="supervisor"></p-tableCheckbox> </td> <td *ngFor="let col of columns" [ngSwitch]="col.value" class="text-wrap"> <div *ngSwitchCase="'NAME'"> {{supervisor.supervisor.firstName}} {{supervisor.supervisor.lastName}} </div> <div *ngSwitchCase="'EMAIL'" class="text-wrap"> {{supervisor.supervisor.email}} </div> <div *ngSwitchCase="'IS_ACTIVE'"> <span *ngIf="supervisor.supervisor.active">{{'active' |translate}}</span> <span *ngIf="!supervisor.supervisor.active">{{'inactive' |translate}}</span> </div> <div *ngSwitchCase="'WORK_PONE'"> {{supervisor.workPhone}} </div> <div *ngSwitchCase="'MOBILE_PHONE'"> {{supervisor.mobilePhone}} </div> <div *ngSwitchCase="'IS_ALLOW'"> <span *ngIf="supervisor.isAllowToPostProject">{{'yes' |translate}}</span> <span *ngIf="!supervisor.isAllowToPostProject">{{'no' |translate}}</span> </div> <div *ngSwitchCase="'ASSIGNMENT'"> <a [routerLink]="" (click)="openAssignmentDialog(supervisor.supervisor.id)" pTooltip="{{'view.assignment' |translate}}">{{"view" | translate}}</a> </div> </td> <td> <button class="btn btn-success btn-sm mr-2" pTooltip="{{'edit.supervisor' |translate}}" (click)="editSupervisor(supervisor)"><i aria-hidden="true" class="fa fa-pencil"></i></button> </td> </tr> </ng-template> <ng-template pTemplate="emptymessage"> <tr> <td class="text-center" [attr.colspan]="9"> {{'no.record.found' | translate}} </td> </tr> </ng-template> </p-table> </div> </div> </div> <div class="Dialog_Common"> <p-dialog [(visible)]="assignmentDialog" [style]="{width: '60%'}" header="{{'assignment' | translate}}" [modal]="true" styleClass="p-fluid"> <section> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item waves-effect waves-light"> <a class="nav-link" id="jobsite-tab" data-toggle="tab" href="#jobsite" role="tab" aria-controls="home" aria-selected="false">Jobsite</a> </li> <li class="nav-item waves-effect waves-light"> <a class="nav-link active" id="job-tab" data-toggle="tab" href="#job" role="tab" aria-controls="contact" aria-selected="true">Job</a> </li> </ul> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade" id="jobsite" role="tabpanel" aria-labelledby="jobsite-tab"> <app-assignment-jobsite></app-assignment-jobsite> </div> <div class="tab-pane fade active show" id="job" role="tabpanel" aria-labelledby="job-tab"> <app-assignment-job></app-assignment-job> </div> </div> </section> </p-dialog> </div> </div>
#!/usr/bin/python # -*- coding: utf-8 -*- # # (C) Seth Edwards, 2014 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: librato_annotation short_description: create an annotation in librato description: - Create an annotation event on the given annotation stream :name. If the annotation stream does not exist, it will be created automatically version_added: "1.6" author: "Seth Edwards (@Sedward)" requirements: [] options: user: description: - Librato account username required: true api_key: description: - Librato account api key required: true name: description: - The annotation stream name - If the annotation stream does not exist, it will be created automatically required: false title: description: - The title of an annotation is a string and may contain spaces - The title should be a short, high-level summary of the annotation e.g. v45 Deployment required: true source: description: - A string which describes the originating source of an annotation when that annotation is tracked across multiple members of a population required: false description: description: - The description contains extra meta-data about a particular annotation - The description should contain specifics on the individual annotation e.g. Deployed 9b562b2 shipped new feature foo! required: false start_time: description: - The unix timestamp indicating the time at which the event referenced by this annotation started required: false end_time: description: - The unix timestamp indicating the time at which the event referenced by this annotation ended - For events that have a duration, this is a useful way to annotate the duration of the event required: false links: description: - See examples required: true ''' EXAMPLES = ''' # Create a simple annotation event with a source - librato_annotation: user: user@example.com api_key: XXXXXXXXXXXXXXXXX title: App Config Change source: foo.bar description: This is a detailed description of the config change # Create an annotation that includes a link - librato_annotation: user: user@example.com api_key: XXXXXXXXXXXXXXXXXX name: code.deploy title: app code deploy description: this is a detailed description of a deployment links: - rel: example href: http://www.example.com/deploy # Create an annotation with a start_time and end_time - librato_annotation: user: user@example.com api_key: XXXXXXXXXXXXXXXXXX name: maintenance title: Maintenance window description: This is a detailed description of maintenance start_time: 1395940006 end_time: 1395954406 ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_url def post_annotation(module): user = module.params['user'] api_key = module.params['api_key'] name = module.params['name'] title = module.params['title'] url = 'https://metrics-api.librato.com/v1/annotations/%s' % name params = {} params['title'] = title if module.params['source'] is not None: params['source'] = module.params['source'] if module.params['description'] is not None: params['description'] = module.params['description'] if module.params['start_time'] is not None: params['start_time'] = module.params['start_time'] if module.params['end_time'] is not None: params['end_time'] = module.params['end_time'] if module.params['links'] is not None: params['links'] = module.params['links'] json_body = module.jsonify(params) headers = {} headers['Content-Type'] = 'application/json' # Hack send parameters the way fetch_url wants them module.params['url_username'] = user module.params['url_password'] = api_key response, info = fetch_url(module, url, data=json_body, headers=headers) response_code = str(info['status']) response_body = info['body'] if info['status'] != 201: if info['status'] >= 400: module.fail_json(msg="Request Failed. Response code: " + response_code + " Response body: " + response_body) else: module.fail_json(msg="Request Failed. Response code: " + response_code) response = response.read() module.exit_json(changed=True, annotation=response) def main(): module = AnsibleModule( argument_spec=dict( user=dict(required=True), api_key=dict(required=True), name=dict(required=False), title=dict(required=True), source=dict(required=False), description=dict(required=False), start_time=dict(required=False, default=None, type='int'), end_time=dict(require=False, default=None, type='int'), links=dict(type='list') ) ) post_annotation(module) if __name__ == '__main__': main()
import { useContext, useEffect, useState } from "react"; import useTitle from "../../Hooks/useTitle"; import { AuthContext } from "../../Provider/AuthProvider"; import MyToyTable from "./MyToyTable"; import Swal from "sweetalert2"; const MyToys = () => { useTitle("MyToy"); const { user } = useContext(AuthContext); const [myCars, setMyCars] = useState([]); const [sortingOrder, setSortingOrder] = useState("ascending"); // State for sorting order useEffect(() => { const url = `https://toy-universe-server-liart.vercel.app/allToy?email=${user?.email}&sortingOrder=${sortingOrder}`; // Include sortingOrder in the URL fetch(url) .then((res) => res.json()) .then((data) => { setMyCars(data); console.log(data); }); }, [user?.email, sortingOrder]); // Include sortingOrder as a dependency const handleDelete = (id) => { Swal.fire({ title: "Are you sure?", text: "You won't be able to revert this!", icon: "warning", showCancelButton: true, confirmButtonColor: "#1F2937", cancelButtonColor: "#555273", confirmButtonText: "Yes, delete it!", }).then((result) => { if (result.isConfirmed) { fetch(`https://toy-universe-server-liart.vercel.app/allToys/${id}`, { method: "DELETE", }) .then((res) => res.json()) .then((data) => { console.log(data); if (data.deletedCount > 0) { const remaining = myCars.filter((cars) => cars._id !== id); setMyCars(remaining); Swal.fire("Deleted!", "Your file has been deleted.", "success"); } }); } }); // if (proceed) { // } }; const handleSortingOrderChange = (event) => { const selectedSortingOrder = event.target.value; setSortingOrder(selectedSortingOrder); }; return ( <div className="overflow-x-auto"> <div className="sorting-container my-2 px-2 py-2"> <label htmlFor="sortingOrder" className="font-semibold"> Sorting Order: </label> <select id="sortingOrder" value={sortingOrder} onChange={handleSortingOrderChange} > <option value="ascending" className="text-[#1F2937]"> Ascending </option> <option value="descending" className="text-[#1F2937]"> Descending </option> </select> </div> <table className="min-w-full bg-white"> <thead> <tr> <th className="py-2 px-4 border-b bg-[#1F2937] text-white"> Seller </th> <th className="py-2 px-4 border-b bg-[#1F2937] text-white"> Toy Name </th> <th className="py-2 px-4 border-b bg-[#1F2937] text-white"> Sub-category </th> <th className="py-2 px-4 border-b bg-[#1F2937] text-white"> Price </th> <th className="py-2 px-4 border-b bg-[#1F2937] text-white"> Available Quantity </th> <th className="py-2 px-4 border-b bg-[#1F2937] text-white"> Image </th> <th className="py-2 px-4 border-b bg-[#1F2937] text-white"></th> <th className="py-2 px-4 border-b bg-[#1F2937] text-white"></th> </tr> </thead> <tbody> {myCars.map((car) => ( <MyToyTable key={car._id} car={car} handleDelete={handleDelete} ></MyToyTable> ))} </tbody> </table> </div> ); }; export default MyToys;
import React, { FC, useEffect, useState } from 'react'; import { TAnalyzeProps } from './types'; import { alpha, Fade, Stack, ToggleButton, ToggleButtonGroup, Typography } from '@mui/material'; import Header from '../header'; import Button from '../button'; import Results from '../results'; import { IColumn, IResult } from '../../types/types'; import { theme } from '../../styles/theme'; import { grey } from '@mui/material/colors'; import Row from '../row'; import { getColumnsFilled } from './helpers/getColumnsFilled'; import { ANALYZE_TITLE, BUTTON_ANALYZE, COLUMNS_TITLES, ROWS, YEARS_LONG, YEARS_SHORT, YEARS_TEXT } from './constants'; import { FADE_ANIMATION_TIME } from '../app/constants'; import { getColumnResult } from './helpers/getColumnResult'; export const Analyze: FC<TAnalyzeProps> = ({ stockData, onReset }) => { const [columns, setColumns] = useState<IColumn[]>([] as IColumn[]); const [results, setResults] = useState<IResult[][] | null>(null); const [disabled, setDisabled] = useState(true); const [fade, setFade] = useState(true); const [forceRerender, setForceRerender] = useState(false); const [years, setYears] = useState(YEARS_LONG); const onSetColumnData = ( key: keyof IColumn, idx: number, value: string, ) => { setColumns(columns.map((column, index) => { if (index === idx) { if (!value.length) { delete column[key]; } else { column[key] = Number(value); } } return column; })); }; const onEnter = (e: React.KeyboardEvent) => { if (!disabled && e.key === 'Enter') { onSubmit(); } }; const onSubmit = () => { setResults(columns.map(column => getColumnResult(column, stockData, years))); }; const onClickBack = () => { setForceRerender(true); setTimeout(onReset, FADE_ANIMATION_TIME); }; const onYearsToggle = ( e: React.MouseEvent<HTMLElement>, years: number ) => { if (!years) return; setYears(years); }; useEffect(() => { if (!columns.length) return; if (getColumnsFilled(columns)) { setDisabled(false); } else { setDisabled(true); } }, [columns]); useEffect(() => { if (columns.length) return; for (let i = 0; i < COLUMNS_TITLES.length - 1; i++) { columns.push({} as IColumn); } }, []); useEffect(() => { setFade(prev => !prev); }, [forceRerender]); return ( <Fade in={fade} appear timeout={FADE_ANIMATION_TIME} > <Stack spacing={1.5}> <Stack justifyContent={'space-between'} alignItems={'flex-end'} direction={'row'} > <Typography color={theme.palette.common.white} variant={'h4'} fontWeight={100} textTransform={'uppercase'} sx={titleStyle} > {ANALYZE_TITLE} </Typography> <ToggleButtonGroup value={years} exclusive onChange={onYearsToggle} > <ToggleButton sx={toggleStyle} value={YEARS_SHORT}> {YEARS_SHORT} {YEARS_TEXT} </ToggleButton> <ToggleButton sx={toggleStyle} value={YEARS_LONG}> {YEARS_LONG} {YEARS_TEXT} </ToggleButton> </ToggleButtonGroup> </Stack> <Stack spacing={1} sx={containerStyle} onKeyDown={onEnter} > <Header columns={COLUMNS_TITLES} ticker={stockData.ticker} onClickBack={onClickBack} price={stockData.price} /> <Stack spacing={1} sx={rowsStyle}> { ROWS.map(row => ( <Row key={row.key} title={row.title} size={COLUMNS_TITLES.length - 1} adornment={row.adornment} onSetData={(idx, value) => onSetColumnData(row.key, idx, value)} //@ts-ignore currentData={stockData[row.key]} /> )) } </Stack> <Button disabled={disabled} onClick={onSubmit}> {BUTTON_ANALYZE} </Button> </Stack> <Results results={results} /> </Stack> </Fade> ); } const titleStyle = { width: theme.spacing(), userSelect: 'none', [theme.breakpoints.down('sm')]: { pl: 2 } }; const containerStyle = { position: 'relative', p: 2.5, pt: theme.spacing(7), //header height bgcolor: grey[800], borderRadius: theme.spacing(1.5), overflow: 'hidden', zIndex: theme.zIndex.appBar, [theme.breakpoints.down('sm')]: { width: `calc(100vw - ${theme.spacing(5)})`, // - paddings borderRadius: 0 }, [theme.breakpoints.down(500)]: { px: 1.5, width: `calc(100vw - ${theme.spacing(3)})`, // - paddings } }; const rowsStyle = { py: 1.5 }; const toggleStyle = { width: theme.spacing(10.5), height: theme.spacing(5), color: alpha(theme.palette.common.white, 0.75), bgcolor: alpha(theme.palette.primary.main, 0.3), '&.Mui-selected': { color: theme.palette.common.white, bgcolor: theme.palette.primary.main, }, '&.Mui-selected:focus, &.Mui-selected:hover, &:hover, &:focus': { color: theme.palette.common.white, bgcolor: theme.palette.primary.dark, } };
package ex01.B; /* Prompt do ChatGPT: Crie uma função em java computando a função fatorial de forma decrescente e recursiva, com abundância de comentários e imprimindo valores a cada iteração */ public class FatorialDecrescenteGPT { // Função principal que inicia o programa public static void main(String[] args) { int numero = 5; // Número para o qual queremos calcular o fatorial System.out.println("Fatorial de " + numero + " é " + fatorial(numero)); } // Função recursiva que calcula o fatorial de um número public static int fatorial(int n) { // Imprime o valor atual de n System.out.println("Chamando fatorial(" + n + ")"); // Caso base: fatorial de 0 ou 1 é 1 if (n == 0 || n == 1) { System.out.println("Base case reached with n = " + n); return 1; } // Chamada recursiva decrescente int resultado = n * fatorial(n - 1); // Imprime o valor atual do resultado após a chamada recursiva System.out.println("Retornando " + resultado + " para fatorial(" + n + ")"); // Retorna o resultado do cálculo fatorial return resultado; } }
package com.example.forcadevendastrab3bi.view; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.Spinner; import androidx.appcompat.app.AppCompatActivity; import com.example.forcadevendastrab3bi.R; import com.example.forcadevendastrab3bi.controller.ClienteController; import com.example.forcadevendastrab3bi.controller.EnderecoController; import com.example.forcadevendastrab3bi.controller.ItemController; import com.example.forcadevendastrab3bi.controller.PedidoVendaController; import com.example.forcadevendastrab3bi.model.Cliente; import com.example.forcadevendastrab3bi.model.Endereco; import com.example.forcadevendastrab3bi.model.Item; import java.util.ArrayList; public class CadastroVendaActivity extends AppCompatActivity { private Spinner spEnderecoVenda; private EditText enderecoVenda; private Spinner spClienteVenda; private EditText clienteVenda; private Spinner spItemVenda; private EditText itemVenda; private EditText quantidadeVenda; private RadioGroup radioGroup; private EditText quantidadeParcelasVenda; private EditText valorTotalVenda; private Button botaoSalvarVenda; private PedidoVendaController pedidoVendaController; private EnderecoController enderecoController; private ItemController itemController; private ClienteController clienteController; private ArrayAdapter adapterEndereco; private ArrayAdapter adapterItem; private ArrayAdapter adapterCliente; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cadastro_venda); setTitle("Cadastrar Venda"); spEnderecoVenda = findViewById(R.id.spEnderecoVenda); enderecoVenda = findViewById(R.id.edEnderecoVenda); spClienteVenda = findViewById(R.id.spClienteVenda); clienteVenda = findViewById(R.id.edClienteVenda); spItemVenda = findViewById(R.id.spItemVenda); itemVenda = findViewById(R.id.edItemVenda); quantidadeVenda = findViewById(R.id.quantidadeVenda); radioGroup = findViewById(R.id.radioGroup); quantidadeParcelasVenda = findViewById(R.id.quantidadeParcelasVenda); valorTotalVenda = findViewById(R.id.valorFinalVenda); botaoSalvarVenda = findViewById(R.id.btSalvarVenda); pedidoVendaController = new PedidoVendaController(this); enderecoController = new EnderecoController(this); clienteController = new ClienteController(this); itemController = new ItemController(this); ArrayList<Endereco> enderecos = enderecoController.retornarTodosEnderecos(); ArrayList<Item> itens = itemController.retornarTodositens(); ArrayList<Cliente> clientes = clienteController.retornarTodosClientes(); String[] vetorEnderecos = new String[enderecos.size()]; String[] vetorItens = new String[itens.size()]; String[] vetorClientes = new String[clientes.size()]; for (int i = 0; i < enderecos.size(); i++){ vetorEnderecos[i] = enderecos.get(i).getLogradouro() +" / " + enderecos.get(i).getNumero(); } for (int i = 0; i < itens.size(); i++){ vetorItens[i] = itens.get(i).getDescricao(); } for (int i = 0; i < clientes.size(); i++){ vetorClientes[i] = clientes.get(i).getNome(); } adapterEndereco = new ArrayAdapter(this, android.R.layout.simple_list_item_1, vetorEnderecos); adapterItem = new ArrayAdapter(this, android.R.layout.simple_list_item_1, vetorItens); adapterCliente = new ArrayAdapter(this, android.R.layout.simple_list_item_1, vetorClientes); spEnderecoVenda.setAdapter(adapterEndereco); spItemVenda.setAdapter(adapterItem); spClienteVenda.setAdapter(adapterCliente); spEnderecoVenda.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { enderecoVenda.setText(String.valueOf(i+1)); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); spItemVenda.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { itemVenda.setText(String.valueOf(i+1)); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); spClienteVenda.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { clienteVenda.setText(String.valueOf(i+1)); calculaValorTotalVenda(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int checkedId) { switch (checkedId) { case R.id.rbAvista: quantidadeParcelasVenda.setVisibility(View.GONE); break; case R.id.rbParcelado: quantidadeParcelasVenda.setVisibility(View.VISIBLE); break; } calculaValorTotalVenda(); } }); botaoSalvarVenda.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { salvarVenda(); } }); } private void salvarVenda(){ } private void calculaValorTotalVenda(){ Double valorFrete = 0.0; Double valorItens = 0.0; Double valorFinal = 0.0; if(enderecoVenda.getText().toString() != null || !enderecoVenda.getText().toString().isEmpty()){ Endereco endereco = enderecoController.retornarEndereco(Integer.parseInt(enderecoVenda.getText().toString())); if(endereco.getCidade().toUpperCase() != "PARANÁ"){ valorFrete = 50.0; }else if(endereco.getCidade().toUpperCase() != "TOLEDO"){ valorFrete = 20.0; } } if(!itemVenda.getText().toString().isEmpty() ){ System.out.println(itemVenda.getText().toString()); System.out.println(!itemVenda.getText().toString().isEmpty()); Item item = itemController.retornarItem(Integer.parseInt(itemVenda.getText().toString())); valorItens = item.getValorUnit(); if(quantidadeVenda.getText().toString() != null || !quantidadeVenda.getText().toString().isEmpty()){ valorItens = valorItens * Double.parseDouble(quantidadeVenda.getText().toString()); } } valorFinal = valorFrete + valorItens; int checkedId = radioGroup.getCheckedRadioButtonId(); switch (checkedId) { case R.id.rbAvista: valorFinal = valorFinal * 0.95; break; case R.id.rbParcelado: break; } valorTotalVenda.setText("R$ "+valorFinal); } }
import React from 'react'; import { useState } from 'react'; import RangeSlider from './RangeSlider'; import Popup from './Popup'; function FilterPopup({ isOpen, onClose, priceRange, setPriceRange }) { const [maxPrice, setMaxPrice] = useState(10000000); if (!isOpen) return null; const handleRangeChange = (values) => { setPriceRange(values); }; return ( <Popup children={ <div> <h2 className="text-xl font-semibold mb-4 text-customColors-secondary">Apply filters</h2> <h3 className='mb-2 text-customColors-secondary'> Select price range </h3> <ul className='flex flex-row mb-2'> <li> <button className='mr-2 p-1 border border-black bg-gray-200' onClick={() => { setMaxPrice(999) setPriceRange([0, 999]) }} > low </button > </li> <li> <button className='mr-2 p-1 border border-black bg-gray-200' onClick={() => { setMaxPrice(999000) setPriceRange([0, 999000]) }} > K </button> </li> <li> <button className='mr-2 p-1 border border-black bg-gray-200' onClick={() => { setMaxPrice(10000000) setPriceRange([0, 10000000]) }} > M </button> </li> </ul> <RangeSlider min={0} max={maxPrice} values={priceRange} onChange={handleRangeChange} /> </div> } onClose={onClose} /> ); } export default FilterPopup;
import { createRouter, createWebHistory } from 'vue-router' import HomeView from '../views/HomeView.vue' const routes = [{ path: '/', name: 'home', component: HomeView }, { path: '/login', name: 'login', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/TelaLogin.vue') }, { path: '/aluno/:matricula', name: 'aluno', props: true, // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/TelaAluno.vue') }, { path: '/cadastro', name: 'cadastro', props: true, // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/CadastroAluno.vue') }, ] const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes }) export default router
import React from 'react'; import { useParams, useNavigate, Link } from 'react-router-dom'; import { useTriviaProvider } from '../../context/Trivia'; import { Problem } from '../../types/index'; function Paper() { const { id } = useParams(); const navigate = useNavigate(); const [current, setCurrent] = React.useState<Problem | null>(null); const { problems, isFinished, setProblems, setIsFinished } = useTriviaProvider(); React.useEffect(() => { setCurrent( problems.find((problem) => problem.id.toString() === id) ?? null ); }, [problems, id]); function handlePreviousButtonClick() { navigate(`/paper/${(current?.id ?? 1) - 1}`); } function handleNextButtonClick() { navigate(`/paper/${(current?.id ?? 1) + 1}`); } function handleAnswer(answer: 'True' | 'False') { current && setCurrent({ ...current, answer }); const updated = problems.map((problem) => { if (problem.id.toString() === id) { return { ...problem, answer }; } return { ...problem, }; }); setProblems(updated); localStorage.setItem('problems', JSON.stringify(updated)); } function handleFinishButtonClick() { setIsFinished(true); localStorage.setItem('isFinished', 'true'); navigate('/result'); } return ( <div className='w-[500px] h-[800px] mx-auto rounded-lg bg-white ring-2 ring-indigo-600 px-10 py-10 text-center relative'> <h1 className='text-slate-800 text-5xl text-center font-bold'> {current?.category} </h1> <div className='mt-36 p-6 bg-white rounded-lg border border-gray-200 shadow-md dark:bg-gray-800 dark:border-gray-700'> <p className='mb-2 text-2xl tracking-tight text-gray-900 break-all dark:text-white' dangerouslySetInnerHTML={{ __html: current?.question ?? '' }} /> <div className='m-10'> <div className='flex items-center mb-4'> <input id='answer-true' type='radio' name='answer' className='w-6 h-6 border-gray-300' checked={current?.answer === 'True'} onChange={() => handleAnswer('True')} disabled={isFinished} /> <label className={`block ml-2 text-2xl font-medium dark:text-gray-300 ${ isFinished && current?.correct_answer === 'True' ? 'text-sky-600' : 'text-gray-900' }`} > True </label> </div> <div className='flex items-center'> <input id='answer-false' type='radio' name='answer' className='w-6 h-6 border-gray-300' checked={current?.answer === 'False'} onChange={() => handleAnswer('False')} disabled={isFinished} /> <label className={`block ml-2 text-2xl font-medium text-gray-900 dark:text-gray-300 ${ isFinished && current?.correct_answer === 'False' ? 'text-sky-600' : 'text-gray-900' }`} > False </label> </div> </div> </div> <div className='w-[calc(100%-80px)] flex justify-between items-center absolute bottom-6'> <button className='w-24 text-base rounded-md bg-indigo-600 text-white hover:bg-indigo-500 active:bg-indigo-400 py-2 px-1 disabled:bg-indigo-300' onClick={handlePreviousButtonClick} type='button' disabled={id === '1'} > Previous </button> <span className='text-3xl'>{`${id} of 10`}</span> {id !== '10' ? ( <button className='w-24 text-base rounded-md bg-indigo-600 text-white hover:bg-indigo-500 active:bg-indigo-400 py-2 px-1 disabled:bg-indigo-300' onClick={handleNextButtonClick} type='button' > Next </button> ) : !isFinished ? ( <button className='w-24 text-base rounded-md bg-indigo-600 text-white hover:bg-indigo-500 active:bg-indigo-400 py-2 px-1 disabled:bg-indigo-300' onClick={handleFinishButtonClick} type='button' > Finish </button> ) : ( <Link to='/result'> <button className='w-24 text-base rounded-md bg-indigo-600 text-white hover:bg-indigo-500 active:bg-indigo-400 py-2 px-1 disabled:bg-indigo-300' type='button' > See Result </button> </Link> )} </div> </div> ); } export { Paper };
using Microsoft.AspNetCore.Mvc; using ProductApi.Application.Interfaces; using ProductApi.Domain.DTO; using System; using System.Threading.Tasks; namespace ProductApi.Controllers { [Route("api/[controller]")] [ApiController] public class ProductController : ControllerBase { private readonly IProductApplication _productApplication; public ProductController(IProductApplication productApplication) { _productApplication = productApplication; } [Route("search")] [HttpGet] public async Task<IActionResult> SearchById(int id) { try { if (!ModelState.IsValid) return BadRequest(ModelState); return Ok(await _productApplication.SearchById(id)); } catch (Exception ex) { return BadRequest(ex.Message); } } [Route("list")] [HttpGet] public async Task<IActionResult> List([FromQuery] ProductSearchDTO search) { try { if (!ModelState.IsValid) return BadRequest(ModelState); return Ok(await _productApplication.List(search)); } catch (Exception ex) { return BadRequest(ex.Message); } } [Route("add")] [HttpPost] public async Task<IActionResult> Add(ProductAddDTO dto) { try { if (!ModelState.IsValid) return BadRequest(ModelState); await _productApplication.Add(dto); return Ok(); } catch (Exception ex) { return BadRequest(ex.Message); } } [Route("update")] [HttpPut] public async Task<IActionResult> Update(ProductUpdateDTO dto) { try { if (!ModelState.IsValid) return BadRequest(ModelState); await _productApplication.Update(dto); return Ok(); } catch (Exception ex) { return BadRequest(ex.Message); } } [Route("delete")] [HttpDelete] public async Task<IActionResult> Delete(int id) { try { if (!ModelState.IsValid) return BadRequest(ModelState); await _productApplication.Delete(id); return Ok(); } catch (Exception ex) { return BadRequest(ex.Message); } } } }
import { Component, h, Prop } from '@stencil/core' @Component({ tag: 'mnv-hero', styleUrl: 'mnv-hero.scss', shadow: true }) export class Mnvhero { @Prop() background: string @Prop() herotitle: string @Prop() button: string @Prop() bgimg: string = 'https://images.pexels.com/photos/373912/pexels-photo-373912.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940' render() { let setBgImg = `url('${this.bgimg}')` return ( <div class='image' style={{ backgroundImage: setBgImg }}> <div class='body'> <mnv-grid container> <mnv-grid item sm='12' md='9' lg='6' xl='6'> <mnv-title level='hero'>{this.herotitle}</mnv-title> </mnv-grid> <mnv-grid item md='3' lg='6' xl='6' /> <mnv-grid item sm='12' md='6' lg='4' xl='4'> <mnv-title level='h4'> <slot /> </mnv-title> </mnv-grid> {this.button ? ( <mnv-grid item sm='12' md='12' lg='12' xl='12'> <mnv-button outlined marginzero style={{ margin: '0px !important' }} > {this.button} </mnv-button> </mnv-grid> ) : ( '' )} </mnv-grid> </div> </div> ) } }
package main import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "html/template" "io" "log" "net/http" "os" "path/filepath" "regexp" "sort" "strings" "time" errors "git.sequentialread.com/forest/pkg-errors" "github.com/shengdoushi/base58" ) type Session struct { SessionId string UserID string ExpiresUnixMilli int64 Flash *map[string]string } type FrontendApp struct { Port int Domain string Router *http.ServeMux DB *DBModel HTMLTemplates map[string]*template.Template cssHash string basicURLPathRegex *regexp.Regexp base58Regex *regexp.Regexp roomNameCache map[string]string } type MatrixRoom struct { Id string Name string IdWithName string Rows int Percent int Ban bool Status string } type DeleteProgress struct { Rooms []MatrixRoom StateGroupsStateProgress int } func initFrontend(config *Config, db *DBModel) FrontendApp { currentDirectory, err := os.Getwd() if err != nil { panic(errors.Wrap(err, "can't initFrontend because can't get working directory:")) } cssBytes, err := os.ReadFile(filepath.Join(currentDirectory, "frontend", "static", "app.css")) if err != nil { panic(errors.Wrap(err, "can't initFrontend because can't read cssBytes:")) } hashArray := sha256.Sum256(cssBytes) cssHash := base58.Encode(hashArray[:6], base58.BitcoinAlphabet) app := FrontendApp{ Port: config.FrontendPort, Domain: config.FrontendDomain, Router: http.NewServeMux(), DB: db, HTMLTemplates: map[string]*template.Template{}, basicURLPathRegex: regexp.MustCompile("(?i)[a-z0-9/?&_+-]+"), base58Regex: regexp.MustCompile("(?i)[a-z0-9_-]+"), cssHash: cssHash, roomNameCache: map[string]string{}, } // serve the homepage app.handleWithSession("/", func(responseWriter http.ResponseWriter, request *http.Request, session Session) { userIsLoggedIn := session.UserID != "" if userIsLoggedIn { deleteProgress, err := ReadJsonFile[DeleteProgress]("data/deleteRooms.json") if err != nil { (*session.Flash)["error"] = "an error occurred reading deleteRooms json" } if deleteProgress.Rooms != nil && len(deleteProgress.Rooms) > 0 { app.buildPageFromTemplate(responseWriter, request, session, "deleting.html", deleteProgress) return } if request.Method == "POST" { refresh := request.PostFormValue("refresh") measureMediaSize := request.PostFormValue("measureMediaSize") == "on" stateGroupsStateScan := request.PostFormValue("stateGroupsStateScan") == "on" if refresh == "true" { go runScheduledTask(db, config, measureMediaSize, stateGroupsStateScan) http.Redirect(responseWriter, request, "/", http.StatusFound) return } toDelete := []MatrixRoom{} for i := 0; i < 20; i++ { roomId := request.PostFormValue(fmt.Sprintf("id_%d", i)) delete := request.PostFormValue(fmt.Sprintf("delete_%d", i)) ban := request.PostFormValue(fmt.Sprintf("ban_%d", i)) if roomId != "" && (delete != "" || ban != "") { toDelete = append(toDelete, MatrixRoom{ Id: roomId, Ban: ban != "", IdWithName: fmt.Sprintf("%s: %s", roomId, app.getMatrixRoomNameWithCache(roomId)), Status: "...", }) } } err := WriteJsonFile("data/deleteRooms.json", DeleteProgress{ Rooms: toDelete, }) if err != nil { (*session.Flash)["error"] = "an error occurred saving deleteRooms json" } go doRoomDeletes(app.DB) http.Redirect(responseWriter, request, "/", http.StatusFound) return } diskUsage, err := os.ReadFile("data/diskUsage.json") if err != nil { (*session.Flash)["error"] = "an error occurred reading diskUsage json" } dbTableSizes, err := os.ReadFile("data/dbTableSizes.json") if err != nil { (*session.Flash)["error"] = "an error occurred reading dbTableSizes json" } rowCountByRoomObject, err := ReadJsonFile[map[string]int]("data/stateGroupsStateRowCountByRoom.json") if err != nil { (*session.Flash)["error"] = "an error occurred reading rowCountByRoom json object" } roomsSlice := []MatrixRoom{} totalRowCount := 0 for roomId, rows := range rowCountByRoomObject { totalRowCount += rows if rows > 10000 { roomsSlice = append(roomsSlice, MatrixRoom{ Id: roomId, Rows: rows, }) } } sort.Slice(roomsSlice, func(i, j int) bool { return roomsSlice[i].Rows > roomsSlice[j].Rows }) biggestRooms := roomsSlice[0:10] bigRoomsRowCount := 0 for i, room := range biggestRooms { // TODO cache this ?? name := app.getMatrixRoomNameWithCache(room.Id) biggestRooms[i] = MatrixRoom{ Id: room.Id, Name: name, IdWithName: fmt.Sprintf("%s: %s", room.Id, name), Rows: room.Rows, Percent: int((float64(room.Rows) / float64(totalRowCount)) * float64(100)), } bigRoomsRowCount += room.Rows } biggestRooms = append(biggestRooms, MatrixRoom{ Name: "Others", Rows: totalRowCount - bigRoomsRowCount, }) bigRoomsBytes, _ := json.Marshal(biggestRooms) //log.Println(string(bigRoomsBytes)) panelTemplateData := struct { DiskUsage template.JS DBTableSizes template.JS BigRooms template.JS BigRoomsSlice []MatrixRoom Updating bool }{template.JS(diskUsage), template.JS(dbTableSizes), template.JS(bigRoomsBytes), biggestRooms, isRunningScheduledTask} app.buildPageFromTemplate(responseWriter, request, session, "panel.html", panelTemplateData) } else { if request.Method == "POST" { username := request.PostFormValue("username") password := request.PostFormValue("password") success, err := matrixAdmin.Login(username, password) if err != nil { (*session.Flash)["error"] += "an error was thrown by the login process 😧" log.Println(errors.Wrap(err, "an error was thrown by the login process")) } else { if success { session.UserID = username session.ExpiresUnixMilli = time.Now().Add(time.Hour * 24).UnixMilli() err = app.setSession(responseWriter, &session) if err != nil { log.Println(errors.Wrap(err, "setSession failed")) } http.Redirect(responseWriter, request, "/", http.StatusFound) return } else { (*session.Flash)["error"] += "username or password was incorrect" } } } loginPageTemplateData := struct { MatrixServerPublicDomain string }{config.MatrixServerPublicDomain} app.buildPageFromTemplate(responseWriter, request, session, "login.html", loginPageTemplateData) } }) app.handleWithSession("/logout", func(responseWriter http.ResponseWriter, request *http.Request, session Session) { if session.UserID != "" && session.SessionId != "" { os.Remove(fmt.Sprintf("data/sessions/%s.json", session.SessionId)) } app.deleteCookie(responseWriter, "sessionId") http.Redirect(responseWriter, request, "/", http.StatusFound) }) // registerHowtoRoutes(&app) // registerLoginRoutes(&app, emailService) // registerProfileRoutes(&app) // registerAdminPanelRoutes(&app) app.reloadTemplates() staticFilesDir := filepath.Join(currentDirectory, "frontend/static") log.Printf("serving static files from %s", staticFilesDir) app.Router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(staticFilesDir)))) return app } func (app *FrontendApp) ListenAndServe() error { return http.ListenAndServe(fmt.Sprintf(":%d", app.Port), app.Router) } func (app *FrontendApp) setCookie(responseWriter http.ResponseWriter, name, value string, lifetimeSeconds int, sameSite http.SameSite) { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#define_where_cookies_are_sent // The Domain attribute specifies which hosts are allowed to receive the cookie. // If unspecified, it defaults to the same host that set the cookie, excluding subdomains. // If Domain is specified, then subdomains are always included. // Therefore, specifying Domain is less restrictive than omitting it. // However, it can be helpful when subdomains need to share information about a user. toSet := &http.Cookie{ Name: name, HttpOnly: true, Secure: true, SameSite: sameSite, Path: "/", Value: value, MaxAge: lifetimeSeconds, } http.SetCookie(responseWriter, toSet) } func (app *FrontendApp) deleteCookie(responseWriter http.ResponseWriter, name string) { http.SetCookie(responseWriter, &http.Cookie{ Name: name, HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, Path: "/", Value: "", MaxAge: -1, }) } func (app *FrontendApp) getSession(request *http.Request, domain string) (Session, error) { toReturn := Session{ Flash: &(map[string]string{}), } for _, cookie := range request.Cookies() { if cookie.Name == "sessionId" && app.base58Regex.MatchString(cookie.Value) { session, err := ReadJsonFile[Session](fmt.Sprintf("data/sessions/%s.json", cookie.Value)) if err == nil { if session.ExpiresUnixMilli > time.Now().UnixMilli() { toReturn.SessionId = cookie.Value toReturn.UserID = session.UserID } } //log.Printf("toReturn.SessionId %s\n", toReturn.SessionId) } else if cookie.Name == "flash" && cookie.Value != "" { bytes, err := base64.RawURLEncoding.DecodeString(cookie.Value) if err != nil { log.Printf("can't getSession because can't base64 decode flash cookie: %+v", err) return toReturn, err } flash := map[string]string{} err = json.Unmarshal(bytes, &flash) if err != nil { log.Printf("can't getSession because can't json parse the decoded flash cookie: %+v", err) return toReturn, err } toReturn.Flash = &flash } } return toReturn, nil } func (app *FrontendApp) setSession(responseWriter http.ResponseWriter, session *Session) error { sessionIdBuffer := make([]byte, 32) rand.Read(sessionIdBuffer) sessionId := base58.Encode(sessionIdBuffer, base58.BitcoinAlphabet) session.SessionId = sessionId err := WriteJsonFile(fmt.Sprintf("data/sessions/%s.json", sessionId), *session) if err != nil { return err } // bytes, _ := json.MarshalIndent(session, "", " ") // log.Printf("setSession(): %s %s\n", sessionId, string(bytes)) exipreInSeconds := int(time.Until(time.UnixMilli(session.ExpiresUnixMilli)).Seconds()) app.setCookie(responseWriter, "sessionId", sessionId, exipreInSeconds, http.SameSiteStrictMode) return nil } func (app *FrontendApp) unhandledError(responseWriter http.ResponseWriter, request *http.Request, err error) { log.Printf("500 internal server error: %+v\n", err) responseWriter.Header().Add("Content-Type", "text/plain") responseWriter.WriteHeader(http.StatusInternalServerError) responseWriter.Write([]byte("500 internal server error")) } func (app *FrontendApp) handleWithSession(path string, handler func(http.ResponseWriter, *http.Request, Session)) { app.Router.HandleFunc(path, func(responseWriter http.ResponseWriter, request *http.Request) { session, err := app.getSession(request, app.Domain) //bytes, _ := json.MarshalIndent(session, "", " ") //log.Printf("handleWithSession(): %s\n", string(bytes)) if err != nil { app.unhandledError(responseWriter, request, err) } else { handler(responseWriter, request, session) } }) } func (app *FrontendApp) buildPage(responseWriter http.ResponseWriter, request *http.Request, session Session, highlight, page template.HTML) { var buffer bytes.Buffer templateName := "page.html" pageTemplate, hasPageTemplate := app.HTMLTemplates[templateName] if !hasPageTemplate { panic(fmt.Errorf("template '%s' not found!", templateName)) } err := pageTemplate.Execute( &buffer, struct { Session Session Highlight template.HTML Page template.HTML CSSHash string }{session, highlight, page, app.cssHash}, ) app.deleteCookie(responseWriter, "flash") if err != nil { app.unhandledError(responseWriter, request, err) } else { io.Copy(responseWriter, &buffer) } } func (app *FrontendApp) renderTemplateToHTML(templateName string, data interface{}) (template.HTML, error) { var buffer bytes.Buffer desiredTemplate, hasTemplate := app.HTMLTemplates[templateName] if !hasTemplate { return "", fmt.Errorf("template '%s' not found!", templateName) } err := desiredTemplate.Execute(&buffer, data) if err != nil { return "", err } return template.HTML(buffer.String()), nil } func (app *FrontendApp) buildPageFromTemplate(responseWriter http.ResponseWriter, request *http.Request, session Session, templateName string, data interface{}) { content, err := app.renderTemplateToHTML(templateName, data) if err != nil { app.unhandledError(responseWriter, request, err) } else { app.buildPage(responseWriter, request, session, template.HTML(""), content) } } func (app *FrontendApp) setFlash(responseWriter http.ResponseWriter, session Session, key, value string) { (*session.Flash)[key] += value bytes, err := json.Marshal((*session.Flash)) if err != nil { log.Printf("can't setFlash because can't json marshal the flash map: %+v", err) return } app.setCookie(responseWriter, "flash", base64.RawURLEncoding.EncodeToString(bytes), 60, http.SameSiteStrictMode) } func (app *FrontendApp) reloadTemplates() { loadTemplate := func(filename string) *template.Template { newTemplateString, err := os.ReadFile(filename) if err != nil { panic(err) } newTemplate, err := template.New(filename).Parse(string(newTemplateString)) if err != nil { panic(err) } return newTemplate } frontendDirectory := "./frontend" //frontendVersion = hashTemplateAndStaticFiles(frontendDirectory)[:6] fileInfos, err := os.ReadDir(frontendDirectory) if err != nil { panic(err) } for _, fileInfo := range fileInfos { if !fileInfo.IsDir() && strings.Contains(fileInfo.Name(), ".gotemplate") { app.HTMLTemplates[strings.Replace(fileInfo.Name(), ".gotemplate", "", 1)] = loadTemplate(filepath.Join(frontendDirectory, fileInfo.Name())) } } } func (app *FrontendApp) getMatrixRoomNameWithCache(id string) string { nameFromCache, hasNameFromCache := app.roomNameCache[id] if hasNameFromCache { return nameFromCache } name, err := matrixAdmin.GetRoomName(id) if err != nil { log.Printf("error getting name for '%s': %s\n", id, err) } else { app.roomNameCache[id] = name } return name }
package net.minecraft.server.packs.repository; import com.mojang.logging.LogUtils; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Consumer; import javax.annotation.Nullable; import net.minecraft.FileUtil; import net.minecraft.network.chat.Component; import net.minecraft.server.packs.FilePackResources; import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.PathPackResources; import net.minecraft.server.packs.linkfs.LinkFileSystem; import net.minecraft.world.level.validation.ContentValidationException; import net.minecraft.world.level.validation.DirectoryValidator; import net.minecraft.world.level.validation.ForbiddenSymlinkInfo; import org.slf4j.Logger; public class FolderRepositorySource implements RepositorySource { static final Logger LOGGER = LogUtils.getLogger(); private final Path folder; private final PackType packType; private final PackSource packSource; private final DirectoryValidator validator; public FolderRepositorySource(Path pFolder, PackType pPackType, PackSource pPackSource, DirectoryValidator pValidator) { this.folder = pFolder; this.packType = pPackType; this.packSource = pPackSource; this.validator = pValidator; } private static String nameFromPath(Path pPath) { return pPath.getFileName().toString(); } public void loadPacks(Consumer<Pack> pOnLoad) { try { FileUtil.createDirectoriesSafe(this.folder); discoverPacks(this.folder, this.validator, false, (p_248243_, p_248244_) -> { String s = nameFromPath(p_248243_); Pack pack = Pack.readMetaAndCreate("file/" + s, Component.literal(s), false, p_248244_, this.packType, Pack.Position.TOP, this.packSource); if (pack != null) { pOnLoad.accept(pack); } }); } catch (IOException ioexception) { LOGGER.warn("Failed to list packs in {}", this.folder, ioexception); } } public static void discoverPacks(Path pFolder, DirectoryValidator pValidator, boolean pIsBuiltin, BiConsumer<Path, Pack.ResourcesSupplier> pOutput) throws IOException { FolderRepositorySource.FolderPackDetector folderrepositorysource$folderpackdetector = new FolderRepositorySource.FolderPackDetector(pValidator, pIsBuiltin); try (DirectoryStream<Path> directorystream = Files.newDirectoryStream(pFolder)) { for(Path path : directorystream) { try { List<ForbiddenSymlinkInfo> list = new ArrayList<>(); Pack.ResourcesSupplier pack$resourcessupplier = folderrepositorysource$folderpackdetector.detectPackResources(path, list); if (!list.isEmpty()) { LOGGER.warn("Ignoring potential pack entry: {}", (Object)ContentValidationException.getMessage(path, list)); } else if (pack$resourcessupplier != null) { pOutput.accept(path, pack$resourcessupplier); } else { LOGGER.info("Found non-pack entry '{}', ignoring", (Object)path); } } catch (IOException ioexception) { LOGGER.warn("Failed to read properties of '{}', ignoring", path, ioexception); } } } } static class FolderPackDetector extends PackDetector<Pack.ResourcesSupplier> { private final boolean isBuiltin; protected FolderPackDetector(DirectoryValidator pValidator, boolean pIsBuiltin) { super(pValidator); this.isBuiltin = pIsBuiltin; } @Nullable protected Pack.ResourcesSupplier createZipPack(Path pPath) { FileSystem filesystem = pPath.getFileSystem(); if (filesystem != FileSystems.getDefault() && !(filesystem instanceof LinkFileSystem)) { FolderRepositorySource.LOGGER.info("Can't open pack archive at {}", (Object)pPath); return null; } else { return new FilePackResources.FileResourcesSupplier(pPath, this.isBuiltin); } } protected Pack.ResourcesSupplier createDirectoryPack(Path pPath) { return new PathPackResources.PathResourcesSupplier(pPath, this.isBuiltin); } } }
using Market.Application.Interfaces; using Market.Application.Services; using Market.Domain; using Market.Infrastructure.Persistence; using Market.Infrastructure.Repositories; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.OpenApi.Models; using System.Reflection; namespace Market.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Market API", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); services.AddSingleton<IServiceProvider>(provider => provider); services.AddDbContext<MarketDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddRepositories(); services.AddApplication(); services.AddControllers(); Resolver.Initialize(services.BuildServiceProvider()); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Market API V1"); }); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
<template> <Head title="Your journey"/> <BreezeAuthenticatedLayout> <div class="py-12"> <div class="text-x bg-gray-900 opacity-90 max-w-prose rounded text-xl max-w-7xl mx-auto sm:px-6 lg:px-8"> <div class="overflow-hidden shadow-sm sm:rounded-lg"> <div class="p-6 pt-12 text-white"> <H2> The Nolands journey of {{ $page.props.auth.user.name }} </H2> <div class="flex flex-col items-center gap-4 justify-center mb-4"> <img alt="avatar" class="flex justify-center image avatar h-32 w-32 rounded-full overflow-hidden border border-gray-500" :src="$page.props.auth.user.avatar "> </div> <div> <H2>Step 1. RSVP & info.</H2> <div :class="{ 'border-green-900 bg-green-900/75': $page.props.auth.user.joins_in_2023, 'border-red-900 bg-red-900/75': !$page.props.auth.user.joins_in_2023 }" class="flex mb-8 items-center font-serif justify-between border-2 rounded-xl p-6 mb-4" > <div v-if="$page.props.auth.user.joins_in_2023 === true"> YOU ARE ATTENDING NOLANDS 2023 </div> <div v-if="$page.props.auth.user.joins_in_2023 === false"> YOU ARE NOT ATTENDING NOLANDS 2023 </div> <div v-if="$page.props.auth.user.joins_in_2023 === null"> PLEASE CONFIRM YOUR ATTENDANCE IN 2023 </div> <Link class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:shadow-outline-gray transition ease-in-out duration-150" :href="route('story.edit')"> Update my information <i class="fas fa-memo-circle-info ml-3"></i> </Link> </div> <div v-if="$page.props.auth.user.joins_in_2023"> <H2>Step 2. Team preferences.</H2> <div :class="{ 'border-green-900 bg-green-900/75': $page.props.auth.user.team_choice_first, 'border-red-900 bg-red-900/75': !$page.props.auth.user.team_choice_first }" class="flex mb-8 items-center font-serif justify-between border-2 rounded-xl p-6 mb-4" > <div v-if="$page.props.auth.user.team_choice_first"> YOU PROVIDED TEAM PREFERENCES </div> <div v-if="$page.props.auth.user.team_choice_first === null"> PLEASE PROVIDE TEAM PREFERENCES </div> <Link class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:shadow-outline-gray transition ease-in-out duration-150" :href="route('teams.index')"> Update team preferences <i class="fas fa-memo-circle-info ml-3"></i> </Link> </div> <H2>Step 3. Pay.</H2> <div :class="{ 'border-green-900 bg-green-900/75': $page.props.auth.user.payment_received, 'border-red-900 bg-red-900/75': !$page.props.auth.user.payment_received }" class="flex items-center font-serif justify-between border-2 rounded-xl p-6 mb-4" > <div v-if="$page.props.auth.user.payment_received"> Payment received and processed </div> <div v-else> Payment not yet received or processed </div> <a v-if="!$page.props.auth.user.payment_received" :href="$page.props.services.payment_link" target="_blank" class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:shadow-outline-gray transition ease-in-out duration-150"> Pay €130<i class="fas fa-sack-dollar ml-3"></i> </a> </div> <Story :user="$page.props.auth.user"/> </div> </div> </div> </div> </div> </div> </BreezeAuthenticatedLayout> </template> <script setup> import BreezeAuthenticatedLayout from '@/Layouts/Authenticated.vue' import {Head, Link} from '@inertiajs/inertia-vue3'; import {Inertia} from "@inertiajs/inertia"; import Story from "@/Components/Story.vue"; import H2 from "@/Components/H2.vue"; </script>
/* eslint-disable @typescript-eslint/no-empty-function */ export abstract class Component { protected parent: Component; public name: string; public setParent(parent: Component) { this.parent = parent; } public getParent(): Component { return this.parent; } /** * Вы можете предоставить метод, который позволит клиентскому коду понять, * может ли компонент иметь вложенные объекты. */ public isComposite(): boolean { return false; } public abstract getInfo(): string; public abstract getSize(): number; } abstract class File extends Component{ public size: number; public createDate: Date; constructor(fileName: string, fileSize: number, date: Date){ super(); this.name = fileName; this.size = fileSize; this.createDate = date; } public getInfo(): string{ return this.getFullName() + " - " + this.size + " - " + this.createDate.toLocaleString(); } public getSize(): number{ return this.size; } public abstract getFullName(): string; } export class TextFile extends File { public getFullName(){ return this.name + ".txt"; } } export class ImgFile extends File { public getFullName(){ return this.name + ".img"; } } export class Folder extends Component { protected children: Component[] = []; constructor(folderName: string){ super(); this.name = folderName; } public add(component: Component): void { this.children.push(component); component.setParent(this); } public remove(component: Component): void { const componentIndex = this.children.indexOf(component); this.children.splice(componentIndex, 1); component.setParent(null); } public isComposite(): boolean { return true; } public getInfo(): string { const results = []; let i = 1; for (const child of this.children) { results.push(i++ + ". " + child.getInfo()); } return `Folder(${results.join('||||')})`; } public getSize():number{ let value = 0; for (const child of this.children){ value += child.getSize(); } return value; } }
install.packages("readxl") library("readxl") airquality <- read_excel("AirQualityUCI.xlsx") airquality colnames(air_data) str(air_data) summary(air_data) library(dplyr) #airquality <- air_data %>% select(-c(NMHC.GT., X, X.1)) #Removing NMHC.GT and empty columns airquality2 <- airquality[,-c(1,2,5)] colnames(airquality) airquality str(airquality) #Structure of air quality dataset colnames(airquality) summary(airquality) #Summary of dataset #Replace -200 with NA airquality2[airquality2 == -200] <- NA #Converting NA to mean in each column airquality2[airquality2 == -200] <- NA airquality2$"CO(GT)"[is.na(airquality2$"CO(GT)")] <- mean(airquality2$"CO(GT)", na.rm = TRUE) airquality2$"PT08.S1(CO)"[is.na(airquality2$"PT08.S1(CO)")] <- mean(airquality2$"PT08.S1(CO)", na.rm = TRUE) airquality2$"C6H6(GT)"[is.na(airquality2$"C6H6(GT)")] <- mean(airquality2$"C6H6(GT)", na.rm = TRUE) airquality2$"PT08.S2(NMHC)"[is.na(airquality2$"PT08.S2(NMHC)")] <- mean(airquality2$"PT08.S2(NMHC)", na.rm = TRUE) airquality2$"NOx(GT)"[is.na(airquality2$"NOx(GT)")] <- mean(airquality2$"NOx(GT)", na.rm = TRUE) airquality2$"PT08.S3(NOx)"[is.na(airquality2$"PT08.S3(NOx)")] <- mean(airquality2$"PT08.S3(NOx)", na.rm = TRUE) airquality2$"PT08.S4(NO2)"[is.na(airquality2$"PT08.S4(NO2)")] <- mean(airquality2$"PT08.S4(NO2)", na.rm = TRUE) airquality2$"PT08.S5(O3)"[is.na(airquality2$"PT08.S5(O3)")] <- mean(airquality2$"PT08.S5(O3)", na.rm = TRUE) airquality2$"T"[is.na(airquality2$"T")] <- mean(airquality2$"T", na.rm = TRUE) airquality2$"RH"[is.na(airquality2$"RH")] <- mean(airquality2$"RH", na.rm = TRUE) airquality2$"AH"[is.na(airquality2$"AH")] <- mean(airquality2$"AH", na.rm = TRUE) airquality2$"NO2(GT)"[is.na(airquality2$"NO2(GT)")] <- mean(airquality2$"NO2(GT)", na.rm = TRUE) summary(airquality2) #Boxplot of data set boxplot(airquality[,3]) boxplot(airquality[,4]) boxplot(airquality[,5]) boxplot(airquality[,6]) boxplot(airquality[,7]) boxplot(airquality[,8]) boxplot(airquality[,9]) boxplot(airquality[,10]) boxplot(airquality[,11]) boxplot(airquality[,12]) boxplot(airquality[,13]) boxplot(airquality[,14]) #pairs(airquality[,3:14]) library(MASS) library(rpart) library(rpart.plot) #air_sample <- sample(nrow(airquality2),nrow(airquality2)*0.80) air_sample air.train <- airquality2[air_sample,] air.test <- airquality2[-air_sample,] #air_rpart <- rpart(formula = T ~ ., data = air.train) #air_rpart #Training of Air quality data #air1 <- lm(T ~ CO.GT. + PT08.S1.CO. + C6H6.GT. + PT08.S2.NMHC. + NOx.GT. + PT08.S3.NOx. + NO2.GT. + PT08.S4.NO2. + PT08.S5.O3. + RH + AH, data =air_train) air1 <- lm(T ~., data =air.train) summary(air1) #Evaluating Model Fitness #In-sample with training data #MSE air_summary <- (summary(air1)) (air_summary$sigma)^2 #R^2 of model air_summary$r.squared #Adjusted R^2 air_summary$adj.r.squared AIC(air1) BIC(air1) pi1 <- predict(object = air1, newdata = air.train) pi1 #MSE mean((pi1- air.train$T)^2) predict(air1) #R-squared air_summary$r.squared #Adjusted R-squared air_summary$adj.r.squared #AIC and BIC AIC(air1) BIC(air1) #Out of sample #Prediction pi <- predict(object = air1, newdata = air.test) pi #MSE mean((pi - air.test$T)^2) #MAE mean(abs(pi - air.test$T)) predict(air1) #Variable Selection ################################ #rpart function air_rpart <- rpart(formula = T ~., data = air.train) #1.1 Printing and ploting the tree air_rpart prp(air_rpart, digits = 4, extra =1) #top root nodes; end nodes -> leaf node #1..1.2 Predicition using regression trees #in-sample prediciton train_pred_tree = predict(air_rpart) train_pred_tree #out-of-sample prediciton test_pred_tree = predict(air_rpart, air.test) test_pred_reg ?predict() #Calculate MSE for tree model MSE.tree <- mean((test_pred_tree-air.test$T)^2) MSE.tree #Comparing out-of-sample with linear regression model with all variable air.reg = lm(T~., data = air.train) test_pred_reg = predict(air.reg, air.test) mean((test_pred_reg - air.test$T)^2) #1.1.3 Comparing the performance of reg tree with linear regression model #in terms of prediction error air_lm <- rpart(T ~., data = airquality) air_train_pred_lm<- rpart(T ~., data = air.train) air_test_pred_lm<- rpart(T ~., data = air.test) #1.2 Pruning air_largetree <- rpart(formula = T ~., data = air.train, cp = 0.01) #Plot the tree prp(air_largetree) #relationship between 10-fold cross-validation error in the training set #and size of tree plotcp(boston_largetree) printcp(boston_largetree) ######################################################### #NNET #install.packages("neuralnet") library(neuralnet) library(nnet) # load Boston data ################################################# ####### ANN for Regression ################## ################################################# ####### Note, the response variable has to be rescaled to (0,1) range, ####### and predictors are recommended to be standardized as well. air.train[,-12]<- as.data.frame(scale(air.train[,-12])) air.train$T<- air.train$T/44.6 air.test[,-12]<- as.data.frame(scale(air.test[,-12])) # fit neural network with one hidden layer air.ann1<- neuralnet(T~., data = air.train, hidden = 5, linear.output = TRUE) #Plot the neural network plot(air.ann1) ####### Prediction on testing sample. air.pred1<- compute(air.ann1, air.test) air.pred1<- air.pred1$net.result*44.6 mean((air.test$T-air.pred1)^2) ####### Let's add another hidden layer. # fit neural network with one hidden layer air.ann2<- neuralnet(T~., data = air.train, hidden = c(5,5), linear.output = TRUE) #Plot the neural network plot(air.ann2) ####### Prediction on testing sample. air.pred2<- compute(air.ann2, air.test) air.pred2<- air.pred2$net.result*44.6 mean((air.test$T-air.pred2)^2) ####### Comparing with linear regression. air.reg<- lm(T~., data = air.train) air.reg.pred<- predict(air.reg, newdata = air.test)*44.6 air.reg.pred summary(air.reg.pred) mean((air.test$T-air.reg.pred)^2)
//package com.TruckBooking.routeData.Exception; // //import com.TruckBooking.TruckBooking.Exception.BusinessException; //import lombok.extern.slf4j.Slf4j; //import org.hibernate.exception.ConstraintViolationException; //import org.springframework.core.Ordered; //import org.springframework.core.annotation.Order; //import org.springframework.dao.DataIntegrityViolationException; //import org.springframework.http.HttpHeaders; //import org.springframework.http.HttpStatus; //import org.springframework.http.ResponseEntity; //import org.springframework.http.converter.HttpMessageNotReadableException; //import org.springframework.http.converter.HttpMessageNotWritableException; //import org.springframework.web.HttpMediaTypeNotSupportedException; //import org.springframework.web.bind.MethodArgumentNotValidException; //import org.springframework.web.bind.MissingServletRequestParameterException; //import org.springframework.web.bind.annotation.ControllerAdvice; //import org.springframework.web.bind.annotation.ExceptionHandler; //import org.springframework.web.context.request.ServletWebRequest; //import org.springframework.web.context.request.WebRequest; //import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; //import org.springframework.web.servlet.NoHandlerFoundException; //import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; // //@Order(Ordered.HIGHEST_PRECEDENCE) //@Slf4j //@ControllerAdvice //public class RouteDataExceptionAdvice extends ResponseEntityExceptionHandler { // // /** // * Handle MissingServletRequestParameterException. Triggered when a 'required' // * request parameter is missing. // * // * @param ex MissingServletRequestParameterException // * @param headers HttpHeaders // * @param status HttpStatus // * @param request WebRequest // * @return the ApiError object // */ // @Override // protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, // HttpHeaders headers, HttpStatus status, WebRequest request) { // log.error("handleMissingServletRequestParameter is started"); // String error = ex.getParameterName() + " parameter is missing"; // return buildResponseEntity(new RouteDataErrorResponse(HttpStatus.BAD_REQUEST, error, ex)); // } // // /** // * Handle HttpMediaTypeNotSupportedException. This one triggers when JSON is // * invalid as well. // * // * @param ex HttpMediaTypeNotSupportedException // * @param headers HttpHeaders // * @param status HttpStatus // * @param request WebRequest // * @return the ApiError object // */ // @Override // protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, // HttpHeaders headers, HttpStatus status, WebRequest request) { // log.error("handleHttpMediaTypeNotSupported is started"); // StringBuilder builder = new StringBuilder(); // builder.append(ex.getContentType()); // builder.append(" media type is not supported. Supported media types are "); // ex.getSupportedMediaTypes().forEach(t -> builder.append(t).append(", ")); // return buildResponseEntity(new RouteDataErrorResponse(HttpStatus.UNSUPPORTED_MEDIA_TYPE, // builder.substring(0, builder.length() - 2), ex)); // } // // /** // * Handle MethodArgumentNotValidException. Triggered when an object fails @Valid // * validation. // * // * @param ex the MethodArgumentNotValidException that is thrown when @Valid // * validation fails // * @param headers HttpHeaders // * @param status HttpStatus // * @param request WebRequest // * @return the ApiError object // */ // @Override // protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, // HttpHeaders headers, HttpStatus status, WebRequest request) { // log.error("handleMethodArgumentNotValid is started"); // RouteDataErrorResponse routeDataErrorResponse = new RouteDataErrorResponse(HttpStatus.BAD_REQUEST); // routeDataErrorResponse.setMessage("Validation error"); // routeDataErrorResponse.addValidationErrors(ex.getBindingResult().getFieldErrors()); // routeDataErrorResponse.addValidationError(ex.getBindingResult().getGlobalErrors()); // return buildResponseEntity(routeDataErrorResponse); // } // // /** // * Handles javax.validation.ConstraintViolationException. Thrown when @Validated // * fails. // * // * @param ex the ConstraintViolationException // * @return the ApiError object // */ // @ExceptionHandler(javax.validation.ConstraintViolationException.class) // protected ResponseEntity<Object> handleConstraintViolation(javax.validation.ConstraintViolationException ex) { // log.error("handleConstraintViolation is started"); // RouteDataErrorResponse routeDataErrorResponse = new RouteDataErrorResponse(HttpStatus.BAD_REQUEST); // routeDataErrorResponse.setMessage("Validation error"); // routeDataErrorResponse.addValidationErrors(ex.getConstraintViolations()); // return buildResponseEntity(routeDataErrorResponse); // } // // /** // * Handles EntityNotFoundException. Created to encapsulate errors with more // * detail than javax.persistence.EntityNotFoundException. // * // * @param ex the EntityNotFoundException // * @return the ApiError object // */ // @ExceptionHandler(EntityNotFoundException.class) // protected ResponseEntity<Object> handleEntityNotFound(EntityNotFoundException ex) { // log.error("handleEntityNotFound is started"); // RouteDataErrorResponse routeDataErrorResponse = new RouteDataErrorResponse(HttpStatus.NOT_FOUND); // routeDataErrorResponse.setMessage(ex.getMessage()); // return buildResponseEntity(routeDataErrorResponse); // } // // /** // * Handle HttpMessageNotReadableException. Happens when request JSON is // * malformed. // * // * @param ex HttpMessageNotReadableException // * @param headers HttpHeaders // * @param status HttpStatus // * @param request WebRequest // * @return the ApiError object // */ // @Override // protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, // HttpHeaders headers, HttpStatus status, WebRequest request) { // log.error("handleHttpMessageNotReadable is started"); // ServletWebRequest servletWebRequest = (ServletWebRequest) request; // log.info("{} to {}", servletWebRequest.getHttpMethod(), servletWebRequest.getRequest().getServletPath()); // String error = "Malformed JSON request"; // return buildResponseEntity(new RouteDataErrorResponse(HttpStatus.BAD_REQUEST, error, ex)); // } // // /** // * Handle HttpMessageNotWritableException. // * // * @param ex HttpMessageNotWritableException // * @param headers HttpHeaders // * @param status HttpStatus // * @param request WebRequest // * @return the ApiError object // */ // @Override // protected ResponseEntity<Object> handleHttpMessageNotWritable(HttpMessageNotWritableException ex, // HttpHeaders headers, HttpStatus status, WebRequest request) { // log.error("handleHttpMessageNotWritable is started"); // String error = "Error writing JSON output"; // return buildResponseEntity(new RouteDataErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, error, ex)); // } // // /** // * Handle NoHandlerFoundException. // * // * @param ex // * @param headers // * @param status // * @param request // * @return // */ // @Override // protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, // HttpStatus status, WebRequest request) { // log.error("handleNoHandlerFoundException is started"); // RouteDataErrorResponse routeDataErrorResponse = new RouteDataErrorResponse(HttpStatus.BAD_REQUEST); // routeDataErrorResponse.setMessage( // String.format("Could not find the %s method for URL %s", ex.getHttpMethod(), ex.getRequestURL())); // routeDataErrorResponse.setDebugMessage(ex.getMessage()); // return buildResponseEntity(routeDataErrorResponse); // } // // /** // * Handle javax.persistence.EntityNotFoundException // */ // @ExceptionHandler(javax.persistence.EntityNotFoundException.class) // protected ResponseEntity<Object> handleEntityNotFound(javax.persistence.EntityNotFoundException ex) { // log.error("handleEntityNotFound is started"); // return buildResponseEntity(new RouteDataErrorResponse(HttpStatus.NOT_FOUND, ex)); // } // // /** // * Handle DataIntegrityViolationException, inspects the cause for different DB // * causes. // * // * @param ex the DataIntegrityViolationException // * @return the ApiError object // */ // @ExceptionHandler(DataIntegrityViolationException.class) // protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex, // WebRequest request) { // log.error("handleDataIntegrityViolation is started"); // if (ex.getCause() instanceof ConstraintViolationException) { // return buildResponseEntity(new RouteDataErrorResponse(HttpStatus.CONFLICT, "Database error", ex.getCause())); // } // return buildResponseEntity(new RouteDataErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex)); // } // // /** // * Handle Exception, handle generic Exception.class // * // * @param ex the Exception // * @return the ApiError object // */ // @ExceptionHandler(MethodArgumentTypeMismatchException.class) // protected ResponseEntity<Object> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex, // WebRequest request) { // log.error("handleMethodArgumentTypeMismatch is started"); // RouteDataErrorResponse routeDataErrorResponse = new RouteDataErrorResponse(HttpStatus.BAD_REQUEST); // routeDataErrorResponse // .setMessage(String.format("The parameter '%s' of value '%s' could not be converted to type '%s'", // ex.getName(), ex.getValue(), ex.getRequiredType().getSimpleName())); // routeDataErrorResponse.setDebugMessage(ex.getMessage()); // return buildResponseEntity(routeDataErrorResponse); // } // // @ExceptionHandler(com.TruckBooking.TruckBooking.Exception.BusinessException.class) // protected ResponseEntity<Object> handleBusinessException(BusinessException ex) { // log.error("handleBusiness Exception is started"); // RouteDataErrorResponse routeDataErrorResponse = new RouteDataErrorResponse(HttpStatus.UNPROCESSABLE_ENTITY); // routeDataErrorResponse.setMessage(ex.getMessage()); // return buildResponseEntity(routeDataErrorResponse); // } // // @ExceptionHandler(Exception.class) // public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) // { // log.error("handleAllExceptions is started"); // return buildResponseEntity(new RouteDataErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR , ex)); // } // // private ResponseEntity<Object> buildResponseEntity(RouteDataErrorResponse routeDataErrorResponse) { // return new ResponseEntity<>(routeDataErrorResponse, routeDataErrorResponse.getStatus()); // } //}
/* * Copyright (C) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { expect } from "@ohos/hypium"; import cryptoFramework from "@ohos.security.cryptoFramework"; import { stringTouInt8Array, uInt8ArrayToShowStr, uInt8ArrayToString, } from "../common/publicDoString"; async function testMDDigestPromise(MDAlgoName) { var globalMd; var globalText = "my test data"; return new Promise((resolve, reject) => { globalMd = cryptoFramework.createMd(MDAlgoName); expect(globalMd != null).assertTrue(); console.warn("md= " + globalMd); console.warn("MD algName is: " + globalMd.algName); let inBlob = { data: stringTouInt8Array(globalText), }; globalMd .update(inBlob) .then(() => { console.warn("[Promise]: update finished"); let digestBlob = globalMd.digest(); return digestBlob; }) .then((mdOutput) => { console.warn( "[Promise]: digest result1: " + uInt8ArrayToShowStr(mdOutput.data) ); console.warn("[Promise]: digest result2: " + mdOutput.data); let mdLen = globalMd.getMdLength(); console.warn("Md len: " + mdLen); expect(mdOutput != null && mdLen != 0 && mdLen != null).assertTrue(); resolve(); }) .catch((err) => { console.error("[promise]catch err:" + err); reject(err); }); }); } async function testHMACDigestPromise(HMACAlgoName, keyAlgoName) { var globalHMAC; var globalText = "my test data"; var globalsymKeyGenerator; var inBlob = { data: stringTouInt8Array(globalText), }; return new Promise((resolve, reject) => { globalHMAC = cryptoFramework.createMac(HMACAlgoName); expect(globalHMAC != null).assertTrue(); console.warn("mac= " + globalHMAC); console.warn("HMAC algName is: " + globalHMAC.algName); console.log("start to call createSymKeyGenerator()"); globalsymKeyGenerator = cryptoFramework.createSymKeyGenerator(keyAlgoName); console.warn("symKeyGenerator algName:" + globalsymKeyGenerator.algName); expect(globalsymKeyGenerator != null).assertTrue(); console.log("createSymKeyGenerator ok"); console.warn("symKeyGenerator algName:" + globalsymKeyGenerator.algName); globalsymKeyGenerator .generateSymKey() .then((key) => { expect(key != null).assertTrue(); console.warn("generateSymKey ok"); console.warn("key algName:" + key.algName); console.warn("key format:" + key.format); var encodedKey = key.getEncoded(); console.warn( "key getEncoded hex: " + uInt8ArrayToShowStr(encodedKey.data) ); var promiseMacInit = globalHMAC.init(key); return promiseMacInit; }) .then(() => { var promiseMacUpdate = globalHMAC.update(inBlob); return promiseMacUpdate; }) .then(() => { var promiseMacdoFinal = globalHMAC.doFinal(); return promiseMacdoFinal; }) .then((macOutput) => { console.warn("HMAC result:" + macOutput.data); let macLen = globalHMAC.getMacLength(); console.warn("MAC len:" + macLen); expect(macOutput != null && macLen != 0 && macLen != null).assertTrue(); resolve(); }) .catch((err) => { console.error("[promise]catch err:" + err); reject(err); }); }); } async function testHMACErrorAlgorithm(HMACAlgoName1, HMACAlgoName2) { var globalHMAC; var globalText = "my test data"; var inBlob = { data: stringTouInt8Array(globalText), }; return new Promise((resolve, reject) => { try { globalHMAC = cryptoFramework.createMac(HMACAlgoName1); reject(); } catch (error) { console.error("[Promise]: error code1: " + error.code + ", message is: " + error.message); expect(error.code == 801).assertTrue(); } try { globalHMAC = cryptoFramework.createMac(HMACAlgoName2); reject(); } catch (error) { console.error("[Promise]: error code2: " + error.code + ", message is: " + error.message); expect(error.code == 401).assertTrue(); resolve(); } }); } async function testHMACDigestPromiseErrorKey(HMACAlgoName, keyAlgoName) { var globalHMAC; var globalText = "my test data"; let globalsymKeyGenerator; var inBlob = { data: stringTouInt8Array(globalText), }; return new Promise((resolve, reject) => { globalHMAC = cryptoFramework.createMac(HMACAlgoName); expect(globalHMAC != null).assertTrue(); console.warn("mac= " + globalHMAC); console.warn("HMAC algName is: " + globalHMAC.algName); console.log("start to call createSymKeyGenerator()"); try { globalsymKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyAlgoName); } catch (error) { console.error("[Promise]: error code1: " + error.code + ", message is: " + error.message); } console.warn("symKeyGenerator algName:" + globalsymKeyGenerator.algName); expect(globalsymKeyGenerator != null).assertTrue(); console.log("createSymKeyGenerator ok"); let key = globalsymKeyGenerator.generateKeyPair(); try { var promiseMacInit = globalHMAC.init(key); expect(promiseMacInit == null).assertTrue(); reject(); } catch (error) { console.error("[Promise]init(key): error code: " + error.code + ", message is: " + error.message); expect(error.code == 401).assertTrue(); resolve(); }; try { var promiseMacInit = globalHMAC.init(null); expect(promiseMacInit == null).assertTrue(); reject(); } catch (error) { console.error("[Promise]init(null): error code: " + error.code + ", message is: " + error.message); expect(error.code == 401).assertTrue(); resolve(); }; }); } async function testHMACDigestPromiseDatablobNull(HMACAlgoName, keyAlgoName) { var globalHMAC; var globalText = "my test data"; var globalsymKeyGenerator; var inBlob = { data: stringTouInt8Array(globalText), }; return new Promise((resolve, reject) => { globalHMAC = cryptoFramework.createMac(HMACAlgoName); expect(globalHMAC != null).assertTrue(); console.warn("mac= " + globalHMAC); console.warn("HMAC algName is: " + globalHMAC.algName); console.log("start to call createSymKeyGenerator()"); globalsymKeyGenerator = cryptoFramework.createSymKeyGenerator(keyAlgoName); console.warn("symKeyGenerator algName:" + globalsymKeyGenerator.algName); expect(globalsymKeyGenerator != null).assertTrue(); console.log("createSymKeyGenerator ok"); console.warn("symKeyGenerator algName:" + globalsymKeyGenerator.algName); globalsymKeyGenerator .generateSymKey() .then((key) => { expect(key != null).assertTrue(); console.warn("generateSymKey ok"); console.warn("key algName:" + key.algName); console.warn("key format:" + key.format); var encodedKey = key.getEncoded(); console.warn( "key getEncoded hex: " + uInt8ArrayToShowStr(encodedKey.data) ); var promiseMacInit = globalHMAC.init(key); return promiseMacInit; }) .then(() => { try { var promiseMacUpdate = globalHMAC.update(null); console.warn("promiseMacUpdate:" + promiseMacUpdate); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); expect(error.code == 401).assertTrue(); resolve(); } }) .then(() => { var promiseMacdoFinal = globalHMAC.doFinal(); return promiseMacdoFinal; }) .catch((err) => { console.error("[promise]catch err:" + err); reject(err); }); }); } async function testHMACDigestPromiseDatablobLong(HMACAlgoName, keyAlgoName, DatablobLen) { var globalHMAC; var globalsymKeyGenerator; var i; var globalText; var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefhijklmnopqrstuvwxyz",n = t.length,s=""; for (i = 0; i < DatablobLen; i++){ globalText += t.charAt(Math.floor(Math.random() * n)); } console.warn("Datablob = " + globalText); var inBlob = { data: stringTouInt8Array(globalText), }; return new Promise((resolve, reject) => { globalHMAC = cryptoFramework.createMac(HMACAlgoName); resolve(); expect(globalHMAC != null).assertTrue(); console.warn("mac= " + globalHMAC); console.warn("HMAC algName is: " + globalHMAC.algName); console.log("start to call createSymKeyGenerator()"); globalsymKeyGenerator = cryptoFramework.createSymKeyGenerator(keyAlgoName); console.warn("symKeyGenerator algName:" + globalsymKeyGenerator.algName); expect(globalsymKeyGenerator != null).assertTrue(); console.log("createSymKeyGenerator ok"); globalsymKeyGenerator .generateSymKey() .then((key) => { expect(key != null).assertTrue(); console.warn("generateSymKey ok"); console.warn("key algName:" + key.algName); console.warn("key format:" + key.format); var encodedKey = key.getEncoded(); console.warn( "key getEncoded hex: " + uInt8ArrayToShowStr(encodedKey.data) ); var promiseMacInit = globalHMAC.init(key); return promiseMacInit; }) .then(() => { try { var promiseMacUpdate = globalHMAC.update(inBlob); console.log("promiseMacUpdate = " + promiseMacUpdate); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } }) .then(() => { var promiseMacdoFinal = globalHMAC.doFinal(); console.log("promiseMacdoFinal = " + promiseMacdoFinal); return promiseMacdoFinal; }) .catch((err) => { console.error("[promise]catch err:" + err); reject(err); }); }); } export { testMDDigestPromise, testHMACDigestPromise, testHMACErrorAlgorithm, testHMACDigestPromiseErrorKey, testHMACDigestPromiseDatablobNull, testHMACDigestPromiseDatablobLong };
/** * Gmixr Native App * https://github.com/jcnh74/Gmixr * @flow */ import React, { Component } from 'react' import { AsyncStorage, NativeModules, ListView, View, Dimensions } from 'react-native' // Components import AlbumRow from './AlbumRow' // Native Modules const SpotifyAuth = NativeModules.SpotifyAuth var styles = require('../style'); const {height, width} = Dimensions.get('window') export default class AlbumSelectView extends Component { constructor(props) { super(props) this.state = { userAlbums: [], dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2 }), albumsData: [], page: 0, total: 0, contentOffsetY:0 } } _processAlbums(tracks, callback){ var mydata = this.state.albumsData for(i = 0; i < tracks.length; i++){ var album = tracks[i].track.album var artist = tracks[i].track.artists var artistName = 'following'; if(typeof(artist) !== 'undefined' && artist.length){ if(artist[0].name){ artistName = artist[0].name } } var imgArr = album.images var playlistImage = 'https://facebook.github.io/react/img/logo_og.png' if(typeof(imgArr) !== 'undefined' && imgArr.length){ if(imgArr[imgArr.length - 1].url){ playlistImage = imgArr[imgArr.length - 1].url } } var found = mydata.some(function (el) { return el.artist === artistName; }) if (!found) { mydata.push({name:album.name, uri:album.uri, image:playlistImage, artist: artistName}) } } var page = this.state.page this.setState({ albumsData: mydata, dataSource: this.state.dataSource.cloneWithRows(mydata), page: page + 1 }, () => { if (typeof callback === "function") { callback(true) } }) } // Get all the users Playlists _fetchAlbums(bearer){ var offset = this.state.page * 50 var userAlbums = this.state.userAlbums fetch('https://api.spotify.com/v1/me/tracks?offset='+offset+'&limit=50', { method: 'GET', headers: { 'Accept': 'application/json', 'Authorization': 'Bearer '+bearer } }) .then((response) => response.json()) .then((responseJson) => { if(responseJson.error){ return } if( ( this.state.page * 50 ) >= responseJson.total ){ return } var tracks = responseJson.items var merge = userAlbums.concat(tracks) this.setState({ userAlbums: merge, total: responseJson.total }, function(){ AsyncStorage.setItem( '@GmixrStore:tracksTotal', JSON.stringify(responseJson.total) ) AsyncStorage.setItem( '@GmixrStore:tracks', JSON.stringify(merge) ) this._processAlbums(merge, () => { this._fetchAlbums(bearer) }) }) }) .catch((err) => { console.error(err) }) } // If we can, respond to fetch function // TODO: May be able to bypass this function _getUsersAlbums(){ // Clear Storage // AsyncStorage.removeItem('@GmixrStore:albums') AsyncStorage.getItem('@GmixrStore:tracks', (err, res) => { if(err){ return } if(res){ this._processAlbums(JSON.parse(res)) }else{ SpotifyAuth.getToken((result)=>{ if(result){ this._fetchAlbums(result) }else{ AsyncStorage.getItem('@GmixrStore:token', (err, res) => { this._fetchAlbums(res) }) } }) } }) } _chooseAlbum(albums){ this.props.chooseAlbum(albums) } _handleScroll(event: Object) { AsyncStorage.setItem( '@GmixrStore:albumsOffsetY', JSON.stringify(event.nativeEvent.contentOffset.y) ) } render() { // AsyncStorage.removeItem('@GmixrStore:tracks') // AsyncStorage.removeItem('@GmixrStore:tracksTotal') return ( <View> <ListView ref="listview" style={[styles.listView, {top: 0, height: height - this.props.vidHeight - 94 }]} dataSource={this.state.dataSource} renderRow={(rowData, sectionID, rowID) => <AlbumRow key={rowID} data={rowData} chooseAlbum={(albums) => this._chooseAlbum(albums)} />} enableEmptySections={true} onScroll={this._handleScroll} contentOffset={{y:this.state.contentOffsetY}} scrollEventThrottle={16} /> </View> ) } componentWillMount() { AsyncStorage.getItem('@GmixrStore:albumsOffsetY', (err, res) => { if(res){ this.setState({ contentOffsetY: parseInt(res) }) }else{ this.setState({ contentOffsetY: 0 }) } }) } componentDidMount() { // IMPORTANT: HIDE IN RELEASE // AsyncStorage.removeItem('@GmixrStore:tracks') // AsyncStorage.removeItem('@GmixrStore:tracksTotal') this.props.events.addListener('userAquired', this._getUsersAlbums, this) if(this.props.userAquired){ this._getUsersAlbums() } } }
#' bouts_length_filter #' #' @description 'bouts_length_filter' generates the short and long sequence maps #' #' @details This function applies the cut-point classes for each epoch in a data file. Then the lengths of the consecutive epochs in the same cut-point class and their corresponding values are determined. After the non-wear time (zerocounts) and invalid days (minwear) are filtered out and the tolerance is incorporated (using function 'tolerated_bouts'), the sequence maps are calculated (using function 'generate_sequence_map') and the long and short sequence maps are generated. #' #' @param counts A vector containing the (aggregated) accelerometer counts from the data file #' @param timeline A vector containing the time stamps corresponding to the accelerometer counts #' @param file_name A string specifying the file name including file extension #' @param epochsize An integer that defines the epoch length in seconds #' @param minwear An integer that defines the minimum wear time in minutes that constitutes a valid day #' @param zerocounts An integer that defines the non-wear time as number of consecutive epochs containing zero counts #' @param cutpoints A vector of integers that defines the cut-point threshold values in counts per minute (cpm). For example if value = c(0, 100, 2296, 4012) the corresponding thresholds are: SB 0 - 100, LPA 100 - 2296, MPA 2296 - 4012, VPA >= 4012 #' @param bts A vector of integers that defines the bout durations in minutes (Default : c(0, 5, 10, 30)). Note: The function only considers bouts < 60 minutes. #' @param tz A string specifying the time zone to be used for the conversion (see strptime) #' @param tolerance_function One of c("V1", "V2") defining the tolerance function used for the bout calculation, where "V1" looks whether a pair of segments (based on intensity) is within a tolerance of 10%; "V2" looks at the whole of segments to identify breaks in bouts within this tolerance (Default : "V2") #' #' @return result A list of \item{days}{An integer indicating the number of days} \item{long_mapping}{A vector consisting of the sequence map for all days} \item{short_mapping}{A matrix in which each column represents a sequence map of one day} \item{long_mapping_length}{An integer representing the length of the long sequence map} \item{short_mapping_length}{A vector of integers representing the lengths of the short sequence maps} #' @export # New sequencing bouts_length_filter <- function(counts, timeline, file_name, epochsize, minwear, zerocounts, cutpoints, bts, tz, tolerance_function="V2") { recording_date = as.Date(timeline, tz = tz) ucf = unique(recording_date) nucf <- length(ucf) # number of unique days in aggregated values Nepoch_per_minute = 60 / epochsize # frequency expressed as number of epochs per minute cutpoints = cutpoints / Nepoch_per_minute # cutpoints for the specified (epoch length of aggregated values) epoch length # Initialize variables: days = 0 long_mapping = short_mapping = NULL long_mapping_length = short_mapping_length = NULL ucfs = NULL for (j in 1:nucf) { # loop over the days counts.subset <- counts[recording_date == as.Date(ucf[j])] # print("---") # print(counts.subset[(61*4):(140*4)]) # print(cutpoints) # Wear / Non-wear detection: # !!! We are not removing non-wear from the data at this point; non-wear data is labeled as -999 !!! countsNonWear <- labelNonWear(counts.subset, zerocounts, Nepoch_per_minute) #non-wear time is => 60 minutes (= default for zerocounts) consecutive zeros #z <- findInterval(counts.subset, vec = cutpoints, all.inside = F) #bouts <- rle(z) z <- findInterval(countsNonWear, vec = c(-999, cutpoints), all.inside = F) bouts <- rle(z - 1) # bouts has two elements: # - length: bout length in epochs # - value: bout class (value 0 is non-wear time!) # print(length(which(bouts$values == 0))) # simulated data shows 1 bout as expected (61 minutes) # print(bouts$lengths[which(bouts$values == 0)]) # simulated data shows 244 epochs as expected (4 epochs x 61 minutes) #weartime = sum(bouts$lengths) #noweartime = sum(bouts$lengths[bouts$values == 0]) weartime = length(countsNonWear) noweartime = sum(bouts$lengths[bouts$length >= zerocounts * Nepoch_per_minute & bouts$values == 0]) #non-wear time is => 60 minutes (= default for zerocounts) consecutive sedentary behavior #noweartime = sum(bouts$lengths[bouts$length >= zerocounts * Nepoch_per_minute #& bouts$values == 1]) #non-wear time is => 60 minutes (= default for zerocounts) consecutive sedentary behavior weartime = weartime - noweartime # Only consider bouts that last less than 60 minutes: ## If we do this, then no classification for non-wear in the sequence maps #bt_values = bouts$values[bouts$lengths < 60 * Nepoch_per_minute] #bt_lengths = bouts$lengths[bouts$lengths < 60 * Nepoch_per_minute] # Consider all bouts that last less than 60 minutes, but also include non-wear time bouts independent of their length bt_values = bouts$values[(bouts$lengths < 60 * Nepoch_per_minute) | (bouts$values == 0)] bt_lengths = bouts$lengths[(bouts$lengths < 60 * Nepoch_per_minute) | (bouts$values == 0)] if (weartime >= (minwear * Nepoch_per_minute)) { # valid day = 480 min (= default for minwear) days = days + 1 ucfs = c(ucfs, as.Date(ucf[j])) # Make this more flexible, according to input bts & add extra variable for timethresholds? # tolerance classes MVPA (class 4), LPA (class 3), SB/inactivity (class 2): time thresholds 5, 10, 30, 60 minutes bb <- tolerated_bouts(bt_values, bt_lengths, tolerance_class = c(4, 3, 2), timethresholds = c(5, 10, 30, 60), Nepoch_per_minute, tolerance_function=tolerance_function) map_per_day = generate_sequence_map(bb$values, bb$lengths, Nepoch_per_minute, bts) sub_length <- bb$lengths # short_mapping is to put the map_per_day from all days next to each other in rows short_mapping = shorting.map(short_mapping, map_per_day) # # short_mapping is to put the map_per_day from all days after each other in one long vector long_mapping = c(long_mapping, map_per_day) # keep track of lengths corresponding to all maps: long_mapping_length = c(long_mapping_length, sub_length) # keep track of lengths corresponding to all maps: short_mapping_length = shorting.map(short_mapping_length, sub_length) # } if (length(long_mapping) == 0) { long_mapping = 0 long_mapping_length = 0 } } if (length(ucfs) > 0) { row.names(short_mapping) = paste(file_name, ucfs, sep = "_") row.names(short_mapping_length) = paste(file_name, ucfs, sep = "_") } result <- list(days = days, long_mapping = long_mapping, short_mapping = short_mapping, long_mapping_length = long_mapping_length, short_mapping_length = short_mapping_length) return(result) }
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import { expect } from 'chai' import { wait } from '@peertube/peertube-core-utils' import { VideoPrivacy } from '@peertube/peertube-models' import { cleanupTests, createMultipleServers, PeerTubeServer, SearchCommand, setAccessTokensToServers, setDefaultAccountAvatar, setDefaultVideoChannel, waitJobs } from '@peertube/peertube-server-commands' describe('Test ActivityPub videos search', function () { let servers: PeerTubeServer[] let videoServer1UUID: string let videoServer2UUID: string let command: SearchCommand before(async function () { this.timeout(120000) servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) await setDefaultAccountAvatar(servers) { const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video 1 on server 1' } }) videoServer1UUID = uuid } { const { uuid } = await servers[1].videos.upload({ attributes: { name: 'video 1 on server 2' } }) videoServer2UUID = uuid } await waitJobs(servers) command = servers[0].search }) it('Should not find a remote video', async function () { { const search = servers[1].url + '/videos/watch/43' const body = await command.searchVideos({ search, token: servers[0].accessToken }) expect(body.total).to.equal(0) expect(body.data).to.be.an('array') expect(body.data).to.have.lengthOf(0) } { // Without token const search = servers[1].url + '/videos/watch/' + videoServer2UUID const body = await command.searchVideos({ search }) expect(body.total).to.equal(0) expect(body.data).to.be.an('array') expect(body.data).to.have.lengthOf(0) } }) it('Should search a local video', async function () { const search = servers[0].url + '/videos/watch/' + videoServer1UUID const body = await command.searchVideos({ search }) expect(body.total).to.equal(1) expect(body.data).to.be.an('array') expect(body.data).to.have.lengthOf(1) expect(body.data[0].name).to.equal('video 1 on server 1') }) it('Should search a local video with an alternative URL', async function () { const search = servers[0].url + '/w/' + videoServer1UUID const body1 = await command.searchVideos({ search }) const body2 = await command.searchVideos({ search, token: servers[0].accessToken }) for (const body of [ body1, body2 ]) { expect(body.total).to.equal(1) expect(body.data).to.be.an('array') expect(body.data).to.have.lengthOf(1) expect(body.data[0].name).to.equal('video 1 on server 1') } }) it('Should search a local video with a query in URL', async function () { const searches = [ servers[0].url + '/w/' + videoServer1UUID, servers[0].url + '/videos/watch/' + videoServer1UUID ] for (const search of searches) { for (const token of [ undefined, servers[0].accessToken ]) { const body = await command.searchVideos({ search: search + '?startTime=4', token }) expect(body.total).to.equal(1) expect(body.data).to.be.an('array') expect(body.data).to.have.lengthOf(1) expect(body.data[0].name).to.equal('video 1 on server 1') } } }) it('Should search a remote video', async function () { const searches = [ servers[1].url + '/w/' + videoServer2UUID, servers[1].url + '/videos/watch/' + videoServer2UUID ] for (const search of searches) { const body = await command.searchVideos({ search, token: servers[0].accessToken }) expect(body.total).to.equal(1) expect(body.data).to.be.an('array') expect(body.data).to.have.lengthOf(1) expect(body.data[0].name).to.equal('video 1 on server 2') } }) it('Should not list this remote video', async function () { const { total, data } = await servers[0].videos.list() expect(total).to.equal(1) expect(data).to.have.lengthOf(1) expect(data[0].name).to.equal('video 1 on server 1') }) it('Should update video of server 2, and refresh it on server 1', async function () { this.timeout(120000) const channelAttributes = { name: 'super_channel', displayName: 'super channel' } const created = await servers[1].channels.create({ attributes: channelAttributes }) const videoChannelId = created.id const attributes = { name: 'updated', tag: [ 'tag1', 'tag2' ], privacy: VideoPrivacy.UNLISTED, channelId: videoChannelId } await servers[1].videos.update({ id: videoServer2UUID, attributes }) await waitJobs(servers) // Expire video await wait(10000) // Will run refresh async const search = servers[1].url + '/videos/watch/' + videoServer2UUID await command.searchVideos({ search, token: servers[0].accessToken }) // Wait refresh await wait(5000) const body = await command.searchVideos({ search, token: servers[0].accessToken }) expect(body.total).to.equal(1) expect(body.data).to.have.lengthOf(1) const video = body.data[0] expect(video.name).to.equal('updated') expect(video.channel.name).to.equal('super_channel') expect(video.privacy.id).to.equal(VideoPrivacy.UNLISTED) }) it('Should delete video of server 2, and delete it on server 1', async function () { this.timeout(120000) await servers[1].videos.remove({ id: videoServer2UUID }) await waitJobs(servers) // Expire video await wait(10000) // Will run refresh async const search = servers[1].url + '/videos/watch/' + videoServer2UUID await command.searchVideos({ search, token: servers[0].accessToken }) // Wait refresh await wait(5000) const body = await command.searchVideos({ search, token: servers[0].accessToken }) expect(body.total).to.equal(0) expect(body.data).to.have.lengthOf(0) }) after(async function () { await cleanupTests(servers) }) })
<?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; use Illuminate\Database\Eloquent\ModelNotFoundException; class userController extends Controller { // public function index() { $users = User::all(); if ($users->count() > 0) { return response()->json([ 'status' => 200, 'users' => $users ], 200); } else { return response()->json([ 'status' => 404, 'message' => 'No user found' ], 404); } } public function getUserById($id) { $user = User::find($id); if ($user) { return response()->json([ 'status' => 200, 'users' => $user ], 200); } else { return response()->json([ 'status' => 404, 'message' => 'User not found' ], 404); } } // public function phone_auth public function register(Request $request) { // Validate input based on email or phone presence $validator = Validator::make($request->all(), [ 'first_name' => 'required|max:191', 'last_name' => 'required|max:191', 'email' => 'required_without:phone|email|unique:users,email|max:191', 'phone' => 'required_without:email|nullable|regex:/^\+855[0-9]{8,9}$/|unique:users,phone', 'address' => 'nullable|max:191', 'password' => [ 'required', 'string', 'min:10', // must be at least 10 characters in length 'regex:/[a-z]/', // must contain at least one lowercase letter 'regex:/[A-Z]/', // must contain at least one uppercase letter 'regex:/[0-9]/', // must contain at least one digit 'regex:/[@$!%*#?&]/', // must contain a special character ], ]); if ($validator->fails()) { return response()->json([ 'status' => 422, 'errors' => $validator->messages() ], 422); } else { $user = User::create([ 'first_name' => $request->first_name, 'last_name' => $request->last_name, 'phone' => $request->phone, 'email' => $request->email, 'address' => $request->address, 'password' => Hash::make($request->password), ]); if ($user) { return response()->json([ 'status' => 200, 'message' => 'User created successfully', 'users' => $user ], 200); } else { return response()->json([ 'status' => 500, 'message' => 'Something went wrong' ], 500); } } } public function login(Request $request) { // Validate incoming request data $validator = Validator::make($request->all(), [ 'identity' => 'required', 'password' => 'required|string', ]); // If validation fails, return errors if ($validator->fails()) { return response()->json([ 'success' => false, 'status' => 422, 'message' => 'Validation failed', 'errors' => $validator->errors(), ], 422); } // Attempt to find the user by phone or email $user = User::where(function ($query) use ($request) { $query->where('phone', $request->identity) ->orWhere('email', $request->identity); })->first(); // If user not found, return error response if (!$user) { return response()->json([ 'success' => false, 'status' => 401, 'message' => 'User not found!', ], 401); } // If password does not match, return error response if (!Hash::check($request->password, $user->password)) { return response()->json([ 'success' => false, 'status' => 401, 'message' => 'Wrong Password!', ], 401); } // Generate a token for the user $token = Str::random(60); // Update the user's token $user->update(['api_token' => $token]); // Unset password from the user object unset($user->password); // Check user's role and return response accordingly if ($user->role_id === 1) { // If user role is 1, it's an admin return response()->json([ 'success' => true, 'status' => 200, 'message' => 'Admin authenticated successfully', 'users' => $user, 'token' => $token, ], 200); } elseif ($user->role_id === 2) { // If user role is 2, it's a regular user return response()->json([ 'success' => true, 'status' => 200, 'message' => 'User authenticated successfully', 'user' => $user, 'token' => $token, ], 200); } else { // Handle other roles if needed return response()->json([ 'success' => false, 'status' => 403, 'message' => 'Unauthorized role!', ], 403); } } public function update(Request $request, $id) { $validator = Validator::make($request->all(), [ 'first_name' => 'required|max:191', 'last_name' => 'required|max:191', 'phone' => 'regex:/^\+855[0-9]{8,9}$/', 'address' => 'required|max:191', ]); if ($validator->fails()) { return response()->json([ 'status' => 422, 'errors' => $validator->messages() ], 422); } else { $user = User::find($id); if (!$user) { return response()->json([ 'status' => 404, 'message' => 'User not found' ], 404); } $user->update([ 'first_name' => $request->first_name, 'last_name' => $request->last_name, 'phone' => $request->phone, 'address' => $request->address, ]); return response()->json([ 'status' => 200, 'message' => 'User updated successfully', 'users' => $user ], 200); } } public function destroy($id) { $user = User::find($id); if ($user) { $user->delete(); return response()->json([ 'status' => 200, 'message' => 'User deleted successfully' ], 200); } else { return response()->json([ 'status' => 404, 'message' => 'User not found' ], 404); } } public function verified($id) { // Attempt to find the user by ID $user = User::find($id); if (!$user) { // If user with the specified ID is not found, return a 404 response return response()->json([ 'status' => 404, 'message' => 'User not found' ], 404); } try { // Update the user's 'is_verified' field to 1 $user->is_verified = 1; $user->save(); // Return a success response with updated user details return response()->json([ 'status' => 200, 'message' => 'User verified successfully', 'user' => $user ], 200); } catch (\Exception $e) { // If an unexpected error occurs during the update process, return a 500 response return response()->json([ 'status' => 500, 'message' => 'Failed to verify user. Please try again later.' ], 500); } } public function as_admin($id) { // Attempt to find the user by ID $user = User::find($id); if (!$user) { // If user with the specified ID is not found, return a 404 response return response()->json([ 'status' => 404, 'message' => 'User not found' ], 404); } try { // Update the user's 'is_verified' field to 1 $user->role_id = 1; $user->save(); // Return a success response with updated user details return response()->json([ 'status' => 200, 'message' => 'User verified successfully', 'user' => $user ], 200); } catch (\Exception $e) { // If an unexpected error occurs during the update process, return a 500 response return response()->json([ 'status' => 500, 'message' => 'Failed to verify user. Please try again later.' ], 500); } } }
import numpy as np from typing import Tuple, Dict, Callable from qdax.types import Descriptor def get_body_descriptor_extractor(config: Dict) -> Tuple[Callable[[np.ndarray], Descriptor], int]: body_descriptors = config["body_descriptors"] if not isinstance(body_descriptors, list): body_descriptors = [body_descriptors] def _descriptor_extractor(body: np.ndarray) -> Descriptor: descriptor = [] if "n_voxels" in body_descriptors: descriptor.append(n_voxels(body)) if "relative_size" in body_descriptors: descriptor.append(relative_size(body)) if "width" in body_descriptors or "height" in body_descriptors: width, height = width_height(body) if "width" in body_descriptors: descriptor.append(width) if "height" in body_descriptors: descriptor.append(height) if "relative_width" in body_descriptors or "relative_height" in body_descriptors: relative_width, relative_height = relative_width_height(body) if "relative_width" in body_descriptors: descriptor.append(relative_width) if "relative_height" in body_descriptors: descriptor.append(relative_height) if "n_active_voxels" in body_descriptors: descriptor.append(n_active_voxels(body)) if "relative_activity" in body_descriptors: descriptor.append(relative_activity(body)) if "elongation" in body_descriptors: descriptor.append(elongation(body)) if "compactness" in body_descriptors: descriptor.append(compactness(body)) return np.array(descriptor) return _descriptor_extractor, len(body_descriptors) def _bounding_box_limits(body: np.ndarray) -> Tuple[int, int, int, int]: rows = np.any(body, axis=1) cols = np.any(body, axis=0) ys = np.where(rows)[0] xs = np.where(cols)[0] y_min, y_max = (0, 0) if len(ys) == 0 else ys[[0, -1]] x_min, x_max = (0, 0) if len(xs) == 0 else xs[[0, -1]] return x_min, x_max, y_min, y_max def n_voxels(body: np.ndarray) -> int: return (body > 0).sum() def n_active_voxels(body: np.ndarray) -> int: return (body >= 3).sum() def relative_activity(body: np.ndarray) -> float: return n_active_voxels(body) / n_voxels(body) def relative_size(body: np.ndarray) -> float: return n_voxels(body) / (body.shape[0] * body.shape[1]) def width_height(body: np.ndarray) -> Tuple[int, int]: x_min, x_max, y_min, y_max = _bounding_box_limits(body) return x_max - x_min + 1, y_max - y_min + 1 def relative_width_height(body: np.ndarray) -> Tuple[float, float]: width, height = width_height(body) return width / body.shape[0], height / body.shape[1] def elongation(body: np.ndarray, n_directions: int = 20) -> float: if n_directions <= 0: raise ValueError("n_directions must be positive") diameters = [] coordinates = np.where(body.transpose() > 0) x_coordinates = coordinates[0] y_coordinates = coordinates[1] if len(x_coordinates) == 0 or len(y_coordinates) == 0: return 0.0 for i in range(n_directions): theta = i * 2 * np.pi / n_directions rotated_x_coordinates = x_coordinates * np.cos(theta) - y_coordinates * np.sin(theta) rotated_y_coordinates = x_coordinates * np.sin(theta) + y_coordinates * np.cos(theta) x_side = np.max(rotated_x_coordinates) - np.min(rotated_x_coordinates) + 1 y_side = np.max(rotated_y_coordinates) - np.min(rotated_y_coordinates) + 1 diameter = min(x_side, y_side) / max(x_side, y_side) diameters.append(diameter) return 1 - min(diameters) def compactness(body: np.ndarray) -> float: convex_hull = body > 0 if True not in convex_hull: return 0.0 new_found = True while new_found: new_found = False false_coordinates = np.argwhere(convex_hull == False) for coordinate in false_coordinates: x, y = coordinate[0], coordinate[1] adjacent_count = 0 adjacent_coordinates = [] for d in [-1, 1]: adjacent_coordinates.append((x, y + d)) adjacent_coordinates.append((x + d, y)) adjacent_coordinates.append((x + d, y + d)) adjacent_coordinates.append((x + d, y - d)) for adj_x, adj_y in adjacent_coordinates: if 0 <= adj_x < body.shape[0] and 0 <= adj_y < body.shape[1] and convex_hull[adj_x][adj_y]: adjacent_count += 1 if adjacent_count >= 5: convex_hull[x][y] = True new_found = True return (body > 0).sum() / convex_hull.sum()
package com.example.playquest; import com.example.playquest.controllers.Home; import com.example.playquest.entities.Ads; import com.example.playquest.entities.PostContent; import com.example.playquest.entities.User; import com.example.playquest.repositories.AdsRepository; import com.example.playquest.repositories.PostContentRepository; import com.example.playquest.repositories.UsersRepository; import com.example.playquest.services.SessionManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.*; import org.springframework.ui.Model; import jakarta.servlet.http.HttpServletRequest; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; public class HomeTest { @InjectMocks private Home homeController; @Mock private SessionManager sessionManager; @Mock private UsersRepository usersRepository; @Mock private PostContentRepository postContentRepository; @Mock private AdsRepository adsRepository; @Mock private Model model; @Mock private HttpServletRequest request; private static final Long USER_ID = 1L; @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); } @Test public void indexWhenUserNotLoggedIn() { when(sessionManager.isUserLoggedIn(request)).thenReturn(false); String result = homeController.Index(model, request); assertEquals("redirect:/login", result); } @Test public void indexWhenUserLoggedIn() { // setup when(sessionManager.isUserLoggedIn(request)).thenReturn(true); when(sessionManager.getUserId(request)).thenReturn(USER_ID); User user = new User(); when(usersRepository.findById(USER_ID)).thenReturn(Optional.of(user)); List<User> users = List.of(new User(), new User()); when(usersRepository.findAll()).thenReturn(users); List<PostContent> postContents = List.of(new PostContent(), new PostContent()); when(postContentRepository.findAllByOrderByCreatedOnDesc()).thenReturn(postContents); List<Ads> ads = List.of(new Ads(), new Ads(), new Ads()); when(adsRepository.findTop3ByOrderByCreatedOnDesc()).thenReturn(ads); // action String result = homeController.Index(model, request); // verify assertEquals("index", result); verify(model).addAttribute("user", user); verify(model).addAttribute("allUsers", users); verify(model).addAttribute("postContents", postContents); } }
// Funciones de flecha (function(){ let miFuncion = function(data: string){ return data.toUpperCase(); } let miFuncionFlecha = (data: string) => data.toUpperCase(); let sumarNormal = function(num1: number, num2: number){ return num1 + num2; } let sumarFlecha = (num1: number, num2: number) => num1 + num2; console.log(miFuncion("Normal")); console.log(miFuncionFlecha("Flecha")); console.log(sumarNormal(2, 4)); console.log(sumarFlecha(6, 8)); window.nombre = 'Iron Man'; let nombre = 'Demos'; let hulk = { nombre: 'Hulk', smash(){ setTimeout(function() { // con la funcion tradicional se hace referencia a la variable del objeto window console.log(`${this.nombre} smash!!!!!`); // con la funcion tradicional se hace referencia a la variable global console.log(`${nombre} smash!!!!!`); }, 1000) }, smashFlecha(){ setTimeout(() => { // con la funcion de flecha si se hace referencia al objeto console.log(`${this.nombre} smash!!!!!`); }, 1000) } } hulk.smash(); hulk.smashFlecha(); })();
/* * 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.github.halab4dev; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Month; import java.util.Calendar; import java.util.Date; import org.bson.Document; import org.bson.types.ObjectId; /** * * @author halab */ public class Application { private static final String COLLECTION_NAME = "example"; public static void main(String[] args) { System.out.println("Connecting to database ..."); String mongodbUri = System.getenv("MONGO_URI"); String dbName = System.getenv("MONGO_DATABASE"); MongoClient client = MongoClients.create(mongodbUri); MongoCollection<Document> collection = client.getDatabase(dbName).getCollection(COLLECTION_NAME); System.out.println("Inserting data ..."); String id = insertData(collection); System.out.println("Querying data ..."); getData(collection, id); } public static String insertData(MongoCollection<Document> collection) { collection.drop(); Document doc = new Document("name", "Docker example") .append("description", "Docker compose example, include mongodb and a java application") .append("created_date", LocalDateTime.of(2024, Month.JANUARY, 1, 23, 5, 0)) .append("last_run_time", LocalDateTime.now()); collection.insertOne(doc); return doc.getObjectId("_id").toString(); } public static void getData(MongoCollection<Document> collection, String id) { Document query = new Document("_id", new ObjectId(id)); Document data = collection.find(query).first(); System.out.println("===== Application information ====="); System.out.println("Name: " + data.getString("name")); System.out.println("Description: " + data.getString("description")); System.out.println("Created date: " + data.getDate("created_date")); System.out.println("Last run time: " + data.getDate("last_run_time")); } }
import { getServerSession, type DefaultSession, type NextAuthOptions, } from "next-auth"; /** * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session` * object and keep type safety. * * @see https://next-auth.js.org/getting-started/typescript#module-augmentation */ declare module "next-auth" { interface Session extends DefaultSession { user: { id: string; // ...other properties // role: UserRole; } & DefaultSession["user"]; } // interface User { // // ...other properties // // role: UserRole; // } } /** * Options for NextAuth.js used to configure adapters, providers, callbacks, etc. * * @see https://next-auth.js.org/configuration/options */ export const authOptions: NextAuthOptions = { callbacks: { session: ({ session, user }) => ({ ...session, user: { ...session.user, id: user.id, }, }), }, // adapter: DrizzleAdapter(db, mysqlTable), providers: [], }; /** * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file. * * @see https://next-auth.js.org/configuration/nextjs */ export const getServerAuthSession = () => getServerSession(authOptions);
pragma solidity >=0.5.0 <0.7.0; contract SimpleCoin { address public minter; mapping (address => uint) public balances; event Sent(address from, address to, uint amount); constructor() public { minter = msg.sender; } function mint(address receiver, uint amount) public { require(msg.sender == minter); require(amount < 1600); balances[receiver] += amount } function send(address received, uint amount) public { require(amount <= balances[msg.sender], "Insufficient Balance"); balances[msg.sender] -= amount; balances[msg.sender] += amount; emit Sent(msg.sender, receiver, amount); } function balances(address _account) external view returns (uint) { return balances[_account]; } }
# Argo CD Self-Healing Capabilities ⏱️ _Estimated Time: 5 Minutes_ 👩‍💻 _Role: Cluster Administrator and/or Developers_ Argo CD is capable healing resources when it detects configuration drift. For example, when a resource that should be present is missing it will be recreated by Argo CD. Another example is when a field such as `spec.replicas` on a Deployment has a value mismatch between what's stored in the Git repository and the actual value set on the resource in the cluster. If your Argo CD Application has the `selfHeal` property set to `true` then it will automatically detect and correct configuration drift for the resources it is managing. That means if someone accidentally runs a `kubectl` command against the wrong resource Argo CD will have your back and will restore the resource to the correct configuration! == Observing Argo CD Self-Healing You currently have a Console Notification being managed by Argo CD. The `selfHeal: true` configuration is defined on the Application CR responsible for managing it. Go ahead an see what happens when you edit/delete the Console Notification resource using the `oc` or `kubectl` CLI: . Login to the OpenShift Web Console as the `opentlc-mgr` user. . Open the OpenShift Web Terminal using the *>_* icon. . Run the following command to list existing Console Notification resources: + [.console-input] [source,bash] ---- oc get consolenotification ---- . Run the following command to delete the `welcome-banner` Console Notification: + [.console-input] [source,bash] ---- oc delete consolenotification welcome-banner ---- . Depending on your timing the Console Notification will briefly disappear, and then immediately reappear. + [NOTE] ==== The reason that the Console Notification reappears is because the *console-customisations* Application in Argo CD has the `selfHeal` property set to `true`. ==== . List existing Console Notification resources again, and pay attention to the *AGE* column: + [.console-input] [source,bash] ---- oc get consolenotification ---- Did you notice that the age of the Console Notification has changed? image::ex5.banner-ages.png[] When you deleted the Console Notification it was automatically recreated by Argo CD. This is reflected through the new value displayed in the *AGE* column. == Toggling the Self-Healing Behaviour It's possible to toggle the self-healing behaviour at any time, so long as you have the necessary permissions and access to the Argo CD dashboard/resources: . Open the Argo CD dashboard and log in as the `admin` user. If you've lost the password, you can return to the *Accessing the Cluster GitOps Dashboard* section to obtain it. . Select the *console-customisations* Application. . Click the *App Details* button in the header. An overlay will appear. . Scroll down and click the *Disable* button next to *Self Heal*. Click the *OK* button when asked to confirm the change. + image::ex5-argocd-disable-healing.png[] . Click the *X* icon in the top-right to close the modal window. . Return to the OpenShift Web Console, and open the OpenShift Web Terminal. . Return to the Web Terminal and run the following command to delete the ConsoleNotification: + [.console-input] [source,bash] ---- oc delete consolenotification welcome-banner ---- The ConsoleNotification will disappear, and won't reappear this time. The Argo CD dashboard should be reporting that the *console-customisations* Application is "OutOfSync". Use the *Sync* button to manually synchronise the Application and restore the banner. Consider re-enabling the self-healing configuration for peace of mind!
import { FormControl, FormLabel, Input, Button, Text, Box, Spinner, FormErrorMessage, Switch, Flex, } from '@chakra-ui/react'; import Breadcrumbs from 'components/breadcrumb'; import DatePicker from 'components/date-picker'; import { Error } from 'components/error'; import { FormWrapper } from 'components/form-wrapper'; import { NumberInput } from 'components/number-input'; import { SelectInput } from 'components/select-input'; import { AsyncSelect } from 'components/async-select'; import { TextInput } from 'components/text-input'; import AppLayout from 'layout/app-layout'; import { FormikHelpers, useFormik } from 'formik'; import { useRouter } from 'next/router'; import { FunctionComponent, useState } from 'react'; import * as yup from 'yup'; import { AccessOperationEnum, AccessServiceEnum, requireNextAuth, withAuthorization } from '@roq/nextjs'; import { compose } from 'lib/compose'; import { createConference } from 'apiSdk/conferences'; import { conferenceValidationSchema } from 'validationSchema/conferences'; import { OrganizationInterface } from 'interfaces/organization'; import { getOrganizations } from 'apiSdk/organizations'; import { ConferenceInterface } from 'interfaces/conference'; function ConferenceCreatePage() { const router = useRouter(); const [error, setError] = useState(null); const handleSubmit = async (values: ConferenceInterface, { resetForm }: FormikHelpers<any>) => { setError(null); try { await createConference(values); resetForm(); router.push('/conferences'); } catch (error) { setError(error); } }; const formik = useFormik<ConferenceInterface>({ initialValues: { title: '', start_time: new Date(new Date().toDateString()), end_time: new Date(new Date().toDateString()), organization_id: (router.query.organization_id as string) ?? null, }, validationSchema: conferenceValidationSchema, onSubmit: handleSubmit, enableReinitialize: true, validateOnChange: false, validateOnBlur: false, }); return ( <AppLayout breadcrumbs={ <Breadcrumbs items={[ { label: 'Conferences', link: '/conferences', }, { label: 'Create Conference', isCurrent: true, }, ]} /> } > <Box rounded="md"> <Box mb={4}> <Text as="h1" fontSize={{ base: '1.5rem', md: '1.875rem' }} fontWeight="bold" color="base.content"> Create Conference </Text> </Box> {error && ( <Box mb={4}> <Error error={error} /> </Box> )} <FormWrapper onSubmit={formik.handleSubmit}> <TextInput error={formik.errors.title} label={'Title'} props={{ name: 'title', placeholder: 'Title', value: formik.values?.title, onChange: formik.handleChange, }} /> <FormControl id="start_time" mb="4"> <FormLabel fontSize="1rem" fontWeight={600}> Start Time </FormLabel> <DatePicker selected={formik.values?.start_time ? new Date(formik.values?.start_time) : null} onChange={(value: Date) => formik.setFieldValue('start_time', value)} /> </FormControl> <FormControl id="end_time" mb="4"> <FormLabel fontSize="1rem" fontWeight={600}> End Time </FormLabel> <DatePicker selected={formik.values?.end_time ? new Date(formik.values?.end_time) : null} onChange={(value: Date) => formik.setFieldValue('end_time', value)} /> </FormControl> <AsyncSelect<OrganizationInterface> formik={formik} name={'organization_id'} label={'Select Organization'} placeholder={'Select Organization'} fetcher={getOrganizations} labelField={'name'} /> <Flex justifyContent={'flex-start'}> <Button isDisabled={formik?.isSubmitting} bg="state.info.main" color="base.100" type="submit" display="flex" height="2.5rem" padding="0rem 1rem" justifyContent="center" alignItems="center" gap="0.5rem" mr="4" _hover={{ bg: 'state.info.main', color: 'base.100', }} > Submit </Button> <Button bg="neutral.transparent" color="neutral.main" type="button" display="flex" height="2.5rem" padding="0rem 1rem" justifyContent="center" alignItems="center" gap="0.5rem" mr="4" onClick={() => router.push('/conferences')} _hover={{ bg: 'neutral.transparent', color: 'neutral.main', }} > Cancel </Button> </Flex> </FormWrapper> </Box> </AppLayout> ); } export default compose( requireNextAuth({ redirectTo: '/', }), withAuthorization({ service: AccessServiceEnum.PROJECT, entity: 'conference', operation: AccessOperationEnum.CREATE, }), )(ConferenceCreatePage);
import { OutputPlugin } from "rollup"; import { basename, dirname, isAbsolute } from "path"; import { pathToName } from "../core/ref"; const empty: [string, string] = ["hidden", ""]; function nameOf(id: string): [string, string] { const name = pathToName(id); if (name[0] === "\0") { return empty; } let prefix = "src "; let dir = dirname(name); if (dir.startsWith("npm:")) { prefix = "npm " dir = dir.substring(4); } if (dir.startsWith("ws:")) { prefix = "workspace "; dir = dir.substring(3); } if (isAbsolute(name)) { prefix = "system "; } return [prefix + dir, basename(name)]; } function emitGroup(dir: string, group: string[]) { console.info(" %s", dir, group.length); } function chunkLogger(): OutputPlugin { return { name: "chunk-logger", writeBundle(_, bundle) { for (const fn in bundle) { const chunk = bundle[fn]; if (chunk && chunk.type === "chunk") { const modules = Object.keys(chunk.modules); const size = Buffer.byteLength(chunk.code); console.info("chunk:", fn, size, modules.length); let dir = ""; const group: string[] = []; for (const id of modules.sort()) { const [key, name] = nameOf(id); if (dir !== key) { dir && emitGroup(dir, group); dir = key; group.length = 0; } group.push(name || id); } dir && emitGroup(dir, group); } } }, }; } export default chunkLogger;
<template> <div class="newCourse"> <form @submit.prevent="submit"> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Название курса</label> <input :title="props.title" v-model="title" type="title" class="form-control" id="exampleFormControlInput1" placeholder="Название курса"> </div> <div class="mb-3"> <label for="exampleFormControlTextarea1" class="form-label">Описание курса</label> <textarea :description="props.description" v-model="description" class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary" style="background-color: #59c680; border: #59c680;">Создать</button> </form> </div> </template> <script setup> import router from '../router'; import { useMainStore } from '../store/mainStore'; import TeacherAPI from '../services/TeacherAPI' const store = useMainStore() var token = 'Bearer ' + store.takeToken let title = "" let description = "" var id = store.takeID const props = defineProps({ title: { type: [String] }, description: { type: [String] }, }) function submit() { var cours = { "title": title, "description": description, "creator": id, "teachers": [id] } debugger TeacherAPI.createCourse(cours, token) .then( () => { router.replace({ name: 'mycourses' }) }) .catch(err => { console.log(err) }) } const emit = defineEmits(['submit']) </script> <style scoped> .newCourse { max-width: 1100px; margin: auto; background-color: #d5d6d1; } </style>
<template> <FontAwesomeIcon icon="plus" class="add-button" @click="router.push(route.fullPath + '&type=register')" /> <div class="filter-area"> <button v-for="(item, index) in tab" :key="index" :class="currentStatus == item ? 'active' : ''" @click="getModelList(currentPage, item)" > {{ item }} </button> </div> <BaseTable v-if="list.length > 0"> <template #thead> <tr> <th v-for="(th, index) in ths" :key="index"> {{ th }} </th> </tr> </template> <template #tbody> <tr v-for="(item, index) in list" :key="index"> <!-- <td> {{ index + 1 + 10 * (currentPage - 1) }} </td> --> <td>{{ item.modelName }}</td> <td>{{ item.projectName }}</td> <td>{{ item.imageName }}</td> <td> {{ item.tag }} </td> <td class="control" v-if="item.reg"> <FontAwesomeIcon icon="circle-info" class="info-button" @click=" router.push( route.fullPath + `&type=settings&modelId=${item.modelId}` ) " /> <FontAwesomeIcon icon="trash" class="remove-button" @click="remove(item.modelId)" /> </td> <td class="control" v-else>진행중</td> </tr> </template> </BaseTable> <Pagination v-if="list.length > 0" class="pagination" :total-items="totalPages" :show-icons="true" :showLabels="false" :slice-length="4" v-model="currentPage" @update:model-value=" (currentPage) => { getModelList(currentPage, currentStatus); } " ></Pagination> </template> <script setup lang="ts"> import { inject, ref, computed, onActivated, onDeactivated } from "vue"; import { useRoute, useRouter } from "vue-router"; import { EventType, Emitter } from "mitt"; import serviceAPI from "@api/services"; import { Pagination } from "flowbite-vue"; import { AxiosInstance } from "axios"; import { getModelList } from "./model"; const tab = <const>["ALL"]; const activeTab = ref<(typeof tab)[number] | null>(null); const emitter = inject("emitter") as Emitter< Record< EventType, { isActive?: boolean; isLoading?: boolean; isActiveCloseButton?: boolean; closeText?: string; message?: string; fn?: () => void; } > >; const ths = <const>["Name", "Project", "Image", "Tag", ""]; const router = useRouter(); const route = useRoute(); const routeCurrentPage = computed<number>(() => { return route.query.currentPage == undefined ? 1 : Number(route.query.currentPage); }); const currentStatus = computed<(typeof tab)[number]>(() => { const status = route.query.currentStatus as (typeof tab)[number]; const getIndex = tab.indexOf(status); return getIndex == -1 ? "ALL" : status; }); const defaultInstance = inject("defaultInstance") as AxiosInstance; const remove = (modelId: string) => { emitter.emit("update:alert", { isActive: true, message: "삭제하시겠습니까?", isActiveCloseButton: true, closeText: "close", fn: () => { emitter.emit("update:loading", { isLoading: true }); defaultInstance .delete(serviceAPI.modelInfo + `?modelId=${modelId}`) .then((result) => { console.log(result); emitter.emit("update:loading", { isLoading: false }); getModelList(1, "ALL"); }); }, }); }; const { list, totalPages, currentPage } = getModelList( routeCurrentPage.value, currentStatus.value ); // 모델 리스트 조회 // const getModelList = (page: number, status: (typeof tab)[number]) => { // console.log(`output-> page,status`, page, status); // defaultInstance // .get<ModelListResType>( // serviceAPI.modelList + // `?page=${ // page - 1 // }&size=10&sort=desc&status=${status.toLocaleLowerCase()}` // ) // .then((result) => { // console.log(result); // modelList.value = result.data.content; // totalPages.value = result.data.totalPages; // router.push({ // query: { // ...route.query, // currentPage: page, // currentStatus: status, // }, // }); // }); // }; onActivated(() => { console.log("모델리스트 활성화"); // connectSSE(); // if (activeTab.value !== null) { // router.push({ // query: { // mainCategory: "modelManage", // subCategory: "modelStatus", // currentPage: currentPage.value, // currentStatus: activeTab.value, // }, // }); // } }); onDeactivated(() => { console.log("모델리스트 비활성화"); // if (sseEvents.value !== null) { // sseEvents.value.close(); // } // activeTab.value = currentStatus.value; }); </script> <style scoped lang="scss"> .add-button { position: fixed; bottom: 50px; right: 0px; color: white; z-index: 1; cursor: pointer; background: #0095ff; border-radius: 50px; width: 40px; height: 40px; padding: 10px; } .pagination { :deep(.inline-flex) { display: flex; width: 100%; justify-content: space-around; button { height: 30px; font-size: 30px; &:not(.cursor-not-allowed) { &:disabled { color: #686de0; } } } } } .filter-area { display: flex; column-gap: 20px; margin: 20px 0 20px 20px; button { padding-bottom: 6px; color: #ccc; &.active { color: black; border-bottom: 2px solid #0095ff; } } } .table-box { height: calc(100% - 126px); margin-bottom: 20px; border-bottom: 1px solid rgba(145, 158, 171, 0.24); thead { tr { th { &:last-child { width: 7%; } } } } tbody { tr { td { &:last-child { width: 7%; } } } .control { .remove-button { color: #ff4343; } .info-button { margin-right: 10px; } } } } </style>
/* * Copyright (C) 2023 Rajesh Hadiya * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.collapsablecardview import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.collapsablecardview.databinding.ItemProductBinding import com.example.collapsablecardview.databinding.PumpItemEntryBinding class ChildRecyclerViewAdapter(private val childList: List<ChildItem>) : RecyclerView.Adapter<ChildRecyclerViewAdapter.ChildProductViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChildProductViewHolder { /*val view = LayoutInflater.from(parent.context).inflate(R.layout.pump_item_entry, parent, false) return ProfileViewHolder(view)*/ return ChildProductViewHolder( ItemProductBinding.inflate(LayoutInflater.from(parent.context), parent, false) ) } override fun onBindViewHolder(holder: ChildProductViewHolder, position: Int) { val childItem = childList[position] holder.bind(childItem) } override fun getItemCount(): Int = childList?.size?:0 inner class ChildProductViewHolder(private val binding: ItemProductBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: ChildItem) { binding.apply { childLogoIV.setImageResource(R.drawable.ic_user) childTitleTv.text = item.name /*parentTitleTv.text = item.title //parentLogoIv.setImageResource(R.drawable.ic_user) childRecyclerView.setHasFixedSize(true) childRecyclerView.layoutManager = GridLayoutManager(this.root.context, 3) */ executePendingBindings() } } } }
import React from 'react'; import { Route } from 'react-router-dom'; import Menu from './components/Menu'; import loadable from '@loadable/component'; const BluePage = loadable(() => import('./pages/BluePage')); const RedPage = loadable(() => import('./pages/RedPage')); const UsersPage = loadable(() => import('./pages/UsersPage')); const App = () => { return ( <div> <Menu></Menu> <hr /> <Route path="/red" component={RedPage} /> <Route path="/blue" component={BluePage} /> <Route path="/users" component={UsersPage} /> </div> ); }; export default App;
import React from 'react' import { useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Link, Outlet } from 'react-router-dom'; import {BiMenu, BiHome} from "react-icons/bi" import {IoMdAdd} from "react-icons/io" import {FiUsers} from "react-icons/fi" import {AiOutlineBarChart} from "react-icons/ai" import styles from "./styles/Sidebar.css" function SidebarComponent() { const dispatch = useDispatch() const [sidebar, setSidebar] = useState("") const [active, setActive] = useState("products") const handleSidebar = () => { const openOrClose = sidebar === "open" ? "" : "open" setSidebar(openOrClose) return openOrClose } const handleActive = (e) => { const activeTab = e.currentTarget.name setActive(activeTab) } /* const handleTheme = () => { dispatch(changeTheme()) } const theme = useSelector(state => state?.theme) */ return ( <> <div className="mainSidebar bg-dark"> <aside className={`sidebar ${sidebar}`}> <div className="top-sidebar"> <Link to="/home" className="brand-logo"><img src="https://res.cloudinary.com/dkfqpw0yr/image/upload/v1667447252/v5fgeh3rn91atyfld8cv.png" alt="Brand"/></Link> <div className="hidden-sidebar welcome-message">Welcome, admin</div> </div> <div className="middle-sidebar"> <ul className="sidebar-list"> <li className='sidebar-list-item'> <button className='sidebar-link menu' onClick={handleSidebar}> <BiMenu className="sidebar-icon"/> <div className="hidden-sidebar"><span>Collapse Sidebar</span></div> <p className="hover">Collapse Sidebar</p> </button> </li> <li className={`sidebar-list-item ${active === "add" && "active"}`}> <Link to="/newProduct" className="sidebar-link" name="add" onClick={handleActive}> <IoMdAdd className="sidebar-icon"/> <div className="hidden-sidebar"><span>Add a New Product</span></div> <p className="hover">Add a New Product</p> </Link> </li> <li className={`sidebar-list-item ${active === "users" && "active"}`}> <Link to="/admin/users" className="sidebar-link" name="users" onClick={handleActive}> <FiUsers className="sidebar-icon"/> <div className="hidden-sidebar"><span>Users</span></div> <p className="hover">Users</p> </Link> </li> <li className={`sidebar-list-item ${active === "products" && "active"}`}> <Link to="/admin/products" className="sidebar-link" name="products" onClick={handleActive}> <AiOutlineBarChart className="sidebar-icon"/> <div className="hidden-sidebar"><span>Products</span></div> <p className="hover">Products</p> </Link> </li> </ul> </div> <div className="bottom-sidebar"> <ul className="sidebar-list"> <li className="sidebar-list-item"> {/* <div className="sidebar-link" onClick={handleTheme}> {theme === "dark" ? <MoonIcon className="sidebar-icon"/> : <SunIcon className="sidebar-icon"/>} <div className="hidden-sidebar"><p>Change Theme</p></div> <p className="hover">Change Theme</p> </div> */} </li> </ul> </div> </aside> </div> <section className='w-100'> <Outlet></Outlet> </section> </> ) } export default SidebarComponent
<template> <div class="map h100"> <div class="plantMap h100" id="allmap"></div> <add-dialog :showFlag="showFlag" :point="point" @close="closeAddDialog" @add="submitAdd"></add-dialog> </div> </template> <script> import Map from '@/class/map' import AddDialog from '@/components/addDialog' export default { name: 'addPlant', data() { return { map: null, point: null, marker: null, showFlag: false } }, components: { AddDialog }, mounted() { this.createMap() this.map.setMiniBounds() }, methods: { createMap() { let _this = this this.map = new Map('allmap') this.map.init() this.map.map.addEventListener('click', function(e) { _this.point = e.point if (!_this.marker) { _this.marker = new BMap.Marker(e.point, { title: '植物坐标', // TODO: 设置一个当前位置的图标 icon: '' }) _this.map.map.addOverlay(_this.marker) _this.marker.setAnimation(BMAP_ANIMATION_BOUNCE) } else { _this.marker.setPosition(e.point) } _this.showFlag = true _this.map.map.panTo(e.point) }) }, closeAddDialog(...data) { this.showFlag = data[0] }, submitAdd(info) { this.$store .dispatch('addPlant', info) .then(res => { this.$message({ type: 'success', message: '信息添加成功' }) }) .catch(err => { this.$message({ type: 'error', message: '信息添加失败' }) }) } } } </script> <style> </style>
/** * Copyright (c) 2012 Alvin S.J. Ng * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT * SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @author Alvin S.J. Ng <alvinsj.ng@gmail.com> * @copyright 2012 Alvin S.J. Ng * */ package com.stepsdk.android.http; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLDecoder; import android.app.AlertDialog; import android.content.DialogInterface.OnClickListener; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.util.Log; public class BlindHttpUploadTask extends AsyncTask<String, Integer, Boolean > { public static final String TAG = "UploadLocalFileTask"; private static final int MAX_BUFFER_SIZE = 1024; public static final int DOWNLOADING = 0; public static final int COMPLETE = 1; private ProgressDialog mProgressDialog; private Context mContext; private String mTargetUrl; public BlindHttpUploadTask( Context context, String targetUrl) { super(); mContext = context; mTargetUrl = targetUrl; } @Override protected Boolean doInBackground(String... pos) { String urlString = mTargetUrl; String filename; try { filename = URLDecoder.decode(pos[1], "UTF-8"); }catch(Exception e) { filename = pos[1]; } String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; try { HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); DataOutputStream dos = new DataOutputStream( conn.getOutputStream() ); OutputStreamWriter dosw = new OutputStreamWriter(dos); dosw.write(twoHyphens + boundary + lineEnd); dosw.write("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filename +"\"" + lineEnd); dosw.write(lineEnd); dosw.flush(); // create a buffer of maximum size String filepath; // handle special character try { filepath = URLDecoder.decode(pos[0], "UTF-8"); }catch(Exception e) { filepath = pos[0]; } InputStream fis = new FileInputStream(new File(filepath)); int bufferSize = Math.min(fis.available(), MAX_BUFFER_SIZE); double fileSize = fis.available(); double downloaded = 0; // read file and write it into form... byte[] buffer = new byte[bufferSize]; int bytesRead = fis.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bufferSize = Math.min(fis.available(), MAX_BUFFER_SIZE); bytesRead = fis.read(buffer, 0, bufferSize); downloaded += bytesRead; } dos.flush(); dosw.write(lineEnd); dosw.write(twoHyphens + boundary + twoHyphens + lineEnd); fis.close(); dosw.flush(); //dos.flush(); InputStream is = conn.getInputStream(); int ch; StringBuffer b =new StringBuffer(); while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); } dos.close(); //dosw.close(); publishProgress(100); return true; } catch (Exception e) { Log.e(TAG, e.getMessage()); return false; } } @Override protected void onPreExecute() { //mProgressDialog = QuickUI.dialogProgressHorizontal(mContext, mContext.getString(R.string.msg_upload_file), false); mProgressDialog.show(); } protected AlertDialog alertDialogforNotification(Context context, String title, String message, boolean cancelable) { AlertDialog.Builder dlgBuilder = new AlertDialog.Builder(context); dlgBuilder.setMessage(message).setCancelable(cancelable) .setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); return dlgBuilder.create(); } @Override protected void onPostExecute(Boolean result) { mProgressDialog.dismiss(); if(result){ AlertDialog alertDialog = alertDialogforNotification(mContext , "File uploaded" , "File uploaded" , false); alertDialog.setButton(0, "OK", new OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } else { AlertDialog alertDialog = alertDialogforNotification(mContext , "Error" , "File upload error" , false); alertDialog.show(); } } }
import AppError from '../../errors/AppError'; import { FakeVehicleRepository } from '../../repositories/fakes/FakeVehicleRepository'; import { ShowVehicleService } from '../ShowVehicleService'; let fakeVehicleRepository: FakeVehicleRepository; let showVehicleService: ShowVehicleService; describe('ShowVehicleService', () => { beforeEach(() => { fakeVehicleRepository = new FakeVehicleRepository(); showVehicleService = new ShowVehicleService(fakeVehicleRepository); }); it('should show the data of a vehicle', async () => { const vehicle = await fakeVehicleRepository.create({ ano: 1996, descricao: 'Fusca Itamar', marca: 'Volkswagen', veiculo: 'Fusca' }); const vehicleShow = await showVehicleService.execute({ id: vehicle.id }); expect(vehicleShow).toHaveProperty('id'); }); it('should not show the data of a non-existent vehicle', async () => { await expect( showVehicleService.execute({ id: 'vehicle_non_existent' }) ).rejects.toBeInstanceOf(AppError); }); });
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Moodle renderer used to display special elements of the lesson module * * @package mod_choice * @copyright 2010 Rossiani Wijaya * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later **/ define ('DISPLAY_HORIZONTAL_LAYOUT', 0); define ('DISPLAY_VERTICAL_LAYOUT', 1); class mod_choice_renderer extends plugin_renderer_base { /** * Returns HTML to display choices of option * @param object $options * @param int $coursemoduleid * @param bool $vertical * @return string */ public function display_options($options, $coursemoduleid, $vertical = false, $multiple = false) { $layoutclass = 'horizontal'; if ($vertical) { $layoutclass = 'vertical'; } $target = new moodle_url('/mod/choice/view.php'); $attributes = array('method'=>'POST', 'action'=>$target, 'class'=> $layoutclass); $disabled = empty($options['previewonly']) ? array() : array('disabled' => 'disabled'); $html = html_writer::start_tag('form', $attributes); $html .= html_writer::start_tag('ul', array('class' => 'choices list-unstyled unstyled')); $availableoption = count($options['options']); $choicecount = 0; foreach ($options['options'] as $option) { $choicecount++; $html .= html_writer::start_tag('li', array('class' => 'option mr-3')); if ($multiple) { $option->attributes->name = 'answer[]'; $option->attributes->type = 'checkbox'; } else { $option->attributes->name = 'answer'; $option->attributes->type = 'radio'; } $option->attributes->id = 'choice_'.$choicecount; $option->attributes->class = 'mx-1'; $labeltext = $option->text; if (!empty($option->attributes->disabled)) { $labeltext .= ' ' . get_string('full', 'choice'); $availableoption--; } if (!empty($options['limitanswers']) && !empty($options['showavailable'])) { $labeltext .= html_writer::empty_tag('br'); $labeltext .= get_string("responsesa", "choice", $option->countanswers); $labeltext .= html_writer::empty_tag('br'); $labeltext .= get_string("limita", "choice", $option->maxanswers); } $html .= html_writer::empty_tag('input', (array)$option->attributes + $disabled); $html .= html_writer::tag('label', $labeltext, array('for'=>$option->attributes->id)); $html .= html_writer::end_tag('li'); } $html .= html_writer::tag('li','', array('class'=>'clearfloat')); $html .= html_writer::end_tag('ul'); $html .= html_writer::tag('div', '', array('class'=>'clearfloat')); $html .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey())); $html .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'action', 'value'=>'makechoice')); $html .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id', 'value'=>$coursemoduleid)); if (empty($options['previewonly'])) { if (!empty($options['hascapability']) && ($options['hascapability'])) { if ($availableoption < 1) { $html .= html_writer::tag('label', get_string('choicefull', 'choice')); } else { $html .= html_writer::empty_tag('input', array( 'type' => 'submit', 'value' => get_string('savemychoice', 'choice'), 'class' => 'btn btn-primary' )); } if (!empty($options['allowupdate']) && ($options['allowupdate'])) { $url = new moodle_url('view.php', array('id' => $coursemoduleid, 'action' => 'delchoice', 'sesskey' => sesskey())); $html .= html_writer::link($url, get_string('removemychoice', 'choice'), array('class' => 'ml-1')); } } else { $html .= html_writer::tag('label', get_string('havetologin', 'choice')); } } $html .= html_writer::end_tag('ul'); $html .= html_writer::end_tag('form'); return $html; } /** * Returns HTML to display choices result * @param object $choices * @param bool $forcepublish * @return string */ public function display_result($choices, $forcepublish = false) { if (empty($forcepublish)) { //allow the publish setting to be overridden $forcepublish = $choices->publish; } $displaylayout = $choices->display; if ($forcepublish) { //CHOICE_PUBLISH_NAMES return $this->display_publish_name_vertical($choices); } else { return $this->display_publish_anonymous($choices, $displaylayout); } } /** * Returns HTML to display choices result * @param object $choices * @return string */ public function display_publish_name_vertical($choices) { $html =''; $html .= html_writer::tag('h3',format_string(get_string("responses", "choice"))); $attributes = array('method'=>'POST'); $attributes['action'] = new moodle_url($this->page->url); $attributes['id'] = 'attemptsform'; if ($choices->viewresponsecapability) { $html .= html_writer::start_tag('form', $attributes); $html .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id', 'value'=> $choices->coursemoduleid)); $html .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey())); $html .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode', 'value'=>'overview')); } $table = new html_table(); $table->cellpadding = 0; $table->cellspacing = 0; $table->attributes['class'] = 'results names table table-bordered'; $table->tablealign = 'center'; $table->summary = get_string('responsesto', 'choice', format_string($choices->name)); $table->data = array(); $count = 0; ksort($choices->options); $columns = array(); $celldefault = new html_table_cell(); $celldefault->attributes['class'] = 'data'; // This extra cell is needed in order to support accessibility for screenreader. MDL-30816 $accessiblecell = new html_table_cell(); $accessiblecell->scope = 'row'; $accessiblecell->text = get_string('choiceoptions', 'choice'); $columns['options'][] = $accessiblecell; $usernumberheader = clone($celldefault); $usernumberheader->header = true; $usernumberheader->attributes['class'] = 'header data'; $usernumberheader->text = get_string('numberofuser', 'choice'); $columns['usernumber'][] = $usernumberheader; $optionsnames = []; foreach ($choices->options as $optionid => $options) { $celloption = clone($celldefault); $cellusernumber = clone($celldefault); if ($choices->showunanswered && $optionid == 0) { $headertitle = get_string('notanswered', 'choice'); } else if ($optionid > 0) { $headertitle = format_string($choices->options[$optionid]->text); if (!empty($choices->options[$optionid]->user) && count($choices->options[$optionid]->user) > 0) { if ((count($choices->options[$optionid]->user)) == ($choices->options[$optionid]->maxanswer)) { $headertitle .= ' ' . get_string('full', 'choice'); } } } $celltext = $headertitle; // Render select/deselect all checkbox for this option. if ($choices->viewresponsecapability && $choices->deleterepsonsecapability) { // Build the select/deselect all for this option. $selectallid = 'select-response-option-' . $optionid; $togglegroup = 'responses response-option-' . $optionid; $selectalltext = get_string('selectalloption', 'choice', $headertitle); $deselectalltext = get_string('deselectalloption', 'choice', $headertitle); $mastercheckbox = new \core\output\checkbox_toggleall($togglegroup, true, [ 'id' => $selectallid, 'name' => $selectallid, 'value' => 1, 'selectall' => $selectalltext, 'deselectall' => $deselectalltext, 'label' => $selectalltext, 'labelclasses' => 'accesshide', ]); $celltext .= html_writer::div($this->output->render($mastercheckbox)); } $numberofuser = 0; if (!empty($options->user) && count($options->user) > 0) { $numberofuser = count($options->user); } if (($choices->limitanswers) && ($choices->showavailable)) { $numberofuser .= html_writer::empty_tag('br'); $numberofuser .= get_string("limita", "choice", $options->maxanswer); } $celloption->text = html_writer::div($celltext, 'text-center'); $optionsnames[$optionid] = $celltext; $cellusernumber->text = html_writer::div($numberofuser, 'text-center'); $columns['options'][] = $celloption; $columns['usernumber'][] = $cellusernumber; } $table->head = $columns['options']; $table->data[] = new html_table_row($columns['usernumber']); $columns = array(); // This extra cell is needed in order to support accessibility for screenreader. MDL-30816 $accessiblecell = new html_table_cell(); $accessiblecell->text = get_string('userchoosethisoption', 'choice'); $accessiblecell->header = true; $accessiblecell->scope = 'row'; $accessiblecell->attributes['class'] = 'header data'; $columns[] = $accessiblecell; foreach ($choices->options as $optionid => $options) { $cell = new html_table_cell(); $cell->attributes['class'] = 'data'; if ($choices->showunanswered || $optionid > 0) { if (!empty($options->user)) { $optionusers = ''; foreach ($options->user as $user) { $data = ''; if (empty($user->imagealt)) { $user->imagealt = ''; } $userfullname = fullname($user, $choices->fullnamecapability); $checkbox = ''; if ($choices->viewresponsecapability && $choices->deleterepsonsecapability) { $checkboxid = 'attempt-user' . $user->id . '-option' . $optionid; if ($optionid > 0) { $checkboxname = 'attemptid[]'; $checkboxvalue = $user->answerid; } else { $checkboxname = 'userid[]'; $checkboxvalue = $user->id; } $togglegroup = 'responses response-option-' . $optionid; $slavecheckbox = new \core\output\checkbox_toggleall($togglegroup, false, [ 'id' => $checkboxid, 'name' => $checkboxname, 'classes' => 'mr-1', 'value' => $checkboxvalue, 'label' => $userfullname . ' ' . $options->text, 'labelclasses' => 'accesshide', ]); $checkbox = $this->output->render($slavecheckbox); } $userimage = $this->output->user_picture($user, array('courseid' => $choices->courseid, 'link' => false)); $profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $choices->courseid)); $profilelink = html_writer::link($profileurl, $userimage . $userfullname); $data .= html_writer::div($checkbox . $profilelink, 'mb-1'); $optionusers .= $data; } $cell->text = $optionusers; } } $columns[] = $cell; $count++; } $row = new html_table_row($columns); $table->data[] = $row; $html .= html_writer::tag('div', html_writer::table($table), array('class'=>'response')); $actiondata = ''; if ($choices->viewresponsecapability && $choices->deleterepsonsecapability) { // Build the select/deselect all for all of options. $selectallid = 'select-all-responses'; $togglegroup = 'responses'; $selectallcheckbox = new \core\output\checkbox_toggleall($togglegroup, true, [ 'id' => $selectallid, 'name' => $selectallid, 'value' => 1, 'label' => get_string('selectall'), 'classes' => 'btn-secondary mr-1' ], true); $actiondata .= $this->output->render($selectallcheckbox); $actionurl = new moodle_url($this->page->url, ['sesskey' => sesskey(), 'action' => 'delete_confirmation()']); $actionoptions = array('delete' => get_string('delete')); foreach ($choices->options as $optionid => $option) { if ($optionid > 0) { $actionoptions['choose_'.$optionid] = get_string('chooseoption', 'choice', $option->text); } } $selectattributes = [ 'data-action' => 'toggle', 'data-togglegroup' => 'responses', 'data-toggle' => 'action', ]; $selectnothing = ['' => get_string('chooseaction', 'choice')]; $select = new single_select($actionurl, 'action', $actionoptions, null, $selectnothing, 'attemptsform'); $select->set_label(get_string('withselected', 'choice')); $select->disabled = true; $select->attributes = $selectattributes; $actiondata .= $this->output->render($select); } $html .= html_writer::tag('div', $actiondata, array('class'=>'responseaction')); if ($choices->viewresponsecapability) { $html .= html_writer::end_tag('form'); } return $html; } /** * Returns HTML to display choices result * @deprecated since 3.2 * @param object $choices * @return string */ public function display_publish_anonymous_horizontal($choices) { debugging(__FUNCTION__.'() is deprecated. Please use mod_choice_renderer::display_publish_anonymous() instead.', DEBUG_DEVELOPER); return $this->display_publish_anonymous($choices, CHOICE_DISPLAY_VERTICAL); } /** * Returns HTML to display choices result * @deprecated since 3.2 * @param object $choices * @return string */ public function display_publish_anonymous_vertical($choices) { debugging(__FUNCTION__.'() is deprecated. Please use mod_choice_renderer::display_publish_anonymous() instead.', DEBUG_DEVELOPER); return $this->display_publish_anonymous($choices, CHOICE_DISPLAY_HORIZONTAL); } /** * Generate the choice result chart. * * Can be displayed either in the vertical or horizontal position. * * @param stdClass $choices Choices responses object. * @param int $displaylayout The constants DISPLAY_HORIZONTAL_LAYOUT or DISPLAY_VERTICAL_LAYOUT. * @return string the rendered chart. */ public function display_publish_anonymous($choices, $displaylayout) { $count = 0; $data = []; $numberofuser = 0; $percentageamount = 0; foreach ($choices->options as $optionid => $option) { if (!empty($option->user)) { $numberofuser = count($option->user); } if($choices->numberofuser > 0) { $percentageamount = ((float)$numberofuser / (float)$choices->numberofuser) * 100.0; } $data['labels'][$count] = $option->text; $data['series'][$count] = $numberofuser; $data['series_labels'][$count] = $numberofuser . ' (' . format_float($percentageamount, 1) . '%)'; $count++; $numberofuser = 0; } $chart = new \core\chart_bar(); if ($displaylayout == DISPLAY_HORIZONTAL_LAYOUT) { $chart->set_horizontal(true); } $series = new \core\chart_series(format_string(get_string("responses", "choice")), $data['series']); $series->set_labels($data['series_labels']); $chart->add_series($series); $chart->set_labels($data['labels']); $yaxis = $chart->get_yaxis(0, true); $yaxis->set_stepsize(max(1, round(max($data['series']) / 10))); return $this->output->render($chart); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Weather App</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"> <style> body { font-family: 'Arial', sans-serif; text-align: center; margin: 0; padding: 0; background-size: cover; background-position: center; background-image: url('background.jpg'); /* Replace 'your-background-image.jpg' with the path to your image */ color: #fff; height: 100vh; display: flex; align-items: center; justify-content: center; transition: background-image 0.5s ease; /* Add transition property for smooth image transition */ } #app { width: 80%; max-width: 400px; padding: 20px; background-color: rgba(255, 255, 255, 0.9); border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); } h1 { color: #333; margin-bottom: 20px; } input { padding: 12px; margin: 8px 0; width: calc(100% - 24px); box-sizing: border-box; border: none; border-radius: 4px; font-size: 16px; } button { margin-top: 25px; padding: 12px; background-color: #1976D2; color: #fff; border: none; border-radius: 4px; cursor: pointer; width: 84%; box-sizing: border-box; font-size: 16px; transition: background-color 0.3s ease; } button:hover { background-color: #1565C0; } #weather-info { margin-top: 20px; color: #333; /* Set text color to black */ } #error-message { color: #d32f2f; margin-top: 10px; } </style> </head> <body> <div id="app"> <h1>Weather App <i class="fas fa-cloud-sun"></i></h1> <input type="text" id="cityInput" placeholder="Enter city name"> <button onclick="getWeather()">Get Weather <i class="fas fa-search"></i></button> <div id="error-message"></div> <div id="weather-info"></div> </div> <script> async function getWeather() { const apiKey = '8d1a4ddf2f82412aaba164754240601'; const cityInput = document.getElementById('cityInput'); const errorMessage = document.getElementById('error-message'); const weatherInfo = document.getElementById('weather-info'); const body = document.body; // Clear previous data and background image errorMessage.textContent = ''; weatherInfo.textContent = ''; body.style.backgroundImage = 'none'; const cityName = cityInput.value.trim(); if (cityName === '') { errorMessage.textContent = 'Please enter a city name.'; return; } try { const response = await fetch(`https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${encodeURIComponent(cityName)}&aqi=yes`); const data = await response.json(); if (response.ok && data.current) { const temperature = data.current.temp_c; const description = data.current.condition.text; weatherInfo.innerHTML = ` <p><strong>Temperature:</strong> ${temperature}°C</p> <p><strong>Weather:</strong> ${description}</p> `; // Set background based on weather description if (description.toLowerCase().includes('sunny')) { body.style.backgroundImage = 'url("sunny.jpg")'; // Replace with the path to your sunny background image } else if (description.toLowerCase().includes('cold')) { body.style.backgroundImage = 'url("cold.jpg")'; // Replace with the path to your cold background image } else if (description.toLowerCase().includes('clear')) { body.style.backgroundImage = 'url("clear.jpg")'; // Replace with the path to your clear background image } else if (description.toLowerCase().includes('haze')) { body.style.backgroundImage = 'url("haze.jpg")'; // Replace with the path to your haze background image } else if (description.toLowerCase().includes('mist')) { body.style.backgroundImage = 'url("mist.jpg")'; // Replace with the path to your mist background image } else if (description.toLowerCase().includes('cloudy')) { body.style.backgroundImage = 'url("cloudy.jpg")'; // Replace with the path to your cloudy background image } else if (description.toLowerCase().includes('partly cloudy')) { body.style.backgroundImage = 'url("cloudy.jpg")'; // Replace with the path to your partly cloudy background image } else if (description.toLowerCase().includes('rainy')) { body.style.backgroundImage = 'url("rainy.jpg")'; // Replace with the path to your rainy background image } else if (description.toLowerCase().includes('overcast')) { body.style.backgroundImage = 'url("rain.jpg")'; // Replace with the path to your rainy background image } } else { errorMessage.textContent = `Error: ${data.error.info}`; } } catch (error) { console.error('Error fetching weather data:', error); errorMessage.textContent = 'An error occurred while fetching weather data. Please try again.'; } } </script> </body> </html>
/* * Copyright © 2009 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * * Authors: * Eric Anholt <eric@anholt.net> * Marek Olšák <maraeo@gmail.com> * */ /** @file fbo-depth-tex1d.c * * Tests that rendering to a 1D texture with a depth texture * and then drawing both to the framebuffer succeeds. */ #include "piglit-util-gl-common.h" #define BUF_WIDTH 16 PIGLIT_GL_TEST_CONFIG_BEGIN config.supports_gl_compat_version = 10; config.window_visual = PIGLIT_GL_VISUAL_DOUBLE | PIGLIT_GL_VISUAL_DEPTH; PIGLIT_GL_TEST_CONFIG_END #define F(name) #name, name struct format { const char *name; GLuint iformat, format, type; const char *extension; } formats[] = { {F(GL_DEPTH_COMPONENT16), GL_DEPTH_COMPONENT, GL_FLOAT, "GL_ARB_depth_texture"}, {F(GL_DEPTH_COMPONENT24), GL_DEPTH_COMPONENT, GL_FLOAT, "GL_ARB_depth_texture"}, {F(GL_DEPTH_COMPONENT32), GL_DEPTH_COMPONENT, GL_FLOAT, "GL_ARB_depth_texture"}, {F(GL_DEPTH24_STENCIL8), GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8_EXT, "GL_EXT_packed_depth_stencil"}, {F(GL_DEPTH_COMPONENT32F), GL_DEPTH_COMPONENT, GL_FLOAT, "GL_ARB_depth_buffer_float"}, {F(GL_DEPTH32F_STENCIL8), GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, "GL_ARB_depth_buffer_float"} }; struct format f; static void create_1d_fbo(GLuint *out_tex, GLuint *out_ds) { GLuint tex, ds, fb; GLenum status; /* Create the color buffer. */ glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_1D, tex); glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, BUF_WIDTH, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); assert(glGetError() == 0); /* Create the depth-stencil buffer. */ glGenTextures(1, &ds); glBindTexture(GL_TEXTURE_1D, ds); glTexImage1D(GL_TEXTURE_1D, 0, f.iformat, BUF_WIDTH, 0, f.format, f.type, NULL); assert(glGetError() == 0); /* Create the FBO. */ glGenFramebuffersEXT(1, &fb); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb); glFramebufferTexture1DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_1D, tex, 0); glFramebufferTexture1DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_1D, ds, 0); if (f.format == GL_DEPTH_STENCIL) { glFramebufferTexture1DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_1D, ds, 0); } assert(glGetError() == 0); status = glCheckFramebufferStatusEXT (GL_FRAMEBUFFER_EXT); if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { piglit_report_result(PIGLIT_SKIP); } glViewport(0, 0, BUF_WIDTH, 1); glClearDepth(1); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); glDepthRange(0, 0); glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); piglit_ortho_projection(BUF_WIDTH, 1, GL_FALSE); /* green */ glColor4f(0.0, 1.0, 0.0, 0.0); piglit_draw_rect(0, 0, BUF_WIDTH, 1); glDeleteFramebuffersEXT(1, &fb); *out_tex = tex; *out_ds = ds; } static void draw_fbo_1d(int x, int y) { glViewport(0, 0, piglit_width, piglit_height); piglit_ortho_projection(piglit_width, piglit_height, GL_FALSE); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glEnable(GL_TEXTURE_1D); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); piglit_draw_rect_tex(x, y, BUF_WIDTH, 1, 0, 0, 1, 1); } enum piglit_result piglit_display(void) { GLboolean pass = GL_TRUE; float black[] = {0,0,0,0}; float green[] = {0,1,0,0}; float *expected; int x; GLuint tex, ds; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(1.0, 1.0, 1.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); create_1d_fbo(&tex, &ds); glBindTexture(GL_TEXTURE_1D, tex); draw_fbo_1d(10, 10); glBindTexture(GL_TEXTURE_1D, ds); draw_fbo_1d(10+BUF_WIDTH, 10); for (x = 0; x < BUF_WIDTH*2; x++) { if (x < BUF_WIDTH) expected = green; else expected = black; pass &= piglit_probe_pixel_rgb(10 + x, 10, expected); } glDeleteTextures(1, &tex); glDeleteTextures(1, &ds); piglit_present_results(); return pass ? PIGLIT_PASS : PIGLIT_FAIL; } void piglit_init(int argc, char **argv) { unsigned i, p; piglit_require_extension("GL_EXT_framebuffer_object"); for (p = 1; p < argc; p++) { for (i = 0; i < sizeof(formats)/sizeof(*formats); i++) { if (!strcmp(argv[p], formats[i].name)) { piglit_require_extension(formats[i].extension); f = formats[i]; return; } } } if (!f.name) { printf("Not enough parameters.\n"); piglit_report_result(PIGLIT_SKIP); } }
import { useState } from "react"; import { BookmarkCheckFill } from "react-bootstrap-icons"; import { useDispatch } from "react-redux"; import { selectLabel } from "../../../features/label/labelSlice"; import { deleteLabel, getLabels } from "../../../features/label/label.thunk"; import EventInput from "../eventInput/EventInput"; import { ListContainer, ListColor, ListItemContainer, DeleteBtn, ButtonContainer, ListInfoContainer, ListWrapper, } from "./CategoryList.styles"; import { Trash } from "react-bootstrap-icons"; const CategoryList = ({ lists }) => { const [isOpenModal, setIsOpenModal] = useState(false); const dispatch = useDispatch(); const openInputFormHandler = () => { dispatch(selectLabel(lists._id)); setIsOpenModal(!isOpenModal); }; const deleteLabelHandler = () => { if (window.confirm("정말 제거하시겠습니까? ")) { dispatch(deleteLabel(lists._id)).then(() => dispatch(getLabels())); } }; return ( <> {isOpenModal && ( <EventInput onConfirm={() => setIsOpenModal(!isOpenModal)} /> )} <ListContainer> <ListWrapper> <ListItemContainer onClick={openInputFormHandler}> <ListColor> <BookmarkCheckFill color={lists.color} /> </ListColor> <span>{lists.labelTitle}</span> <ListInfoContainer> <p> {lists.allDay && "종일"} {lists.daysOfWeek && "정기"} </p> </ListInfoContainer> </ListItemContainer> <ButtonContainer> <DeleteBtn> <Trash onClick={deleteLabelHandler} /> </DeleteBtn> </ButtonContainer> </ListWrapper> </ListContainer> </> ); }; export default CategoryList;
/* Copyright (c) 2017 FIRST. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of FIRST nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS * LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.ElapsedTime; import com.qualcomm.robotcore.util.Range; /** * This file contains an example of an iterative (Non-Linear) "OpMode". * An OpMode is a 'program' that runs in either the autonomous or the teleop period of an FTC match. * The names of OpModes appear on the menu of the FTC Driver Station. * When an selection is made from the menu, the corresponding OpMode * class is instantiated on the Robot Controller and executed. * * This particular OpMode just executes a basic Tank Drive Teleop for a two wheeled robot * It includes all the skeletal structure that all iterative OpModes contain. * * Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name. * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list */ @TeleOp(name="HardwareDebbuging", group="Iterative Opmode") public class HardwareDebugging extends OpMode { // Declare OpMode members. private ElapsedTime runtime = new ElapsedTime(); private DcMotor dc_Motor1 = null; private DcMotor dc_Motor2 = null; private Servo servo1 = null; private Servo servo2 = null; /* * Code to run ONCE when the driver hits INIT */ @Override public void init() { telemetry.addData("Status", "Initialized"); // Initialize the hardware variables. Note that the strings used here as parameters // to 'get' must correspond to the names assigned during the robot configuration // step (using the FTC Robot Controller app on the phone). dc_Motor1 = hardwareMap.get(DcMotor.class, "dc_Motor1"); dc_Motor2 = hardwareMap.get(DcMotor.class, "dc_Motor2"); servo1 = hardwareMap.get(Servo.class, "servo1"); servo2 = hardwareMap.get(Servo.class, "servo2"); // Most robots need the motor on one side to be reversed to drive forward // Reverse the motor that runs backwards when connected directly to the battery dc_Motor1.setDirection(DcMotor.Direction.FORWARD); dc_Motor2.setDirection(DcMotor.Direction.FORWARD); servo1.setDirection(Servo.Direction.FORWARD); servo2.setDirection(Servo.Direction.REVERSE); // Tell the driver that initialization is complete. telemetry.addData("Status", "Initialized"); } /* * Code to run REPEATEDLY after the driver hits INIT, but before they hit PLAY */ @Override public void init_loop() { } /* * Code to run ONCE when the driver hits PLAY */ @Override public void start() { runtime.reset(); } /* * Code to run REPEATEDLY after the driver hits PLAY but before they hit STOP */ @Override public void loop() { // Setup a variable for each Power1 wheel to save power level for telemetry double Motor1Power; double Motor2Power; double Posi = servo1.getPosition(); // Choose to Power1 using either Tank Mode, or POV Mode // Comment out the method that's not used. The default below is POV. // POV Mode uses left stick to go forward, and right stick to Power2. // - This uses basic math to combine motions and is easier to Power1 straight. double Power1 = gamepad1.left_stick_y; double Power2 = gamepad1.right_stick_x; Motor1Power = Range.clip(Power1, -1.0, 1.0) ; Motor2Power = Range.clip(Power2, -1.0, 1.0) ; float Servo_Close = gamepad1.right_trigger; float Servo_Open = gamepad1.left_trigger; while (Servo_Close > 0){ Posi = Range.clip(Posi + 0.1, 0, 1.0); } while (Servo_Open > 0){ Posi = Range.clip(Posi - 0.1, 0, 1.0); } // Tank Mode uses one stick to control each wheel. // - This requires no math, but it is hard to Power1 forward slowly and keep straight. // Motor1Power = -gamepad1.left_stick_y ; // Motor2Power = -gamepad1.right_stick_y ; // Send calculated power to wheels dc_Motor1.setPower(Motor1Power); dc_Motor2.setPower(Motor2Power); servo1.setPosition(Posi); servo2.setPosition(Posi); double Servo1 = servo1.getPosition(); double Servo2 = servo2.getPosition(); // Show the elapsed game time and wheel power. telemetry.addData("Status", "Run Time: " + runtime.toString()); telemetry.addData("Motors", "Motor1 (%.2f), Motor2 (%.2f)", Motor1Power, Motor2Power); // Will HardwareMap.get( class, device) send an ID Number??? telemetry.addData("Motor ID", "Motor1:(%.2f), Motor2:(%.2f)", dc_Motor1, dc_Motor2); telemetry.addData("Servos", "Servo1 ($.2f), Servo2 (%.2f)", Servo1 , Servo2); } /* * Code to run ONCE after the driver hits STOP */ @Override public void stop() { } }
package com.aulanosa.api.services.impl; import com.aulanosa.api.dtos.EstadisticaDTO; import com.aulanosa.api.dtos.JugadorDTO; import com.aulanosa.api.mappers.EstadisticaMapper; import com.aulanosa.api.repositories.EstadisticaRepository; import com.aulanosa.api.services.EstadisticaService; import com.aulanosa.api.services.JugadorService; import jakarta.annotation.PostConstruct; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; import java.util.stream.IntStream; @Service @Lazy @Component public class EstadisticaServiceImpl implements EstadisticaService { @Autowired private EstadisticaRepository estadisticaRepository; @Autowired private JugadorService jugadorService; /** * Este método permite obtener los promedios de todos los jugadores mediante una petición a una api externa * @return Lista de objetos EstadisticaDTO */ private List<EstadisticaDTO> obtenerPromedios() { List<EstadisticaDTO> promedios = new ArrayList<>(); List<JugadorDTO> jugadores = jugadorService.obtenerJugadoresTemporada(); int[] playerIds = jugadores.stream().mapToInt(JugadorDTO::getIdJugador).toArray(); int midpoint = playerIds.length / 2; int[] firstHalf = Arrays.copyOfRange(playerIds, 0, midpoint); int[] secondHalf = Arrays.copyOfRange(playerIds, midpoint, playerIds.length); String firstHalfParams = IntStream.of(firstHalf) .mapToObj(id -> "player_ids[]=" + id) .collect(Collectors.joining("&")); String secondHalfParams = IntStream.of(secondHalf) .mapToObj(id -> "player_ids[]=" + id) .collect(Collectors.joining("&")); try { for (int i = 0; i < 2; i++) { URL url = null; if(i==0){ url = new URL("https://api.balldontlie.io/v1/season_averages?season=2023&" + firstHalfParams); }else{ url = new URL("https://api.balldontlie.io/v1/season_averages?season=2023&" + secondHalfParams); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", System.getenv("BALL_DONT_LIE")); connection.setRequestMethod("GET"); connection.connect(); int code = connection.getResponseCode(); if (code != 200) { System.out.println("Se produjo un error: " + code); System.out.println(connection.getResponseMessage()); } else { StringBuilder information = new StringBuilder(); Scanner sc = new Scanner(connection.getInputStream()); while (sc.hasNext()) { information.append(sc.nextLine()); } sc.close(); JSONArray jsonArray = new JSONObject(information.toString()).getJSONArray("data"); for (int j = 0; j < jsonArray.length(); j++) { JSONObject jsonObject = jsonArray.getJSONObject(j); EstadisticaDTO estadisticaDTO = new EstadisticaDTO(); estadisticaDTO.setIdJugador(jsonObject.getInt("player_id")); estadisticaDTO.setPuntosPorPartido(jsonObject.getDouble("pts")); estadisticaDTO.setAsistenciasPorPartido(jsonObject.getDouble("ast")); estadisticaDTO.setPerdidasPorPartido(jsonObject.getDouble("turnover")); estadisticaDTO.setFaltasPorPartido(jsonObject.getDouble("pf")); estadisticaDTO.setTirosIntentados(jsonObject.getDouble("fga")); estadisticaDTO.setTirosConvertidos(jsonObject.getDouble("fgm")); estadisticaDTO.setTirosLibresIntentados(jsonObject.getDouble("fta")); estadisticaDTO.setTirosLibresConvertidos(jsonObject.getDouble("ftm")); estadisticaDTO.setTriplesIntentados(jsonObject.getDouble("fg3a")); estadisticaDTO.setTriplesConvertidos(jsonObject.getDouble("fg3m")); estadisticaDTO.setRebotesPorPartido(jsonObject.getDouble("reb")); estadisticaDTO.setRebotesOfensivosPorPartido(jsonObject.getDouble("oreb")); estadisticaDTO.setRebotesDefensivosPorPartido(jsonObject.getDouble("dreb")); estadisticaDTO.setRobosPorPartido(jsonObject.getDouble("stl")); estadisticaDTO.setTaponesPorPartido(jsonObject.getDouble("blk")); estadisticaDTO.setPorcentajeTirosDeCampo(jsonObject.getDouble("fg_pct")); estadisticaDTO.setPorcentajeTriples(jsonObject.getDouble("fg3_pct")); estadisticaDTO.setPorcentajeTirosLibres(jsonObject.getDouble("ft_pct")); estadisticaDTO.setMinutosJugados(jsonObject.getString("min")); estadisticaDTO.setPartidosJugados(jsonObject.getInt("games_played")); promedios.add(estadisticaDTO); } System.out.println("ESTADISTICAS TODO BIEN"); } } } catch (Exception e) { e.printStackTrace(); } return promedios; } /** * Este método permite almacenar las estadísticas de los jugadores en base de datos */ @Override @Scheduled(cron = "0 59 23 23 10 ?") public void insertarEstadisticas() { List<EstadisticaDTO> promedios = obtenerPromedios(); for (EstadisticaDTO estadisticaDTO : promedios) { estadisticaRepository.save(EstadisticaMapper.convertirAModelo(estadisticaDTO)); } } /** * Este método permite obtener todas las estadísticas de la base de datos * @return */ @Override public List<EstadisticaDTO> getEstadisticas() { return EstadisticaMapper.convertirLista(estadisticaRepository.findAll()); } }
@using Microsoft.AspNetCore.Identity @inject SignInManager<IdentityUser> SignInManager @inject UserManager<IdentityUser> UserManager <!DOCTYPE html> <html lang="en"> <head> <link rel="shortcut icon" href="/logo3.png" type="image/png"> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://fonts.googleapis.com/css2?family=Raleway:ital,wght@0,400;0,500;0,600;0,700;1,400&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Raleway:ital,wght@0,400;0,500;0,600;0,700;1,400&display=swap" rel="stylesheet"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;400;700&display=swap" rel="stylesheet"> <script src="https://cdn.anychart.com/releases/v8/js/anychart-base.min.js"></script> <script src="https://cdn.anychart.com/releases/v8/js/anychart-ui.min.js"></script> <script src="https://cdn.anychart.com/releases/v8/js/anychart-exports.min.js"></script> <script src="https://cdn.anychart.com/releases/v8/js/anychart-stock.min.js"></script> <script src="https://cdn.anychart.com/releases/v8/js/anychart-data-adapter.min.js"></script> <link href="https://cdn.anychart.com/releases/v8/css/anychart-ui.min.css" type="text/css" rel="stylesheet"> <link href="https://cdn.anychart.com/releases/v8/fonts/css/anychart-font.min.css" type="text/css" rel="stylesheet"> <title>@ViewData["Title"] - AM</title> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" /> </head> <body> <header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <div class="container"> <a asp-area="" asp-controller="Home" asp-action="Index"><img src="~/logo2.png"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark nav_link_page" asp-area="" asp-controller="Home" asp-action="Index">Главная страница</a> </li> @if (SignInManager.IsSignedIn(User)) { <li class="nav-item"> <a class="nav-link text-dark nav_link_page" asp-area="" asp-controller="Home" asp-action="Privacy">Справка</a> </li> } </ul> <partial name="_LoginPartial" /> </div> </div> </nav> </header> <div class="container-fluid"> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> &copy; 2021 | App Marketing | @if (SignInManager.IsSignedIn(User)) {<a class="link_page nav_link_page" asp-area="" asp-controller="Home" asp-action="Privacy">Справка</a>} else {<a class="link_page nav_link_page" asp-area="" asp-controller="Home" asp-action="Index">Главная страница</a>} </div> </footer> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> <script src="http://thecodeplayer.com/uploads/js/prefixfree-1.0.7.js" type="text/javascript"></script> @await RenderSectionAsync("Scripts", required: false) </body> </html>
#include "binary_trees.h" /** * binary_tree_rotate_left - a function that performs a left-rotation * on a binary tree * @tree: a pointer to the root node of the tree to rotate * * Return: a pointer to the new root node of the tree once rotated */ binary_tree_t *binary_tree_rotate_left(binary_tree_t *tree) { binary_tree_t *right; if (!tree || !tree->right) return (NULL); right = tree->right; right->parent = tree->parent; tree->parent = right; if (right->left) right->left->parent = tree; tree->right = right->left; right->left = tree; return (right); }
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const express_1 = __importDefault(require("express")); const body_parser_1 = __importDefault(require("body-parser")); const uuid_1 = require("uuid"); const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); const app = (0, express_1.default)(); app.listen(3000, () => { console.log("SERVER RUN:3000"); }); app.use(body_parser_1.default.json()); const medicos = []; const pacientes = []; const consultasCadastradas = []; const secretKeyMedico = "10203040"; const secretKeyPaciente = "10203050"; const secretKeyConsulta = "10203060"; // Cadastro de Médico app.post("/medicos", (req, res) => { const { nome, crm } = req.body; if (!nome || !crm) { return res .status(400) .json({ error: "Por favor, preencha todos os campos..." }); } const existingUser = medicos.find((user) => user.nome === nome); if (existingUser) { return res.status(409).json({ error: "Usuário já existe" }); } const newUser = { id: (0, uuid_1.v4)(), nome, crm, }; medicos.push(newUser); res .status(201) .json({ message: "Médico cadastrado com sucesso", user: newUser }); }); // Login de Médico app.post("/login/medico", (req, res) => { const { nome, crm } = req.body; const medico = medicos.find((m) => m.nome === nome && m.crm === crm); if (medico) { const token = jsonwebtoken_1.default.sign({ nome, crm }, secretKeyMedico, { expiresIn: "1h", }); res.json({ token }); } else { res.status(401).json({ error: "Credenciais inválidas" }); } }); // Listar Médicos app.get("/medicos", (req, res) => { res.json(medicos); }); // Atualizar Médico app.put("/medicos/:id", (req, res) => { const atualizaMedicoId = req.params.id; const { nome, crm } = req.body; const medicoIndex = medicos.findIndex((m) => m.id === atualizaMedicoId); if (medicoIndex === -1) { return res.status(404).json({ error: "Médico não encontrado." }); } const medicoAtualizado = { id: atualizaMedicoId, nome, crm, }; medicos[medicoIndex] = medicoAtualizado; res.json({ message: "Médico atualizado com sucesso", medico: medicoAtualizado, }); }); // Delete Médico app.delete("/medicos/:id", (req, res) => { const medicoIdToDelete = req.params.id; const medicoIndex = medicos.findIndex((m) => m.id === medicoIdToDelete); if (medicoIndex === -1) { return res.status(404).json({ error: "Médico não encontrado." }); } medicos.splice(medicoIndex, 1); res.json({ message: "Médico excluído com sucesso" }); }); // ... Resto do código (Cadastro, Login, Listar e Atualizar Pacientes, Delete Paciente) // Cadastro de Paciente app.post("/pacientes", (req, res) => { const { nomepaciente, rg } = req.body; if (!nomepaciente || !rg) { return res .status(400) .json({ error: "Por favor, preencha todos os campos..." }); } const existingUser = pacientes.find((user) => user.nomepaciente === nomepaciente); if (existingUser) { return res.status(409).json({ error: "Usuário já existe" }); } const newUser = { id: (0, uuid_1.v4)(), nomepaciente, rg, }; pacientes.push(newUser); res .status(201) .json({ message: "Paciente cadastrado com sucesso", user: newUser }); }); // Login de Paciente app.post("/login/pacientes", (req, res) => { const { nomepaciente, rg } = req.body; const pacienteEncontrado = pacientes.find((p) => p.nomepaciente === nomepaciente && p.rg === rg); if (pacienteEncontrado) { const token = jsonwebtoken_1.default.sign({ nomepaciente, rg }, secretKeyPaciente, { expiresIn: "1h", }); res.json({ token }); } else { res.status(401).json({ error: "Erro, digite novamente ..." }); } }); // Listar Pacientes app.get("/pacientes", (req, res) => { res.json(pacientes); }); // Atualizar Paciente app.put("/pacientes/:id", (req, res) => { const atualizaPacienteId = req.params.id; const { nomepaciente, rg } = req.body; const pacienteIndex = pacientes.findIndex((p) => p.id === atualizaPacienteId); if (pacienteIndex === -1) { return res.status(404).json({ error: "Paciente não encontrado." }); } const pacienteAtualizado = { id: atualizaPacienteId, nomepaciente, rg, }; pacientes[pacienteIndex] = pacienteAtualizado; res.json({ message: "Paciente atualizado com sucesso", paciente: pacienteAtualizado, }); }); // Delete Paciente app.delete("/pacientes/:id", (req, res) => { const pacienteIdToDelete = req.params.id; const pacienteIndex = pacientes.findIndex((p) => p.id === pacienteIdToDelete); if (pacienteIndex === -1) { return res.status(404).json({ error: "Paciente não encontrado." }); } pacientes.splice(pacienteIndex, 1); res.json({ message: "Paciente excluído com sucesso" }); }); // consulta // agendar consulta app.post("/agendar/consultas", (req, res) => { const { descricao, data, paciente_id, medico_id } = req.body; if (!descricao || !data || !paciente_id || !medico_id) { return res .status(400) .json({ error: "Por favor, preencha todos os campos..." }); } const existingConsulta = consultasCadastradas.find((user) => user.data === data); if (existingConsulta) { return res.status(409).json({ error: "ERRO,Consulta já foi cadastrada" }); } const newConsulta = { id: (0, uuid_1.v4)(), descricao, data, medico_id, paciente_id, }; consultasCadastradas.push(newConsulta); res .status(201) .json({ message: "Consulta cadastrada com sucesso", consulta: newConsulta }); }); // listando consultas cadastradas app.get("/listar/consultas", (req, res) => { res.json(consultasCadastradas); }); // atualizando consulta app.put("/atualizando/consultas/:id", (req, res) => { const atualizaConsulta = req.params.id; const { descricao, data, paciente_id, medico_id } = req.body; console.log("Dados recebidos:", descricao, data, paciente_id, medico_id); const consultasIndex = consultasCadastradas.findIndex((c) => c.id === atualizaConsulta); if (consultasIndex === -1) { return res.status(400).json("consulta nao encontrada"); } const consultaAtualizada = { id: atualizaConsulta, descricao, data, paciente_id, medico_id, }; consultasCadastradas[consultasIndex] = consultaAtualizada; console.log("Consulta atualizada:", consultaAtualizada); res.json({ message: "consulta foi atualizada", consulta: consultaAtualizada }); }); app.delete("/deletar/consultas/:id", (req, res) => { const excluindoConsultas = req.params.id; const excluindoIndex = consultasCadastradas.findIndex((c) => c.id === excluindoConsultas); if (excluindoIndex === -1) { return res.status(401).json("consulta nao encontrada"); } consultasCadastradas.splice(excluindoIndex, 1); res.json({ message: "consulta excluida com sucesso" }); });
import * as React from "react"; import MobileStepper from "@mui/material/MobileStepper"; import Button from "@mui/material/Button"; import styles from "../../style"; import Introduction from "./Introduction"; import { validateContactInfo, validateCredentials, validateDescription, } from "./Validate"; import { useSelector } from "react-redux"; import { RootState } from "../../../state/store"; import { useCreatePostMutation } from "../../../state/api/gd"; import { Link, useNavigate } from "react-router-dom"; import Swal from "sweetalert2"; import { ColorRing } from "react-loader-spinner"; import Credentials from "./credentials"; import Description from "./Description"; import { PrimaryButton } from "src/gd/components/Button"; import "react-phone-input-2/lib/style.css"; export type UserData = { application_for: string; mode: string; category: string; first_name: string; last_name: string; fathers_name: string; mothers_name: string; country: string; province: string; city: string; zip: string; address: string; marital_status: string; specific_marital_status: string; date_of_birth: Date | null; sex: string; specific_sex: string; blood_group: string; occupation: string; email: string; phone: string; identification_card: File | null; certificate_from_city_council: File | null; medical_report: File | null; permission_letter: File | null; test_results: File | null; name_of_employment: string; credential_photos: string[]; other_documents: File | null; title: string; photo: string; live_description: string; written_description: string; time_limit: string; fixed_time: Date | null; donation_needed: string | number; [key: string]: string | string[] | number | Date | File | null | undefined; }; const initState: UserData = { application_for: "", mode: "", category: "", first_name: "", last_name: "", fathers_name: "", mothers_name: "", country: "", province: "", city: "", zip: "", address: "", marital_status: "", specific_marital_status: "", date_of_birth: null, sex: "", specific_sex: "", blood_group: "", occupation: "", email: "", phone: "", identification_card: null, certificate_from_city_council: null, medical_report: null, permission_letter: null, test_results: null, name_of_employment: "", credential_photos: [], other_documents: null, title: "", photo: "", live_description: "", written_description: "", time_limit: "", fixed_time: null, donation_needed: "", }; export default function Apply() { const navigate = useNavigate(); const successAlert = () => { Swal.fire({ title: "Thank you!", text: "We received your application. Go to your dashboard to check your details.", icon: "success", showConfirmButton: true, confirmButtonText: "Dashboard", preConfirm: () => navigate("/gd/profile"), }); }; const { access_token } = useSelector((state: RootState) => state.auth); const [createPost, { isLoading: isCreatingPost }] = useCreatePostMutation(); const [userData, setUserData] = React.useState<UserData>(initState); const [errorMessage, setErrorMessage] = React.useState<any>({}); console.log("userData", userData); const steps = [ { label: "Introduction", content: ( <Introduction userData={userData} setUserData={setUserData} errorMessage={errorMessage} setErrorMessage={setErrorMessage} /> ), }, { label: "Credentials", content: ( <Credentials userData={userData} setUserData={setUserData} errorMessage={errorMessage} setErrorMessage={setErrorMessage} /> ), }, { label: "Description", content: ( <Description userData={userData} setUserData={setUserData} errorMessage={errorMessage} setErrorMessage={setErrorMessage} /> ), }, ]; const [activeStep, setActiveStep] = React.useState(0); const maxSteps = steps.length; const handleNext = () => { let errMsg = {}; if (activeStep === 0) { errMsg = validateContactInfo(userData); } if (activeStep === 1) { errMsg = validateCredentials(userData); } if (Object.keys(errMsg).length > 0) return setErrorMessage(errMsg); setActiveStep((prevActiveStep) => prevActiveStep + 1); }; const handleBack = () => { setActiveStep((prevActiveStep) => prevActiveStep - 1); }; const handleSubmit = async () => { const errMsg = validateDescription(userData); if (Object.keys(errMsg).length > 0) return setErrorMessage(errMsg); const response = await createPost({ userData, access_token }); console.log("response", response); if ("error" in response) { if ("data" in response.error) { const errorData: any = response.error.data; setErrorMessage(errorData); } } if ("data" in response) { setErrorMessage({}); successAlert(); setUserData(initState); } }; return ( <div className={`${styles.paddingX} ${styles.paddingY} text-secondaryTheme`} > <div className="mb-3 flex justify-between items-center"> <h1 className={`text-start ${styles.heading2}`}>Apply for donation!</h1> <Link to={`${access_token ? "/gd/apply/volunteer" : "/login"}`}> <PrimaryButton> Be a Volunteer </PrimaryButton> </Link> </div> <div className="w-full bg-white p-[1rem] sm:p-[5rem] mt-[3rem]"> <h4 className="text-xl font-bold text-gray-900 m-0 p-0"> {steps[activeStep].label} </h4> <div className="w-full mt-5">{steps[activeStep].content}</div> </div> <MobileStepper variant="text" steps={maxSteps} position="static" activeStep={activeStep} sx={{ background: "transparent", color: "white", marginTop: "3rem", padding: 0, }} nextButton={ <Button variant="contained" onClick={activeStep === maxSteps - 1 ? handleSubmit : handleNext} className="focus:outline-none bg-green-700 normal-case px-4 text-secondaryTheme" > {activeStep === maxSteps - 1 ? ( isCreatingPost ? ( <ColorRing visible={true} height="30" width="30" ariaLabel="blocks-loading" wrapperStyle={{}} wrapperClass="blocks-wrapper" colors={[ "#b8c480", "#B2A3B5", "#F4442E", "#51E5FF", "#429EA6", ]} /> ) : ( "Submit" ) ) : ( "Next" )} </Button> } backButton={ <Button variant="outlined" className={`${ activeStep === 0 ? "hidden" : "d-flex" } focus:outline-none normal-case px-4 text-secondaryTheme`} onClick={handleBack} hidden={true} disabled={activeStep === 0} > Back </Button> } /> </div> ); }
classdef Fitness < handle methods(Static=true) function [trainErr, testErr, genErr] = evalMackey(rc, show) % evalMackey evaluates reservoir fitness on the Mackey-glass % time-series. Errors are squashed to meliorate blow up. % Parameters: % rc : reservoir computer object % show : optional flag to plot results % Returns: % trainErr : Mean squared error on training data seen before % testErr : Mean squared error on data not seen before from the % training sequence % genErr: Mean squared error on data not seen before from a new % sequence if nargin < 2, show = false; end; % Make time series with random initial point T = makeMackeyGlass(0.5+rand,17,0.1,50000); T = T(10001:10:end); % subsample (now have 4000 time steps) T = tanh(T-1); % squash into (-1,1) X = 0.2*ones(size(T)); % constant bias % Train on the Mackey glass data (only regress on second 1000) rc.reset(); trainErr = rc.train(X, T, 1000:2000, 1); % Mean squared error on data not seen before, same series rc.reset(); [~,~] = rc.stream(X(:,1:2000),T(:,1:2000)); [~,Y] = rc.stream(X(:,2001:2500)); testErr = (T(:,2001:2500)-Y).^2; testErr = mean(testErr(:)); if show t = 2001:2500; plot(t,T(:,t)',t,Y'); end % %%% Generalization error % % Make time series with new random initial point % T = makeMackeyGlass(0.5+rand,17,0.1,50000); % T = T(10001:10:end); % subsample (now have 4000 time steps) % T = tanh(T-1); % squash into (-1,1) % % % Reset the reservoir to zero activations and stream the first 2000 time % % steps with "teacher forcing" (target output is used for feedback) % rc.reset(); % [~,~] = rc.stream(X(:,1:2000),T(:,1:2000)); % % % Stream the remainder without teacher forcing % [~,Y] = rc.stream(X(:,2001:3000)); % % % Mean squared error on data not seen before, new series % % genErr = tanh(T(:,2001:3000)-Y).^2; % genErr = (T(:,2001:3000)-Y).^2; % genErr = mean(genErr(:)); % % if show % subplot(3,1,3); % t = 2001:3000; % plot(t,T(:,t)',t,Y'); % end genErr = 0; end function [trainErr, testErr, genErr] = evalSpeech(rc, Xsp, Tsp) % evalSpeech evaluates reservoir fitness on the Speech data % time-series. % Parameters: % rc : reservoir computer object % Xsp : input speech signals in SpeechData.mat % Tsp : target output signals in SpeechData.mat % Returns: % trainErr : 0/1 error rate on training data heard before % testErr : 0/1 error rate on utterances not heard before from % speakers heard before % genErr : 0/1 error rate on utterances not heard before from % speakers not heard before % randomize training set (N speakers, utterances, and digits) N = 3; utterances = randperm(10,N); speakers = randperm(10,N); digits = randperm(10,N); % Don't train on last speaker or utterances X = Xsp(utterances(1:end-1), speakers(1:end-1), digits); T = Tsp(utterances(1:end-1), speakers(1:end-1), digits); % Train t = repmat({1:99},size(T)); % Use 1st 99 time-steps in each series rc.train(X, T, t, 1); % Tally losses X = Xsp(utterances, speakers, digits); trainErr = 0; testErr = 0; genErr = 0; for u = 1:N for s = 1:N for d = 1:N % Reset the reservoir to zero activations and stream a testing signal rc.reset(); [~,Y] = rc.stream(X{u,s,d}); [~,p] = max(Y(:,90)); % predicted digit if s < N if u < N trainErr = trainErr + (p~=digits(d)); else testErr = testErr + (p~=digits(d)); end else genErr = genErr + (p~=digits(d)); end end end end trainErr = trainErr/((N-1)*(N-1)*N); testErr = testErr/((N-1)*N); genErr = genErr/(N*N); end function fit = eval(rcMackey, rcSpeech, Xsp, Tsp) % eval aggregates performance on both Mackey-glass and speech. % The two ReservoirComputers given as input should wrap the same % reservoir. Xsp, Tsp are the data from SpeechData.mat % Evaluate on each task [trainErr, testErr, genErr] = Fitness.evalMackey(rcMackey); [trainLoss, testLoss, genLoss] = Fitness.evalSpeech(rcSpeech, Xsp, Tsp); % Aggregate % unfit = trainErr+testErr+genErr+trainLoss+testLoss+genLoss; unfit = testErr+testLoss; % unfit = trainErr+trainLoss; %fit = 1./(1+unfit); % invert for fitness in [0,1] fit = 1./unfit; % invert for fitness in [0,Inf] end function fit = evalOtca(otca, Xsp, Tsp) % evalOtca wraps otca in task-specific reservoirs and evaluates. N = numel(otca.a); % number of units % Mackey ext = randperm(N, 20); % indices of external-signal-receiving units readIn = sparse(ext(1:10), 1, 1, N, 1); % 1st 10 for input readOut = zeros(1, N); readBack = sparse(ext(11:20), 1, 1, N, 1); % last 10 for feedback rcMackey = ReservoirComputer(otca, readIn, readOut, readBack); % Speech numIn = 2; % Number of input-receiving units per channel ext = randperm(N, numIn*13); % 13 input channels readIn = sparse(ext, repmat(1:13, 1, numIn), 1, N, 13); readOut = zeros(10, N); % 10 output channels readBack = zeros(N, 10); % no feedback rcSpeech = ReservoirComputer(otca, readIn, readOut, readBack); % Evaluate fit = Fitness.eval(rcMackey, rcSpeech, Xsp, Tsp); end end end
# Задача 1. Повторение кода # # В одной из практик вы уже писали декоратор do_twice, который повторяет вызов декорируемой функции два раза. # В этот раз реализуйте декоратор repeat, который повторяет задекорированную функцию уже n раз. import functools from collections.abc import Callable def repeat(num: int): def decorator(func: Callable) -> Callable: @functools.wraps(func) def wrapped(*args, **kwargs): for _ in range(num): func(*args, **kwargs) return None return wrapped return decorator @repeat(num=5) def some_func(): print('Функция выполнена') some_func()
#include "main.h" /** * _strlen - returns the length of a string. * * @s: pointer to the string to be checked. * * Return: returns length of a string passed to it. */ int _strlen(char *s) { int counter; counter = 0; while (*s != '\0') { counter++; s++; } return (counter); }
import React, { useContext } from "react"; import PropTypes from "prop-types"; import UserForm from "../components/ui/userForm"; import { useHistory } from "react-router-dom"; import { UserContext } from "../UserContext"; import Logout from "../components/ui/logout"; import MainBlock from "../components/common/mainBlock"; import { fetchUsers } from "../mocked-api/users"; const User = () => { const history = useHistory(); const userContext = useContext(UserContext); const onBlockClick = async () => { const newUsers = await fetchUsers(1); userContext.setUsers(newUsers); history.push("/Main?page=1"); }; return ( <div className="d-flex"> <MainBlock onClick={onBlockClick} /> <div style={{ flex: 15 }}> <div className="d-flex justify-content-between"> <div className="d-flex justify-content-start"> <h3 className="text-black-50 m-3" onClick={onBlockClick} > Пользователи </h3> </div> <Logout /> </div> <div className="container mt-5"> <div className="row"> <div className="col-md-6 p-4"> <h3>Добавление пользователя</h3> <UserForm /> </div> </div> </div> </div> </div> ); }; User.propTypes = { addUser: PropTypes.func }; export default User;
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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 com.polygon.geolocation.useractivityrecog import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.util.Log import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.platform.LocalContext import com.google.android.gms.location.ActivityTransitionResult import com.polygon.geolocation.useractivityrecog.UserActivityTransitionManager.Companion.getActivityType import com.polygon.geolocation.useractivityrecog.UserActivityTransitionManager.Companion.getTransitionType @Composable fun UserActivityBroadcastReceiver( systemAction: String, systemEvent: (userActivity: String) -> Unit, ) { val context = LocalContext.current val currentSystemOnEvent by rememberUpdatedState(systemEvent) DisposableEffect(context, systemAction) { val intentFilter = IntentFilter(systemAction) val broadcast = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val result = intent?.let { ActivityTransitionResult.extractResult(it) } ?: return var resultStr = "" for (event in result.transitionEvents) { resultStr += "${getActivityType(event.activityType)} " + "- ${getTransitionType(event.transitionType)}" } Log.d("UserActivityReceiver", "onReceive: $resultStr") currentSystemOnEvent(resultStr) } } context.registerReceiver(broadcast, intentFilter) onDispose { context.unregisterReceiver(broadcast) } } }
### 文章目录 - [一:经典网络结构](#_16) - - [(1) LeNet-5(CNN开山始祖)](#1_LeNet5CNN_18) - [(2)AlexNet](#2AlexNet_55) - - [A:简介](#A_57) - [B:网络结构](#B_83) - [(3)VGGNet](#3VGGNet_146) - - [A:简介](#A_148) - [B:网路结构](#B_182) - [二:复杂网络结构](#_279) - - [(1)ResNet(残差网络)](#1ResNet_281) - - [A:简介](#A_283) - [B:网络结构](#B_294) - [(2)DenseNet](#2DenseNet_393) - [(3)InceptionNet v1-v4](#3InceptionNet_v1v4_468) - [三:轻量型网络结构](#_474) - - [(1)MobileNet](#1MobileNet_476) - [(2)SquuezeNet](#2SquuezeNet_494) - [(3)ShuffleNet](#3ShuffleNet_498) 过去几年计算机视觉研究中的大量研究都集中在如何把这些基本构件组合起来,形成有效的卷积神经网络。最直观的方式之一就是去看一些案例,就像很多人通过看别人的代码来学习编程一样,通过研究别人构建有效组件的案例是个不错的办法。实际上在计算机视觉任务中表现良好的神经网络框架往往也适用于其它任务,也许你的任务也不例外。也就是说,**如果有人已经训练或者计算出擅长识别猫、狗、人的神经网络或者神经网络框架,而你的计算机视觉识别任务是构建一个自动驾驶汽车,你完全可以借鉴别人的神经网络框架来解决自己的问题** 1998年**卷积神经网络开山之作LeNet**被提出,但当时受限于算力和数据集,所以它提出之后一直被传统目标识别算法(特征提取+分类器)所压制,终于在沉寂了14年之后的2012年,**AlexNet横空出世**,在ImageNet挑战赛一举夺魁,使得CNN再次被人重视,并且一发不可收拾,不断研究发展 **如下图是卷积神经网络发展概述,主要是如下三个发展趋势** - 经典网络结构:以LeNet、AlexNet、VGGNet为代表,主要是卷积层的简单堆叠 - 复杂神经网络:以ResNet、InceptionNetV1-V4、DenseNet为代表 - 轻量型神经网络:以MobileNetV1-V3、ShuffleNet、SqueezeNet为代表 ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2F63563048a59c4bf8ae979165fe9abcec.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) # 一:经典网络结构 ## (1) LeNet-5(CNN开山始祖) **LeNet-5:是一个较简单的卷积神经网络。下图显示了其结构:输入的二维图像,先经过两次卷积层到池化层,再经过全连接层,最后使用softmax分类作为输出层** - **注意**:使用的激活函数为tanh ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Faef89129ae534a28b65296e2728d0b9c.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Fb376176f7eca4f4fb080b69052de3067.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) ```python import torch.nn as nn import torch.nn.functional as F class LeNet5(nn.Module): def __init__(self): super(LeNet5, self).__init__() self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5) self.pool = nn.MaxPool2d(kernel_size=2, stride=2) self.conv2 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5) self.fc1 = nn.Linear(in_features=16 * 5 * 5, out_features=120) self.fc2 = nn.Linear(in_features=120, out_features=84) self.fc3 = nn.Linear(in_features=84, out_features=10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x ``` ## (2)AlexNet ### A:简介 LeNet提出之后,卷积神经网络在CV和ML中就小有名气了,但是那是它并没有开始主导这些领域,这是因为虽然LeNet在小数据集上取到了很好的效果,但是在更大、更真实的数据集上训练卷积神经网络的性能和可行性还有待研究,事实上在上世纪90年代和2012年大部分时间里,神经网络往往被其他机器学习方法超越,例如非常出名的SVM 但在CV中,神经网络和传统机器学习算法仍然是有很大区别的,例如传统机器学习方法并不会把原始像素直接作为输入,而是会有一个非常重要的步骤——**特征工程** 虽然上世纪90年代已经有了一些神经网络的加速卡,但仅仅靠他们还不足以开发出有大量参数的深层多通道多层卷积神经网络。因此,与卷积神经网络这种**端到端**(像素输入分类输出)的系统不同,传统机器学习流水线应该是这样 - 收集数据 - 根据光学、几何学等其他知识手工对数据集进行预处理 - 通过标准特征提取算法,例如SIFT(尺度不变特征变换)、SURF(加速鲁邦特征)输入数据 - 将提取好的特征送入到你喜欢的分类器中,例如SVM 在2012年AlexNet出现之前,图像特征都是机械地算出来的,而有一些研究人员认为**特征本身是可以被学习的**,并且,在合理地复杂性前提下,特征应该有多个共同学习的神经网络层组成,每个层都应该有可以学习的层数。AlexNet便是这样的网络,2012年在ImageNet上夺得第一名,准确率比传统机器学习算法高出不少 ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Fc1a2345f84d642eeb818dfd138f25960.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) 和人眼提出物体特征一样,AlexNet的**底层**会提取到如边缘、颜色等基础信息,然后**高层**会建立在这些底层特征上再次提取,以标识更大的特征,例如眼睛、鼻子、草叶等等,而更高层可以检测整个物体,例如人、飞机等等 ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2F11375d54662f47a6b3e60985bb766a6b.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) **Alex的成功主要归功于以下两点** - **数据**:2009年ImageNet数据集发布,并发起了ImageNet挑战赛,要求比赛人员需要从100万个样本中训练模型,以区分1000个不同类别的对象,这种规模是前所未有的 - **硬件**:1999年NVIDA发明了GPU,用于为游戏玩家服务,用来加速图形处理。GPU可以优化高吞吐量的4×4矩阵和向量加法,从而服务于基本图形任务,仔细思考,这些数学运算和卷积运算非常相似。因此GPU的出现大大改变了神经网络训练的窘境 ### B:网络结构 **AlexNet:Alex网络结构如下图所示,其设计理念和LeNet非常相似,主要区别如下** - 网络结构要比LeNet5**深很多** - 由5个卷积层、两个全连接层隐藏层和一个全连接输出层组成 - AlexNet使用ReLU作为激活函数 - AlexNet第一层的卷积核比较大,为11×11,这是因为ImageNet中大多图像要比MNIST图像多10倍以上 - AlexNet使用**dropout算法**来控制全连接层复杂程度,而LeNet5只使用了权重衰减 - AlexNet对图像数据进行了**增广**(例如对一张图像翻转、裁切和变色相等于有了3张以上的图像),这增大了样本量,减少了过拟合 ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Fec061de081154499a6af67d2d8c2ffd0.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) **细节过程** ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2F03f425754d06439c887f96fb2f493d48.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) ```python import torch import torch.nn as nn import torch.nn.functional as F class AlexNet(nn.Module): def __init__(self, num_classes=1000): super(AlexNet, self).__init__() self.features = nn.Sequential( nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(64, 192, kernel_size=5, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(192, 384, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(384, 256, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(256, 256, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), ) self.avgpool = nn.AdaptiveAvgPool2d((6, 6)) self.classifier = nn.Sequential( nn.Dropout(), nn.Linear(256 * 6 * 6, 4096), nn.ReLU(inplace=True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(inplace=True), nn.Linear(4096, num_classes), ) def forward(self, x): x = self.features(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.classifier(x) return x ``` ## (3)VGGNet ### A:简介 虽然AlexNet证明了深层神经网络网络是有效的,但是它没有提供一个**通用的模板**来指导后续的研究人员设计新的网络。与芯片设计中工程师从放置晶体管到逻辑元件再到逻辑块的过程类似,神经网络架构的设计也逐渐变得更加抽象。**研究人员开始从单个神经元角度思考问题,发展到整个层,现在又转向块,重复层的模式** 在VGG网络中,通过使用循环和子程序,可以很容易地在任何现代深度学习框架中实现这些重复的架构 **经典CNN的基本组成部分一般是下面的序列** - 带填充以保持分辨率的卷积层 - 激活函数 - 汇聚层 一个VGG块与之类似,由一系列卷积层组成,后面再加上利用空间下采样的最大汇聚层 ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2F01c2b7254f914d19b8b322e1577c4a6f.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) 下面代码中定义了一个名字叫做`vgg_block`的函数来实现一个VGG块 ```python ```python import torch from torch import nn # num_convs表示该VGG块内卷积层的数量 def vgg_block(num_convs, in_chaneels, out_channels): layers = [] for _ in range(num_convs): layers.append(nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)) layers.apeend(nn.ReLu()) in_channels = out_channels layers.append(nn.MaxPool2d(kernel_size=2, stride=2)) return nn.Sequential(*layers) ``` ### B:网路结构 **VGGNet:VGG网络结构如下图所示,和AlexNet、LeNet-5一样,VGG网络可以分为两个部分** - 第一部分主要由卷积层和汇聚层组成 - 第二部分由全连接层组成 ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Fbf93485c77244711a1764044f9a26230.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) **其优点如下** - VGG模型**以较深的网络结构,较小的卷积核和池采样域**,使其能够在获得更多图像特征的同时控制参数的个数,避免计算量过多和过于复杂的结构 - 采用小的卷积核进行堆叠,两个3×3卷积核的堆叠相当于5×5卷积核的视野,三个3×3卷积核的堆叠相当于7×7卷积核的视野。这样做可以有更少的参数(3个堆叠的3×3卷积核参数为27个,而一个7×7卷积核参数有49个),另外还拥有了**更多的非线性变换,增强了CNN的学习能力** - 在卷积结构中,引入1×1卷积核,在不影响输入输出维度的情况下,增强了网络的表达能力,降低了计算力量 - 训练时,先训练级别简单(层数较浅)的A级网络,然后使用A级网络的权重来初始化后面的复杂模型,加快训练收敛速度 - 采用Multi-Scale方法来训练和预测,可以增加训练的数据量,防止模型过拟合,提升预测准确率 - Multi-Scale(多尺度图像预测):将图片进行不同尺度的缩放,得到图像金字塔,然后对每层图片提取不同尺度的特征,得到特征图。最后对每个尺度的特征都进行单独的预测 - **VGG可以单独作为特征抽取器或预训练模型来使用** **VGG有很多的变体** ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Fa23d78ece36a4a8aa30f1f527e0ff6a8.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) 如下,实现一个VGG16,16表示它有13个卷积层和3个全连接层 ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2F1bd55cae530e47d2bebf38859aa1edc5.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) ```python import torch import torch.nn as nn import torch.nn.functional as F class VGG16(nn.Module): def __init__(self, num_classes=1000): super(VGG16, self).__init__() self.features = nn.Sequential( nn.Conv2d(3, 64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(64, 64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(64, 128, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(128, 128, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(128, 256, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(256, 256, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(256, 256, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(256, 512, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(512, 512, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(512, 512, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(512, 512, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(512, 512, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(512, 512, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), ) self.classifier = nn.Sequential( nn.Linear(512 * 7 * 7, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, num_classes), ) def forward(self, x): x = self.features(x) x = x.view(x.size(0), -1) x = self.classifier(x) return x model = VGG16() ``` # 二:复杂网络结构 ## (1)ResNet(残差网络) ### A:简介 从LeNet-5、AlexNet、VGG中可以看出,深层网络一般会比浅层网络的效果要好。那么要想进一步提升模型的准确率,那么把网络设计的越深越好不就行了吗。但事实并非如此,如下图,在ImageNet上做过一个实验,对于一个常规的网络,其在56层时的错误率却远远高于20层时的错误率 ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Fe3ee512944c042c5af92b6c6afcd9a24.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) 因此,随着网络层级的不断加深,模型的精度在前期也会随之提升,但是当网络层级增加到一定的数目以后,训练精度和测试精度迅速下降,这**说明网络变得很深以后,深度网络变得更加难以训练了**。回想神经网络反向传播原理,**神经网络在反向传播中要不断传播梯度,而当网络层数加深时,梯度在传播过程中会逐渐消失,最终导致无法对前面网络层进行有效调整** ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Fa6e8075f5f44423ba8184d5220917efe.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) ### B:网络结构 **ResNet:残差网络的基本结构如下图所示,很明显该图是带有跳跃结构的** ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2F60a20df0bb134b4fb28d0c0cb1ee0158.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) 假定某段神经网络的输入是 x x x,期望的复杂输出是 H \( x \) H\(x\) H\(x\),如果要学习这样的模型,则训练的难度会比较大。残差网络的思想是,**如果已经学习到了较为饱和的准确率,或者说当发现下层的误差会变大时,那么接下来的学习目标就转变为恒等映射的学习,也就是使输入 x x x近似于输出 H \( x \) H\(x\) H\(x\),以保证在后面的层次中不会造成精度的下降**。在上图中,通过“shortcut connections”的方式,直接把输入 x x x传到输出作为初始结果,输出结构为 H \( x \) = F \( x \) + x H\(x\)=F\(x\)+x H\(x\)\=F\(x\)+x,当 F \( x \) = 0 F\(x\)=0 F\(x\)\=0时,那么 H \( x \) = x H\(x\)=x H\(x\)\=x 因此,残差网络将学习目标改变了:**不再是学习一个完整的输出,而是目标值 H \( x \) H\(x\) H\(x\)和 x x x的差值,也即残差:= H \( x \) = x H\(x\)=x H\(x\)\=x,因此后续的训练目标就是要将残差结果逼近于0,使得随着网络加深,准确率不下降** 这种残差跳跃式的结构,打破了传统的神经网络n-1层的输出只能给n层作为输入的惯例,**使某一层的输出可以直接跨过几层作为后面某一层的输入,其意义在于为叠加多层网络而使得整个学习模型的错误率不降反升的难题提供了新的方向** **下图是一个34层的深度残差网络结构图,下图中的实线和虚线分别表示** - 实线:表示通道相同,所以 H \( x \) = F \( x \) + x H\(x\)=F\(x\)+x H\(x\)\=F\(x\)+x - 虚线:表示通道不同,所以 H \( x \) = F \( x \) + W x H\(x\)=F\(x\)+Wx H\(x\)\=F\(x\)+Wx,W为卷积操作 ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Fb00c76a8e5464c00985d41490fd6fd9e.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) ```python import torch import torch.nn as nn import torch.nn.functional as F # 基本跳连模块 class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion*planes: self.shortcut = nn.Sequential( nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(self.expansion*planes) ) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.bn2(self.conv2(out)) out += self.shortcut(x) out = F.relu(out) return out class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(ResNet, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) self.linear = nn.Linear(512*block.expansion, num_classes) def _make_layer(self, block, planes, num_blocks, stride): strides = [stride] + [1]*(num_blocks-1) layers = [] for stride in strides: layers.append(block(self.in_planes, planes, stride)) self.in_planes = planes * block.expansion return nn.Sequential(*layers) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.layer1(out) out = self.layer2(out) out = self.layer3 out = self.layer4(out) out = F.avg_pool2d(out, 4) out = out.view(out.size(0), -1) out = self.linear(out) return out def ResNet18(): return ResNet(BasicBlock, [2,2,2,2]) def ResNet34(): return ResNet(BasicBlock, [3,4,6,3]) def ResNet50(): return ResNet(Bottleneck, [3,4,6,3]) def ResNet101(): return ResNet(Bottleneck, [3,4,23,3]) def ResNet152(): return ResNet(Bottleneck, [3,8,36,3]) ``` ## (2)DenseNet **DenseNet:就是在保证网络中层与层之间最大程度的信息传输的前提下,直接把所有层连接起来。换句话说,每一层的输入来自前面所有层的输出** ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Fc8e389ec3a794323a33239a38cd01128.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) ```python import torch import torch.nn as nn class DenseBlock(nn.Module): def __init__(self, in_channels, growth_rate, num_layers): super(DenseBlock, self).__init__() self.layers = nn.ModuleList([nn.Sequential( nn.BatchNorm2d(in_channels), nn.ReLU(), nn.Conv2d(in_channels, growth_rate, kernel_size=3, padding=1, bias=False) ) for _ in range(num_layers)]) def forward(self, x): for layer in self.layers: out = layer(x) x = torch.cat([x, out], dim=1) return x class TransitionLayer(nn.Module): def __init__(self, in_channels, out_channels): super(TransitionLayer, self).__init__() self.transition = nn.Sequential( nn.BatchNorm2d(in_channels), nn.ReLU(), nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), nn.AvgPool2d(kernel_size=2, stride=2) ) def forward(self, x): return self.transition(x) class DenseNet(nn.Module): def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16), num_init_features=64, bn_size=4, drop_rate=0, num_classes=1000): super(DenseNet, self).__init__() self.features = nn.Sequential( nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False), nn.BatchNorm2d(num_init_features), nn.ReLU(), nn.MaxPool2d(kernel_size=3, stride=2, padding=1) ) num_features = num_init_features for i, num_layers in enumerate(block_config): block = DenseBlock(num_features, growth_rate, num_layers) self.features.add_module(f'denseblock_{ i+1}', block) num_features = num_features + num_layers * growth_rate if i != len(block_config) - 1: trans = TransitionLayer(num_features, num_features // 2) self.features.add_module(f'transition_{ i+1}', trans) num_features = num_features // 2 self.features.add_module('norm5', nn.BatchNorm2d(num_features)) self.classifier = nn.Linear(num_features, num_classes) def forward(self, x): features = self.features(x) out = nn.functional.adaptive_avg_pool2d(features, (1, 1)) out = out.view(out.size(0), -1) out = self.classifier(out) return out ``` ## (3)InceptionNet v1-v4 - 仅做了解 # 三:轻量型网络结构 ## (1)MobileNet **MobileNet:由Google团队提出,主要目的是为了设计能够用于移动端的网络结构,使用深度可分离卷积方式代替传统卷积方式。如下图,Depthwise convolution和标准卷积不同,对于标准卷积其卷积核是用在所有的输入通道上(input channels),而depthwise convolution针对每个输入通道采用不同的卷积核,就是说一个卷积核对应一个输入通道,所以说depthwise convolution是depth级别的操作。而pointwise convolution其实就是普通的卷积,只不过其采用1x1的卷积核** ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Ff29f529c13e14e06ab582528b726b08e.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) 对于depthwise separable convolution,其首先是采用depthwise convolution对不同输入通道分别进行卷积,然后采用pointwise convolution将上面的输出再进行结合,这样其实整体效果和一个标准卷积是差不多的,但是会大大减少计算量和模型参数量。 ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Fca0776b593914c508a7bc6e301f7563d.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) MobileNet网络结构如下 ![在这里插入图片描述](https://ziquyun.com/main/csdn/img?url=https%3A%2F%2Fimg-blog.csdnimg.cn%2Fd963a571a1614de7b6000bdb49a20bea.png&rfUrl=https%3A%2F%2Fzhangxing-tech.blog.csdn.net%2Farticle%2Fdetails%2F128921438) ## (2)SquuezeNet - [知乎:SqueezeNet详解](https://zhuanlan.zhihu.com/p/49465950) ## (3)ShuffleNet - 知乎:[『高性能模型』轻量级网络ShuffleNet\_v1及v2](https://www.cnblogs.com/hellcat/p/10318630.html)
<script setup lang="ts"> const props = defineProps({ songUrl: { type: String, required: true }, songText: { type: String, required: false, default: 'Play' }, }) const audio = ref<HTMLAudioElement | null>(null) const isPlaying = ref(false) const play = () => { if (audio.value) { audio.value.play() isPlaying.value = true } } const pause = () => { if (audio.value) { audio.value.pause() isPlaying.value = false } } const togglePlay = () => { if (isPlaying.value) { pause() } else { play() } } onMounted(() => { audio.value = new Audio(props.songUrl) }) onUnmounted(() => { if (audio.value) { audio.value.pause() audio.value = null } }) </script> <template> <div class="music-player"> <button @click="togglePlay"> <span v-if="!isPlaying">▶️ {{songText}}</span> <span v-else>⏸️ Pause</span> </button> </div> </template> <style scoped> .music-player { display: flex; /* justify-content: center; align-items: center; */ margin-top: 1rem; } .music-player button { background: transparent; border: none; font-size: 1rem; color: white; cursor: pointer; } </style>
// import 'package:student_sphere/consts/consts.dart'; // import 'package:student_sphere/widgets_common/container_heading.dart'; // import 'package:student_sphere/widgets_common/container_text.dart'; // import 'package:http/http.dart' as http; // // var link = localhostip + "/api/students/read2.php"; // // Future<List<Map<String, dynamic>>> fetchDataFromAPI() async { // final response = await http.post(Uri.parse(link)); // // if (response.statusCode == 200) { // final List<dynamic> data = json.decode(response.body); // return List<Map<String, dynamic>>.from(data); // } else { // throw Exception('Failed to load data from the API'); // } // } // // Future<Map<String, dynamic>> fetchDataFromApis(String id) async { // // try { // final response = await http.post( // Uri.parse(link), // body: {'id': id}, // ); // // // Check if the request was successful (status code 200) // if (response.statusCode == 200) { // // Parse the JSON response // Map<String, dynamic> data = json.decode(response.body); // return data; // } else { // // If the request was not successful, throw an exception // throw Exception('Failed to fetch data from the API'); // } // } catch (e) { // // Handle any errors that occurred during the fetch // print('Error: $e'); // return {}; // } // } // // class HomeScreen extends StatelessWidget { // String idStudent; // HomeScreen({super.key, required this.idStudent}); // @override // Widget build(BuildContext context) { // // return Scaffold( // backgroundColor: backColor, // appBar: AppBar( // automaticallyImplyLeading: false, // title: "Student Profile".text.fontFamily(bold).size(22).make(), // centerTitle: true, // ), // body: FutureBuilder<Map<String, dynamic>>(future: fetchDataFromApis(idStudent), // builder: (context,snapshot){ // if (snapshot.connectionState == ConnectionState.waiting) { // // While data is still loading, show a loading indicator // return CircularProgressIndicator(); // } else if (snapshot.hasError) { // // If there's an error, display an error message // return Text('Error: ${snapshot.error}'); // } else if (!snapshot.hasData || snapshot.data!.isEmpty) { // // If no data is available, display a message indicating that // return Text('No data available'); // } // else{ // Map<String, dynamic> data = snapshot.data!; // return SingleChildScrollView( // child: Column( // children: [ // // Align( // // alignment: Alignment.centerLeft, // // child: ("Student Profile").text.size(22).color(Colors.black).fontFamily(bold).make()), // 20.heightBox, // Column( // mainAxisAlignment: MainAxisAlignment.center, // children: [ // containerHeading(width: context.screenWidth, title: "University Information"), // Padding( // padding: const EdgeInsets.only(left: 8,bottom: 8), // child: Container( // color: lightGrey, // width: context.screenWidth, // height: context.screenHeight * 0.20, //context.screenHeight * 0.20 // child: Padding( // padding: const EdgeInsets.symmetric(horizontal: 5,vertical: 10), // child: Column( // children: [ // containerText(title1: "Roll No:",title2: data?['id'] ?? 'N/A'), // 8.heightBox, // containerText(title1: "Section:",title2: data?['section'] ?? 'N/A'), // 8.heightBox, // containerText(title1: "Degree:",title2: data?['degree'] ?? 'N/A'), // 8.heightBox, // containerText(title1: "Campus:",title2: data?['campus'] ?? 'N/A'), // 8.heightBox, // containerText(title1: "Status:",title2: data?['status'] ?? 'N/A'), // ], // ), // ), // ), // ), // 20.heightBox, // containerHeading(width: context.screenWidth, title: "Personal Information"), // Padding( // padding: const EdgeInsets.only(left: 8,bottom: 8), // child: Container( // decoration: const BoxDecoration( // //borderRadius: BorderRadius.circular(10), // color: lightGrey, // ), // // width: context.screenWidth, // height: context.screenHeight * 0.25, //context.screenHeight * 0.20 // child: Padding( // padding: const EdgeInsets.symmetric(horizontal: 5,vertical: 10), // child: Column( // children: [ // containerText(title1: "Name:",title2: (data?['first_name'] ?? 'N/A') + " " + (data?['last_name'] ?? 'N/A')), // 8.heightBox, // containerText(title1: "Gender:",title2: data?['gender'] ?? 'N/A'), // 8.heightBox, // containerText(title1: "DOB:",title2: data?['dob'] ?? 'N/A'), // 8.heightBox, // containerText(title1: "Email:",title2: data?['email'] ?? 'N/A'), // 8.heightBox, // containerText(title1: "Nationality:",title2: data?['nationality'] ?? 'N/A'), // 8.heightBox, // containerText(title1: "Phone Number:",title2: data?['phone'] ?? 'N/A'), // ], // ), // ), // ), // ), // 20.heightBox, // containerHeading(width: context.screenWidth, title: "Family Information"), // Padding( // padding: const EdgeInsets.only(left: 8,bottom: 8), // child: Container( // color: lightGrey, // width: context.screenWidth, // //height: context.screenHeight * 0.12, //context.screenHeight * 0.20 // child: Padding( // padding: const EdgeInsets.symmetric(horizontal: 5,vertical: 10), // child: Column( // children: [ // containerText(title1: "Relation:",title2: data?['relation'] ?? 'N/A'), // 8.heightBox, // containerText(title1: "Name:",title2: data?['parent_name'] ?? 'N/A'), // 8.heightBox, // containerText(title1: "Phone Number:",title2: data?['parent_phone'] ?? 'N/A'), // ], // ), // ), // ), // ), // // ], // ), // // ], // ), // ); // } // }), // ); // } // } import 'package:student_sphere/consts/consts.dart'; import 'package:student_sphere/widgets_common/container_heading.dart'; import 'package:student_sphere/widgets_common/container_text.dart'; import 'package:http/http.dart' as http; var link = localhostip + "/api/students/read2.php"; Future<Map<String, dynamic>> fetchDataFromApis(String id) async { try { final response = await http.post( Uri.parse(link), body: {'id': id}, ); // Check if the request was successful (status code 200) if (response.statusCode == 200) { // Parse the JSON response Map<String, dynamic> data = json.decode(response.body); return data; } else { // If the request was not successful, throw an exception throw Exception('Failed to fetch data from the API'); } } catch (e) { // Handle any errors that occurred during the fetch print('Error: $e'); return {}; } } class HomeScreen extends StatelessWidget { final String idStudent; HomeScreen({Key? key, required this.idStudent}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( automaticallyImplyLeading: false, title: "Student Profile".text.fontFamily(bold).size(22).color(Colors.teal).make(), centerTitle: true, backgroundColor: Colors.teal, ), body: FutureBuilder<Map<String, dynamic>>( future: fetchDataFromApis(idStudent), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } else if (snapshot.hasError) { return Center(child: Text('Error: ${snapshot.error}')); } else if (!snapshot.hasData || snapshot.data!.isEmpty) { return Center(child: Text('No data available')); } else { Map<String, dynamic> data = snapshot.data!; return SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildCategory(context, "University Information", [ containerText(title1: "Roll No:", title2: data['id'] ?? 'N/A'), containerText(title1: "Section:", title2: data['section'] ?? 'N/A'), containerText(title1: "Degree:", title2: data['degree'] ?? 'N/A'), containerText(title1: "Campus:", title2: data['campus'] ?? 'N/A'), containerText(title1: "Status:", title2: data['status'] ?? 'N/A'), ]), _buildCategory(context, "Personal Information", [ containerText( title1: "Name:", title2: (data['first_name'] ?? 'N/A') + " " + (data['last_name'] ?? 'N/A')), containerText(title1: "Gender:", title2: data['gender'] ?? 'N/A'), containerText(title1: "DOB:", title2: data['dob'] ?? 'N/A'), containerText(title1: "Email:", title2: data['email'] ?? 'N/A'), containerText(title1: "Nationality:", title2: data['nationality'] ?? 'N/A'), containerText(title1: "Phone Number:", title2: data['phone'] ?? 'N/A'), ]), _buildCategory(context, "Family Information", [ containerText(title1: "Relation:", title2: data['relation'] ?? 'N/A'), containerText(title1: "Name:", title2: data['parent_name'] ?? 'N/A'), containerText(title1: "Phone Number:", title2: data['parent_phone'] ?? 'N/A'), ]), ], ), ), ); } }, ), ); } Widget _buildCategory(BuildContext context, String title, List<Widget> items) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ containerHeading(width: context.screenWidth, title: title), const SizedBox(height: 10), Container( decoration: BoxDecoration( color: lightGrey, borderRadius: BorderRadius.circular(10), ), child: Padding( padding: const EdgeInsets.all(10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: items, ), ), ), const SizedBox(height: 20), ], ); } }
import type { CountryCode, Image, LanguageCode, Nullable, Translation, TMDBResponse, TMDBResponseList, Country, Language, Video, WithId, ExternalId, GenericResponse, } from '../../types' import type { Collection } from '../collections/types' import type { Genre, GenreCode } from '../genres/types' import type { CompanyItem } from '../companies/types' import type { PersonCast, PersonCrew } from '../people/types' import type { CertificationCode } from '../certifications/types' import type { ListItem } from '../lists/types' import type { ReviewItem } from '../reviews/types' import type { WatchProvider } from '../watch-providers/types' import type { Filters } from '../../types/filters' export type Movie = { id: number imdb_id: string media_type?: 'movie' title: string backdrop_path: Nullable<string> belongs_to_collection: Nullable<Collection> budget: number genres: Genre[] genre_ids?: GenreCode[] homepage: string original_language: LanguageCode original_title: string overview: Nullable<string> popularity: number poster_path: Nullable<string> release_date: string revenue: number runtime: number status: | 'Rumored' | 'Planned' | 'In Production' | 'Post Production' | 'Released' | 'Canceled' tagline: Nullable<string> adult: false video: boolean vote_average: number vote_count: number production_companies: CompanyItem[] production_countries: Country[] spoken_languages: Language[] } export type MovieItem = Pick< Movie, | 'id' | 'media_type' | 'poster_path' | 'adult' | 'overview' | 'release_date' | 'genre_ids' | 'original_title' | 'original_language' | 'title' | 'backdrop_path' | 'popularity' | 'vote_count' | 'video' | 'vote_average' > export type MovieAccountStates = { id: number favorite: boolean rated: { value: number } | boolean watchlist: boolean } export type MovieAlternativeTitles = { id: number titles: { iso_3166_1: CountryCode title: string type: string }[] } export type MovieChanges = { changes: { key: keyof Movie items: { id: string action: 'updated' time: string iso_639_1: LanguageCode value: string original_value: string }[] }[] } export type MovieTranslations = { id: number translations: Translation<{ title: string overview: string homepage: string }>[] } export type MovieReleaseDates = { id: number results: { ido_3166_1: CountryCode release_dates: { certification: CertificationCode iso_639_1: LanguageCode release_date: string type: number note: string }[] } } export type MovieCredits = { id: number cast: PersonCast[] crew: PersonCrew[] } export type MovieImages = { id: number backdrops: Image[] posters: Image[] } export type MovieKeyworks = { id: number keywords: { id: number name: string }[] } export type MovieVideos = { id: number results: Video[] } export type MovieWatchProviders = { id: number results: { [key in CountryCode]?: { link: string flatrate?: WatchProvider[] rent?: WatchProvider[] buy?: WatchProvider[] } } } // Filters type SessionFilters = Pick<Filters, 'guest_session_id'> & Required<Pick<Filters, 'session_id'>> export type MovieDetailsFilters = Pick< Filters, 'append_to_response' | 'language' > export type MovieAccountStatesFilters = SessionFilters export type MovieAlternativeTitlesFilters = Pick<Filters, 'country'> export type MovieChangesFilters = Pick< Filters, 'page' | 'start_date' | 'end_date' > export type MovieCreditsFilters = Pick<Filters, 'language'> export type MovieImagesFilters = Pick< Filters, 'language' | 'include_image_language' > export type MovieListsFilters = Pick<Filters, 'language' | 'page'> export type MovieRecommendationsFilters = Pick<Filters, 'language' | 'page'> export type MovieReviewsFilters = Pick<Filters, 'language' | 'page'> export type MovieSimilarFilters = Pick<Filters, 'language' | 'page'> export type MovieVideosFilters = Pick< Filters, 'language' | 'include_image_language' > export type MovieLatestFilters = Pick<Filters, 'language'> export type MovieRateFilters = Pick<Filters, 'session_id' | 'guest_session_id'> export type MovieNowPlayingFilters = Pick< Filters, 'language' | 'page' | 'region' > export type MoviePopularFilters = Pick<Filters, 'language' | 'page' | 'region'> export type MovieTopRatedFilters = Pick<Filters, 'language' | 'page' | 'region'> export type MovieUpcomingFilters = Pick<Filters, 'language' | 'page' | 'region'> // Body export type MovieRateBody = { value: number } // Responses type WithDates<T> = T & { dates: { maximum: string minimum: string } } export type MovieDetailsResponse = TMDBResponse<Movie> export type MovieAccountStatesResponse = TMDBResponse<MovieAccountStates> export type MovieAlternativeTitlesResponse = TMDBResponse<MovieAlternativeTitles> export type MovieChangesResponse = TMDBResponse<MovieChanges> export type MovieCreditsResponse = TMDBResponse<MovieCredits> export type MovieExternalIdsResponse = TMDBResponse<ExternalId> export type MovieImagesResponse = TMDBResponse<MovieImages> export type MovieKeywordsResponse = TMDBResponse<MovieKeyworks> export type MovieLatestResponse = TMDBResponse<Movie> export type MovieListsResponse = WithId<TMDBResponseList<ListItem[]>> export type MovieRecommendationsResponse = TMDBResponseList<Movie[]> export type MovieReleaseDatesResponse = TMDBResponse<MovieReleaseDates> export type MovieReviewsResponse = WithId<TMDBResponseList<ReviewItem[]>> export type MovieSimilarResponse = TMDBResponseList<MovieItem[]> export type MovieTranslationsResponse = TMDBResponse<MovieTranslations> export type MovieVideosResponse = TMDBResponse<MovieVideos> export type MovieWatchProvidersResponse = TMDBResponse<MovieWatchProviders> export type MovieRateResponse = TMDBResponse<GenericResponse> export type MovieNowPlayingResponse = WithDates<TMDBResponseList<Movie[]>> export type MovieUpcomingResponse = WithDates<TMDBResponseList<Movie[]>> export type MoviePopularResponse = TMDBResponseList<MovieItem[]> export type MovieTopRatedResponse = TMDBResponseList<MovieItem[]>
/* * 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 org.apache.jackrabbit.demo.mu.servlets; import org.apache.jackrabbit.demo.mu.exceptions.TestEndException; import org.apache.jackrabbit.demo.mu.model.TestCommandType; import org.apache.jackrabbit.demo.mu.model.TestProcess; import javax.jcr.RepositoryException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.LinkedList; import java.util.List; /** * Process answers on previous question and forward to the nex one or to the results of test. * * @author Pavel Konnikov * @version $Revision$ $Date$ */ public class TestProcessServlet extends MuServlet { protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { String command; if (httpServletRequest.getAttribute("newtest") != null) { command = "process"; } else { command = httpServletRequest.getParameter("command"); } switch (TestCommandType.valueOf(command)) { case abort: httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/tests"); break; case process: try { // login to repository loginToRepository(); // get test process attribute TestProcess testProcess = (TestProcess) httpServletRequest.getSession().getAttribute("process"); List<Integer> nubersOfGivenAnswers = new LinkedList<Integer>(); for (Object param : httpServletRequest.getParameterMap().keySet()) { if (httpServletRequest.getParameter((String) param).equals("on")) { // in case checkboxes nubersOfGivenAnswers.add(Integer.valueOf(((String) param).substring(6))); } else if (((String) param).startsWith("answer")) { // in case radio buttons nubersOfGivenAnswers.add(Integer.valueOf(httpServletRequest.getParameter((String) param).substring(6))); } } // process given answers testProcess.processGivenAnswers(nubersOfGivenAnswers); // give next question httpServletRequest.setAttribute("multiple", testProcess.isMultiple()); httpServletRequest.setAttribute("question", testProcess.nextQuestion()); httpServletRequest.setAttribute("position", testProcess.getQuestionNumber()); // forward to next question getServletContext().getRequestDispatcher("/pages/ProcessQuestion.jsp").forward(httpServletRequest, httpServletResponse); } catch (TestEndException e) { // remove possible setted web session attributes httpServletRequest.removeAttribute("question"); httpServletRequest.removeAttribute("position"); httpServletRequest.removeAttribute("multiple"); // forward to the test results httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/end-test"); } catch (RepositoryException e) { // remove possible setted web session attributes httpServletRequest.removeAttribute("question"); httpServletRequest.removeAttribute("position"); httpServletRequest.removeAttribute("multiple"); // redirect to the error page httpServletRequest.getSession().setAttribute("errorDescription", "Can't process question."); httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/error"); } finally { // don't forget loguot session.logout(); } break; } } }
import { formatTime } from "../../utils/formatTime"; import styles from "./songcard.module.css"; function SongCard({ artist, duration, photo, title, isActive }) { return ( <div className={`song-card ${styles["song-card"]} ${ isActive && styles.active }`} data-title={title} > <div className={styles["thumbnail-container"]}> <img src={photo} alt="song thumbnail" /> </div> <div className={styles["song-info-container"]}> <h6 className={styles["song-info-title"]}>{title}</h6> <p className={styles["song-info-artist"]}>{artist}</p> </div> <div className={styles["duration-container"]}> <p className={styles.duration}>{formatTime(duration)}</p> </div> </div> ); } export default SongCard;
/* * Copyright 2011, 2012, DFKI GmbH Robotics Innovation Center * * This file is part of the MARS simulation framework. * * MARS is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * MARS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with MARS. If not, see <http://www.gnu.org/licenses/>. * */ /** * \file Thread.h * \author Lorenz Quack */ #ifndef MARS_UTILS_THREAD_H #define MARS_UTILS_THREAD_H #include <cstddef> // for std::size_t #include <list> #include "Mutex.h" namespace mars { namespace utils { struct PthreadThreadWrapper; class Thread { public: Thread(); virtual ~Thread(); /** * \brief Starts the execution of this Thread. * This will start new thread in which the run method will be executed. * This method will return as soon as the thread has been set up. * \see run(), wait(), wait(unsigned long) */ void start(); /** * \brief Tries to cancel the Thread. * \param block If \c true cancel will only return when the * Thread stopped. * The Thread can only be canceled at certain cancellation points. * Many IO related system calls are cancellation points and so * is Thread::wait. You can manually add cancellation points to * you run method by calling Thread::setCancelationPoint(). * \see setCancellationPoint() */ void cancel(bool block=false); /** * \brief Adds a cancellation point to your run method. * \see cancel */ void setCancellationPoint(); /** * \brief stops execution until the thread has finished. * \see wait(unsigned long), cancel() */ bool wait(); bool join(); /** * \brief puts the Thread to sleep for a specified amount of time. * \param timeoutMilliseconds The time the Thread shall sleep in * milliseconds * \see wait(), cancel() */ bool wait(unsigned long timeoutMilliseconds); /** * \brief returns \c true if the Thread is running. * returns \c true if the Thread was \link start started \endlink and * has not terminated (i.e. the run method has not returned yet) and * was not canceled. returns \c false otherwise. * \see isFinished() */ bool isRunning() const; /** * \see isRunning() */ bool isFinished() const; void setStackSize(std::size_t stackSize); std::size_t getStackSize() const; bool isCurrentThread() const; static Thread* getCurrentThread(); static void cancelAll(bool block=false); protected: /** * \brief The thread will execute this method once it has been * \link start() started \endlink. * \see start(), cancel(), wait(), wait(unsigned long) */ virtual void run() = 0; /** * causes the current thread to sleep for \arg msec millisecond. */ static void msleep(unsigned long msec); private: // disallow copying Thread(const Thread &); Thread &operator=(const Thread &); static void* runHelper(void *context); static void cleanupHandler(void *context); PthreadThreadWrapper *myThread; std::size_t myStackSize; bool running; bool finished; static Mutex threadListMutex; static std::list<Thread*> threads; }; // end of class Thread } // end of namespace utils } // end of namespace mars #endif /* MARS_UTILS_THREAD_H */
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Student Form</title> </head> <input> <h1>Student Registration</h1> <br><br> <input th:action="@{/processStudentForm}" th:object="${student}" method="post"> First name: <input type="text" th:field="*{firstName}"> <br><br> Last name: <input type="text" th:field="*{lastName}"> <br><br> Country: <select th:field="*{country}"> <option th:each="tempCountry:${countries}" th:value="${tempCountry}" th:text="${tempCountry}"></option> </select> <br><br> Favourite Programming Language: <input type="radio" th:field="*{favouriteProgrammingLanguage}" th:each="lang:${favouriteProgrammingLanguage}" th:value="${lang}" th:text="${lang}" > <br><br> Favourite Operating System: <input type="checkbox" th:field="*{favouriteOS}" th:each="OS:${favouriteOS}" th:value="${OS}" th:text="${OS}"> <br><br> <input type="submit" value="Submit"> </form> </body> </html>
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(SnackbarStatus) public enum SnackbarStatus: Int { case visible case hidden } open class Snackbar: Bar { /// A convenience property to set the titleLabel text. open var text: String? { get { return textLabel.text } set(value) { textLabel.text = value layoutSubviews() } } /// Text label. @IBInspectable open let textLabel = UILabel() open override var intrinsicContentSize: CGSize { return CGSize(width: width, height: 49) } /// The status of the snackbar. open internal(set) var status = SnackbarStatus.hidden open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { for v in subviews { let p = v.convert(point, from: self) if v.bounds.contains(p) { return v.hitTest(p, with: event) } } return super.hitTest(point, with: event) } /// Reloads the view. open override func reload() { super.reload() centerViews = [textLabel] } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open override func prepare() { super.prepare() depthPreset = .none interimSpacePreset = .interimSpace8 contentEdgeInsets.left = interimSpace contentEdgeInsets.right = interimSpace backgroundColor = Color.grey.darken3 clipsToBounds = false prepareTextLabel() } /// Prepares the textLabel. private func prepareTextLabel() { textLabel.contentScaleFactor = Screen.scale textLabel.font = RobotoFont.medium(with: 14) textLabel.textAlignment = .left textLabel.textColor = .white textLabel.numberOfLines = 0 } }
<div class="page-container"> <nav class="navbar flex-column flex-md-row py-3 px-3"> <h1 class="py-3 px-3"> C'est la vie </h1> <ul class="justify-content-right"> <li ><a (click) ='book()'>Book Now</a></li> <li ><a (click)= "signUp()">SignUp</a></li> <li *ngIf = '!_auth.loggedIn()'><a (click)='signIn()'>Sign in</a></li> <li *ngIf = '_auth.loggedIn()'><a (click)= "_auth.logOut()">Logout</a></li> <li ><button class="membership" (click)="addMember()">Free Membership</button></li> </ul> </nav> <!--Forms--> <div class="wrapper" [class.d-none]="disableAvailable" > <h2>Check Availibility</h2> <div class="container py-3"> <div class="col-md-4 mb-3 mx-auto"> <div class="card"> <div class="card-body"> <form class="form"> <div class="form-group "> <label for="checkInDate">Check In Date</label> <input type="date" #checkInDate=ngModel class="form-control col-xs-4" [(ngModel)]="reservationData.checkInDate" name="checkInDate" [min]="minDate1" required> <small [class.d-none] = "(checkInDate.untouched || checkInDate.valid)" class="text-danger">checkInDate is required</small> </div> <div class="form-group"> <label>Check Out Date</label> <input type="date" #checkOutDate=ngModel class="form-control col-xs-4" [(ngModel)]="reservationData.checkOutDate" name="checkOutDate" [min]="minDate2" required> <small [class.d-none] = "checkOutDate.untouched || checkOutDate.valid" class="text-danger">checkOutDate is required</small> </div> <br> <div> <button type="button" class="btn btn1" (click)="checkAvailibility()" [disabled]='checkInDate.invalid || checkOutDate.invalid'>Check</button> <button type="button" class="btn" (click) = "goBack()">Back</button> </div> </form> </div> </div> </div> </div> <br><br><br> </div> <div class="wrapper" [class.d-none]="disableBooking" > <h2>Reservation Details</h2> <div class="container py-3"> <div class="col-md-4 mb-3 mx-auto"> <div class="card"> <div class="card-body"> <form class="form"> <div class="form-group "> <label for="membershipId">Membership Id</label> <input type="text" pattern="^[0-9a-fA-f]{24}$" #membershipId=ngModel class="form-control col-xs-4" [(ngModel)]="reservationData.membershipId" name="membershipId" required> <small>Not a member? <a routerLink="/members/addMember">Click here!</a></small><br> <small [class.d-none] = "(membershipId.untouched || membershipId.valid)" class="text-danger">Vaild membership Id is required</small> </div> <div class="form-group "> <label for="noOfChildren">No Of Children</label> <input type="number" #noOfChildren=ngModel class="form-control col-xs-4" [(ngModel)]="reservationData.noOfChildren" name="noOfChildren" required> <small [class.d-none] = "(noOfChildren.untouched || noOfChildren.valid)" class="text-danger">No. of Children is required and should be max 2</small> </div> <div class="form-group"> <label>No Of Adults</label> <input type="number" #noOfAdults=ngModel class="form-control col-xs-4" [(ngModel)]="reservationData.noOfAdults" name="noOfAdults" required> <small [class.d-none] = "noOfAdults.untouched || noOfAdults.valid" class="text-danger">No. of adults is required</small> </div> <div class="form-group"> <label>Verification Document</label> <input type="text" #verificationDoc=ngModel class="form-control col-xs-4" [(ngModel)]="reservationData.verificationDoc" name="verificationDoc" required> <small [class.d-none] = "verificationDoc.untouched || verificationDoc.valid" class="text-danger">Verification Document is required</small> </div> <div class="form-group"> <label>Additional Requirements</label> <input type="text" #additionalRequirements=ngModel class="form-control col-xs-4" [(ngModel)]="reservationData.additionalRequirements" name="additionalRequirements" > </div> <br> <div> <button type="button" class="btn btn1" (click)="initPay()" [disabled]='noOfAdults.invalid || noOfChildren.invalid || membershipId.invalid || verificationDoc.invalid'>Next</button> </div> </form> </div> </div> </div> </div> <br><br><br> </div> <app-footer-dark></app-footer-dark>
// react import { useState, useEffect } from "react"; // statics import { weatherAPICallBaseURL } from "../statics/URLS"; import DEFAULTS from "../statics/DEFAULTS"; // custom hooks import { useDebounce } from '@react-hook/debounce'; import useStateWithAutoSave from "./useStateWithAutoSave"; const useCitySearch = () => { // settings menu states const [citySearch, setCitySearch] = useDebounce("", DEFAULTS.cityFormDebounceTime); const [isCityValid, setIsCityValid] = useState(""); const [city, setCity] = useStateWithAutoSave(DEFAULTS.storageNames.city); // on citySearch useEffect(() => { async function testCity() { // uses bootstrap messages like "is-valid" if (citySearch) { try { // try to fetch weather data for city const res = await fetch(`${weatherAPICallBaseURL}?q=${citySearch}&appid=${process.env.REACT_APP_OPENWEATHERMAP_API_KEY}`); const weather = await res.json(); // if city is valid if (weather.cod === 200) { // display message setIsCityValid("is-valid"); // change city to the searched city (changing state of the city automatically saves it to storage and updates the ui see useWeatherFetch custom hook) setCity(citySearch); } else { // if city is not valid display city invalid message setIsCityValid("is-invalid"); } } catch { // if something is broken display city invalid message setIsCityValid("is-invalid"); } } else { // if city textbox is empty don't display any message setIsCityValid(""); } } testCity(); }, [citySearch]); return [city, setCity, citySearch, setCitySearch, isCityValid, setIsCityValid] } export default useCitySearch;
import openai from sklearn.cluster import KMeans import re import logging import time from concurrent.futures import ThreadPoolExecutor, as_completed import random from sentence_transformers import SentenceTransformer import os, sys import random app_dir = os.path.dirname(os.path.dirname(__file__)) helpers_dir = os.path.join(app_dir, 'helpers') sys.path.append(helpers_dir) import rai_guide from cred import KEY import requests gpt3 = "gpt-3.5-turbo" gpt4 = "gpt-4-turbo-preview" openai.api_key = KEY prompt = [ {"role": "system", "content": "You are an advanced AI Language Model trained in ethical reasoning and Responsible AI Impact Assessment. Your task is to provide a thorough Responsible AI Impact Assessment analysis of the given situation to the best of your ability.Keep your responses specific to the system I describe."} ] model = SentenceTransformer("mixedbread-ai/mxbai-embed-large-v1") logging.basicConfig( level=logging.CRITICAL, format='%(asctime)s - %(levelname)s - %(message)s', filename='results.log', filemode='a' ) # Predefined fairness goals and potential harms fariness_goals = { 'f1': {'concern': 'Quality of service', 'guide': rai_guide.f1_guide, 'potential_harms': [ "Performance Bias", "Outcome Inequality"] }, 'f2': {'concern': 'Allocation of resources and opportunities', 'guide': rai_guide.f2_guide, 'potential_harms': [ "Negative Feedback Loops", "Allocation Bias", "Access to Opportunities"] }, 'f3': {'concern': "stereotyping, demeaning, and erasing outputs", 'guide': rai_guide.f3_guide, 'potential_harms': [ # Stereotyping Harms: "Cultural Misrepresentation", "Reinforcement of Biases", # Demeaning Harms: "Denigration and Offense / Psychological Impact", "Facilitating Harassment and Abuse", # Erasure Harms: "Erasure of Minorities / Invisibility and Marginalization", "Historical and Cultural Erasure" ] } } # Predefined demographic groups demographic_groups_list = [ "Age", "Gender", "Ethnicity", "Income", "Level of education", "Religion" ] def chat(model, messages): """ Helper function for sending messages to the OpenAI Chat API. """ response = openai.ChatCompletion.create( model=model, messages=messages ) return response['choices'][0]['message']['content'] def chat_mistral(_, messages): """ Helper function for sending messages to the Mistral Chat API. """ response = requests.post(f"http://localhost:11434/api/chat",json={ "model": "mistral:7b-instruct-v0.2-q4_K_M", "messages": messages, "stream": False }) if response.status_code == 200: return response.json()['message']['content'] else: print("Request failed") def get_direct_stakeholders(sys_info): """ Generates direct stakeholders, categorized into obvious and surprising, for the given system information. Directly called by the backend service. """ messages = prompt + [{'role': 'user', 'content': sys_info}] messages.append({'role': 'user', 'content': f"{rai_guide.direct_stakeholder_def}\nIdentify the most relevant stakeholder(s) categorized into 'direct obvious' and 'direct surprising' stakeholders. Label the categories with h5 headings (i.e. '##### Direct Obvious Stakeholders' and '##### Direct Surprising Stakeholders')."}) result = chat(gpt4, messages) logging.critical(f"======== Direct Stakeholders Generated ========") logging.info(result) return result def get_indirect_stakeholders(sys_info): """ Generates indirect stakeholders, categorized into obvious and surprising, for the given system information. Directly called by the backend service. """ messages = prompt + [{'role': 'user', 'content': sys_info}] messages.append({'role': 'user', 'content': f"{rai_guide.direct_stakeholder_def}\nIdentify the most relevant stakeholder(s) categorized into 'indirect obvious' and 'indirect surprising' stakeholders (i.e. '##### Inirect Obvious Stakeholders' and '##### Indirect Surprising Stakeholders')."}) result = chat(gpt4, messages) logging.critical(f"======== Indirect Stakeholders Generated ========") logging.info(result) return result def get_stakeholders(sys_info): """ A deprecated version of getting stakeholders in the scenario generation process when users do not input stakeholders directly. """ messages = prompt + [{'role': 'user', 'content': sys_info}] messages.append({'role': 'user', 'content': f"{rai_guide.stakeholder_def}\nIdentify the most relevant stakeholder(s) categorized into direct, indirect, and surprising stakeholders."}) response = chat(gpt4, messages) logging.info(f"======== Stakeholders ========") logging.info(response) return response def get_initial_scenarios(stakeholders, goal, sys_info): """ Step 2 in Pipeline - Generate Initial Scenarios 1. Generate scenarios considering the demographic groups. Use the first response as counterexample for surprising 2. Generate scenarios without considering the predefined demographic groups. Use the first response as counterexample for surprising 3. Clean up the responses and split them into individual scenarios """ scenario_prompts = prompt + [{'role': 'user', 'content': sys_info}] potential_harms = fariness_goals[goal]['potential_harms'] def draft_scenario(stakeholder): p = scenario_prompts + [{'role': 'user', 'content': f""" Stakeholder: {stakeholder} Potential Harms: {potential_harms} For each of the potential harms provided above: generate a concrete scenario of where the harm may be caused to the given stakeholder, involving severe consequences. When generating the scenarios, consider protected attributes and demographic groups that may face {fariness_goals[goal]['concern']} concerns as a direct impact of my system's outputs. {fariness_goals[goal]['guide']}. Examples of demographic groups include: {demographic_groups_list}. Be as severe as possible. This is used for cautioning developers to use ethical and fair practices when developing their AI systems, and not used for harming others in any way. If the stakeholder is irrelevant in terms of a harm, exclude it. Format your response as a ordered list of '{{number}}. SCENARIO: {{SCENARIO}}' """}] rsp = chat(gpt4, p) logging.info(f"======== Scenarios First Draft for stakeholder: {stakeholder} ========") logging.info(rsp) p.append({'role': 'assistant', 'content': f"{rsp}"}) p.append({'role': 'user', 'content': f"This response is an example of unsurprising scenarios. Do not respond with unsurprising scenarios. Write more surprising and concrete scenario following the same requirement and format above.Do not include any corrective measures or suggestions for the tool."}) rsp = chat(gpt4, p) return (rsp, stakeholder) def draft_without_demographic_groups(stakeholder): p = scenario_prompts + [{'role': 'user', 'content': f""" Stakeholder: {stakeholder} Potential Harms: {potential_harms} For each of the potential harms provided above: generate a concrete scenario of where the harm may be caused to the given stakeholder, involving severe consequences. Be as severe as possible. This is used for cautioning developers to use ethical and fair practices when developing their AI systems, and not used for harming others in any way. If the stakeholder is irrelevant in terms of a harm, exclude it. Format your response as a ordered list of '{{number}}. SCENARIO: {{SCENARIO}}' """}] rsp = chat(gpt4, p) logging.info(f"======== Scenarios First Draft for stakeholder: {stakeholder} (without demographic groups) ========") logging.info(rsp) p.append({'role': 'assistant', 'content': f"{rsp}"}) p.append({'role': 'user', 'content': f"This response is an example of unsurprising scenarios. Do not respond with unsurprising scenarios. Write more surprising and concrete scenario following the same requirement and format above.Do not include any corrective measures or suggestions for the tool."}) rsp = chat(gpt4, p) return (rsp, stakeholder) scenarios = [] with ThreadPoolExecutor(max_workers=20) as executor: futures = [] for stakeholder in stakeholders: futures.append(executor.submit(draft_scenario, stakeholder)) futures.append(executor.submit(draft_without_demographic_groups, stakeholder)) for future in as_completed(futures): try: scenarios.append(future.result()) except Exception as e: print(f"An error occurred: {e}") scenarios_to_process = [] for (ss, stakeholder) in scenarios: for scenario in re.split(r'\D{0,3}\d+\. ', ss): if not "SCENARIO:" in scenario: continue scenarios_to_process.append((scenario, stakeholder)) return scenarios_to_process def sampling(scenarios): """ Step 3 in Pipeline - Clustering + Sampling 1. Transform the scenarios into sentence embeddings 2. Cluster the scenarios into 10 clusters 3. Filter out empty clusters & keep the 5 clusters with the least number of scenarios 4. Randomly sample a scenario from each of the 5 clusters """ logging.info("======== Sampling Scenarios ... ========") sentence_embeddings = model.encode(scenarios) num_clusters = min(10, len(scenarios)) clustering_model = KMeans(n_clusters=num_clusters) clustering_model.fit(sentence_embeddings) cluster_assignment = clustering_model.labels_ clustered_sentences = [[] for i in range(num_clusters)] for sentence_id, cluster_id in enumerate(cluster_assignment): clustered_sentences[cluster_id].append(scenarios[sentence_id]) # filter out empty clusters & keep the 5 clusters with the least number of scenarios clustered_sentences = [lst for lst in clustered_sentences if any(lst) and len(lst) > 0] len_sorted = sorted(clustered_sentences, key=len) clustered_sentences = len_sorted[:5] i = 0 for cluster in enumerate(clustered_sentences): logging.info(f"=== Cluster {i} ===") logging.info(cluster) i += 1 return list(map(lambda L: random.choice(L), clustered_sentences)) def refine_scenarios(scenarios_sampled, sys_info, feedback=None): """ Step 4 in Pipeline - Refinement for Concreteness & Severity In parallel, execute the helper function for refining each of the scenarios: 1. Remove the "SCENARIO:" prefix 2. Ask the llm to generate a more concrete and severe version of the scenario with definitions of the terms. Output is a paragraph (shortened version) of the scenario. 3. Evaluate if the scenario is concrete. If it is not, repeat the process for up to 3 times. """ logging.info("======== Revising Scenarios ... ========") def refine_helper(data): scenario, stakeholder = data logging.info("=== Original Scenario ===") logging.info(scenario) text = scenario.replace("SCENARIO: ", "") try: i = 0 while True: messages= [ {"role": "system", "content": "You are writing concrete scenarios from text generated by another LLM."}, {"role": "user", "content": sys_info}, {"role": "user", "content": f"{text}\nWrite a more concrete and detailed version of the above type of scenario. Definition of concreteness: {rai_guide.concrete_def}\nAlso, make the story more severe and contain more intense harm. Definition of severity: {rai_guide.severity_def}\n{'Consider the following feedback when revising the scenario: ' + feedback if feedback else ''}\nThen, shorten it to a paragraph. \nFormat your response as: Only output the shortened scenario."} ] v2 = chat(gpt4, messages) logging.info(f"Concrete Version -> {v2}") rsp = chat(gpt3, [{"role": "system", "content": "You are evaluating stories generated by another LLM."}, {"role": "user", "content": f"{v2}\nDoes the text above sound like a concrete story? \n{rai_guide.concrete_def}\nRespond with either YES or NO."}]) is_story = rsp logging.info(f"Is Story? -> {is_story}") if "YES" in is_story or i > 3: return (v2, stakeholder) i+=1 except Exception as e: logging.warning(str(e)) return str(e) revised_scenarios = [] with ThreadPoolExecutor(max_workers=5) as executor: results = [executor.submit(refine_helper, scenario) for scenario in scenarios_sampled] for future in as_completed(results): revised_scenarios.append(future.result()) logging.info("======== Revised Scenarios ========") logging.info(revised_scenarios) return revised_scenarios def select_final_scenarios(revised_scenarios, goal): """ Step 5 in Pipeline - Pick Final Scenario 1. Ask the llm to return the indexes of 2 diverse scenarios that are the most severe, surprising, concrete, and relevant. 2. If the llm response is invalid / not parsable, pick 2 random scenarios 3. Return both the picked scenarios and the unpicked scenarios (for further processing and displaying if requested) """ logging.info("======== Picking Final Scenarios ... ========") def pick_scenario_helper(cluster): messages=[{"role": "system", "content": "You are evaluating stories generated by another LLM."}, {"role": "user", "content": f""" {cluster} For the scenarios above, please select two diverse scenarios that are the most severe, surprising, concrete, and relevant to the context. The qualities are defined as: {rai_guide.severity_def} {rai_guide.surprising_def} {rai_guide.concrete_def} {rai_guide.relevant_def} {rai_guide.diversity_def} Respond strictly with only the numbers of the scenario, separated with a comma."""}] rsp = chat(gpt4, messages) try: s1,s2 = rsp.split(',')[:2] s1,s2 = int(re.sub(r'\D', '', s1)), int(re.sub(r'\D', '', s2)) if 0 <= s1 < len(cluster) and 0 <= s2 < len(cluster): return s1, s2 return except: print("Pick scenario index error") random_integers = random.sample(range(0, len(cluster)+1), 2) return random_integers[0], random_integers[1] sentences = [] for i, (rs, stakeholder) in enumerate(revised_scenarios): sentences.append((f"{i}. {rs}", stakeholder)) s1,s2 = pick_scenario_helper([sent[0] for sent in sentences]) logging.info(f"chosen scenarios: {s1}, {s2}") unpicked_scenarios = [s for i, s in enumerate(sentences) if i not in (s1, s2)] return [sentences[s1], sentences[s2]], unpicked_scenarios def remove_correctives(picked_scenarios): """ Helper function for removing corrective measures from the scenarios. """ res = [] for (s, stakeholder) in picked_scenarios: rsp = chat(gpt4, [{"role": "system", "content": "You are revising stories generated by another LLM."}, {"role": "user", "content": f"{s}\n Remove any corrective measures or suggestions for the tool."}]) res.append((rsp, stakeholder)) return res def generate_heading(scenario): """ Helper function for generating a heading for a scenario. """ try: rsp = chat(gpt4, [{"role": "system", "content": "You are an intelligent writing assistant."}, {"role": "user", "content": f"{scenario}\nsummarize the above story into an one sentence heading. Format your response as: only the generated heading"}]) return rsp except Exception as e: print(str(e)) return "Error" def duration(diff): """ Helper function for converting time difference to a readable format. """ return time.strftime("%H:%M:%S", time.gmtime(diff)) def stakeholder_list_helper(stakeholders): """ Deprecated function for converting the stakeholder string to a list. """ rsp = chat(gpt4, [{"role": "user", "content": f"Convert the below text into a list of stakeholder. Format: string of comma seperated list. Example: user1,user2,...\nText:{stakeholders}"}]) return rsp.split(",") def log_helper(message, start_time=None): """ Helper function for logging critical messages and duration. """ if start_time: print(f"{message} - {duration(time.time() - start_time)}") logging.critical(f"{message} - {duration(time.time() - start_time)}") else: logging.critical(f"{message}") def generate_scenarios(sys_info, goal, given_stakeholders=None, feedback=None): """ Primary function, combining all the steps in the pipeline, to generate scenarios. Directly called by the backend service. """ if goal not in ['f1', 'f2', 'f3']: return "Invalid Goal" logging.critical(f"==== Generating {goal} scenarios for the following scenario: ====") logging.critical(sys_info) # Step 1: Generate Stakeholders start = time.time() if given_stakeholders: logging.info(given_stakeholders) stakeholders = given_stakeholders else: stakeholders = stakeholder_list_helper(get_stakeholders(sys_info)) log_helper("Stakeholder Generated", start) logging.info(stakeholders) # Step 2: Generate Initial Scenarios - (a) Consider demographic groups & (b) Use the first response as counterexample for surprising start = time.time() initial_scenarios = get_initial_scenarios(stakeholders, goal, sys_info) log_helper("Initial Scenarios Generated", start) # Step 3: Clustering + Sampling start = time.time() scenarios_sampled = sampling(initial_scenarios) log_helper("Finished Clustering & Sampling", start) # Step 4: Refinement for Concreteness & Severity start = time.time() scenarios = refine_scenarios(scenarios_sampled, sys_info, feedback) log_helper("Finished Revising Scenarios", start) # Step 5: Pick Final Scenario start = time.time() picked_scenarios, unpicked_scenarios = select_final_scenarios(scenarios, goal) final_scenarios = remove_correctives(picked_scenarios) logging.critical(f"==== Final Scenarios - {duration(time.time() - start)} ====") scenario_heading_list = [ (generate_heading(scenario) + f" (Stakeholder: {stakeholder})", re.sub(r'^\d+\.\s*', '', scenario.strip()).strip()) for (scenario, stakeholder) in final_scenarios ] # result = format_scenario_result(scenario_heading_list) print(scenario_heading_list) logging.critical(scenario_heading_list) return scenario_heading_list, unpicked_scenarios
package org.example.controller; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServlet; import org.example.dto.Product; import org.example.framework.CustomControllerAnnotation; import org.example.service.ProductService; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @CustomControllerAnnotation(path = "/products") public class ProductController extends HttpServlet { private ProductService productService; private final ObjectMapper objectMapper; public ProductController() { this.objectMapper = new ObjectMapper(); } public void setProductService(ProductService productService) { this.productService = productService; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); if (pathInfo == null || pathInfo.equals("/")) { List<Product> products = productService.getAllProducts(); resp.setContentType("application/json"); resp.getWriter().write(objectMapper.writeValueAsString(products)); } else { try { int id = Integer.parseInt(pathInfo.substring(1)); Product product = productService.getProductById(id); if (product == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } else { resp.setContentType("application/json"); resp.getWriter().write(objectMapper.writeValueAsString(product)); } } catch (NumberFormatException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Product product = objectMapper.readValue(req.getInputStream(), Product.class); Product createdProduct = productService.addProduct(product); resp.setContentType("application/json"); resp.getWriter().write(objectMapper.writeValueAsString(createdProduct)); resp.setStatus(HttpServletResponse.SC_CREATED); } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Product product = objectMapper.readValue(req.getInputStream(), Product.class); Product updatedProduct = productService.updateProduct(product); resp.setContentType("application/json"); resp.getWriter().write(objectMapper.writeValueAsString(updatedProduct)); } }
#!/usr/bin/python3 """ This module is a definition of a FileStorage class.""" import os import datetime import json class FileStorage: """ This class represents the class for storing and retrieving data""" __file_path = "file.json" __objects = {} def all(self): """ This method returns the dictionary __objects""" return FileStorage.__objects def new(self, obj): """This method sets in __objects the obj with <obj class name>.id""" obj_key = "{}.{}".format(type(obj).__name__, obj.id) FileStorage.__objects[obj_key] = obj def save(self): """This method serializes __objects to JSON file (path: __file_path)""" with open(FileStorage.__file_path, "w", encoding="utf-8") as f: serialized_obj = { key: value.to_dict() for key, value in FileStorage.__objects.items() } json.dump(serialized_obj, f) def classes(self): """This method returns a valid classes dict &their respective refr""" from models.base_model import BaseModel from models.user import User from models.state import State from models.city import City from models.amenity import Amenity from models.place import Place from models.review import Review classes = {"BaseModel": BaseModel, "User": User, "State": State, "City": City, "Amenity": Amenity, "Place": Place, "Review": Review} return classes def reload(self): """ This method reloads the objects that have been stored """ if not os.path.isfile(FileStorage.__file_path): return with open(FileStorage.__file_path, "r", encoding="utf-8") as f: serialized_obj = json.load(f) serialized_obj = { key: self.classes()[value["__class__"]](**value) for key, value in serialized_obj.items() } FileStorage.__objects = serialized_obj def attributes(self): """This method returns valid attributes & their types for class name""" base_model_attrs = { "id": str, "created_at": datetime.datetime, "updated_at": datetime.datetime } user_attrs = { "email": str, "password": str, "first_name": str, "last_name": str } state_attrs = { "name": str } city_attrs = { "state_id": str, "name": str } amenity_attrs = { "name": str } place_attrs = { "city_id": str, "user_id": str, "name": str, "description": str, "number_rooms": int, "number_bathrooms": int, "max_guest": int, "price_by_night": int, "latitude": float, "longitude": float, "amenity_ids": list } review_attrs = { "place_id": str, "user_id": str, "text": str } attributes = { "BaseModel": base_model_attrs, "User": user_attrs, "State": state_attrs, "City": city_attrs, "Amenity": amenity_attrs, "Place": place_attrs, "Review": review_attrs } return attributes
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2010-2011 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * http://glassfish.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package com.sun.jersey.oauth.tests; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import junit.framework.Assert; import com.sun.jersey.api.core.HttpContext; import com.sun.jersey.oauth.server.OAuthServerRequest; import com.sun.jersey.oauth.signature.OAuthParameters; import com.sun.jersey.oauth.signature.OAuthSecrets; import com.sun.jersey.oauth.signature.OAuthSignature; import com.sun.jersey.oauth.signature.OAuthSignatureException; @Path("/request_token") public class RequestTokenResource extends Assert { @POST @Produces("text/plain") public String handle(@Context HttpContext hc) { OAuthServerRequest osr = new OAuthServerRequest(hc.getRequest()); OAuthSecrets secrets = new OAuthSecrets().consumerSecret("kd94hf93k423kf44"); OAuthParameters params = new OAuthParameters().readRequest(osr); // ensure parameters correctly parsed into OAuth parameters object assertEquals(params.getConsumerKey(), "dpf43f3p2l4k3l03"); assertEquals(params.getSignatureMethod(), "PLAINTEXT"); assertEquals(params.getSignature(), secrets.getConsumerSecret() + "&"); assertEquals(params.getTimestamp(), "1191242090"); assertEquals(params.getNonce(), "hsu94j3884jdopsl"); assertEquals(params.getVersion(), "1.0"); try { // verify the plaintext signature assertTrue(OAuthSignature.verify(osr, params, secrets)); } catch (OAuthSignatureException ose) { fail(ose.getMessage()); } return "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03"; } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateAdminsPermissionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create( 'admins_permissions', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('admin_id')->unsigned()->index(); $table->foreign('admin_id')->references('id')->on('admins')->onDelete('cascade'); $table->unsignedBigInteger('permission_id')->unsigned()->index(); $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade'); $table->timestamps(); $table->softDeletes(); } ); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('admins_permissions'); } }
package net.mrmidi.pmp.bank.ui.screens import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import net.mrmidi.pmp.bank.ui.components.PaymentListItem import net.mrmidi.pmp.bank.ui.components.showDatePickerDialog import net.mrmidi.pmp.bank.viewmodel.HomeViewModel import java.time.LocalDate import java.time.format.DateTimeFormatter @RequiresApi(Build.VERSION_CODES.O) // Required for LocalDate @Composable fun HomeScreen(homeViewModel: HomeViewModel = viewModel(), accountId: Int, navController: NavController) { val context = LocalContext.current val paymentHistory by homeViewModel.paymentHistory.collectAsState(initial = emptyList()) val currentBalance by homeViewModel.currentBalance.collectAsState(initial = "0.00") val selectedDate = remember { mutableStateOf<LocalDate?>(null) } val dateFormatter = remember { DateTimeFormatter.ofPattern("yyyy-MM-dd") } val (selectedType, setSelectedType) = remember { mutableStateOf("All") } LaunchedEffect(Unit) { println("Fetching payment history for account: $accountId") homeViewModel.fetchPaymentHistory(accountId) } Column(modifier = Modifier.fillMaxSize().padding(16.dp)) { // Balance and Buttons Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { // add padding to the elements Button(onClick = { /* Navigate to New Payment */ println("Navigating to New Payment") // Open the New Payment screen navController.navigate("payment/$accountId") }) { Text("New Payment") } Button(onClick = { /* Navigate to QR Payment */ }) { Text("QR Payment") } } Spacer(modifier = Modifier.height(16.dp)) // Add a spacer for better separation Text( text = "Balance: $currentBalance", style = MaterialTheme.typography.headlineMedium, modifier = Modifier.padding(vertical = 8.dp) ) Spacer(modifier = Modifier.height(16.dp)) // Add a spacer for better separation // Date and Type Filter Column(modifier = Modifier.fillMaxSize().padding(16.dp)) { // Date Picker Button Button(onClick = { showDatePickerDialog(context) { date -> selectedDate.value = date } }) { Text(text = selectedDate.value?.format(dateFormatter) ?: "Select Date") } // Payment Type Toggle Row { ToggleButton( text = "All", isSelected = selectedType == "All", onClick = { setSelectedType("All") }, modifier = Modifier.padding(end = 3.dp) // Add padding to the end (right) of the button ) ToggleButton( text = "Withdrawals", isSelected = selectedType == "Withdrawal", onClick = { setSelectedType("Withdrawal") }, modifier = Modifier.padding(horizontal = 3.dp) // Add padding horizontally around the button ) ToggleButton( text = "Deposits", isSelected = selectedType == "Deposit", onClick = { setSelectedType("Deposit") }, modifier = Modifier.padding(start = 3.dp) // Add padding to the start (left) of the button ) } Row { // Apply Filters Button Button(onClick = { // Implement filter application logic here // For example: homeViewModel.fetchFilteredData(accountId, selectedDate, selectedType) println("Applying filters for account: $accountId)") println("Selected date: ${selectedDate.value?.format(dateFormatter)}") println("Selected type: $selectedType") homeViewModel.fetchPaymentHistory(accountId, selectedDate.value?.format(dateFormatter), selectedType.lowercase()) }) { Text("Apply Filters") } // cancel Filters Button Button(onClick = { // Implement filter application logic here // For example: homeViewModel.fetchFilteredData(accountId, selectedDate, selectedType) println("Cancel filters for account: $accountId)") println("Selected date: ${selectedDate.value?.format(dateFormatter)}") println("Selected type: $selectedType") homeViewModel.fetchPaymentHistory(accountId) }) { Text("Cancel Filters") } } // Payment List LazyColumn(modifier = Modifier.padding(vertical = 8.dp).fillMaxSize()) { items(items = paymentHistory, itemContent = { operation -> PaymentListItem( operation = operation, accountId = accountId, onItemClick = { _, _ -> // Handle item click println("Clicked on operation: ${operation.operation_id} for account: $accountId") }) }) } } } } @Composable fun ToggleButton(text: String, isSelected: Boolean, onClick: () -> Unit, modifier: Modifier) { Button( modifier = modifier, onClick = onClick, colors = ButtonDefaults.buttonColors( containerColor = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.secondary, contentColor = MaterialTheme.colorScheme.onPrimary ) ) { Text(text = text) } } // //@RequiresApi(Build.VERSION_CODES.O) // Required for LocalDate ////@Composable //fun showDatePickerDialog(context: Context, onDateSelected: (LocalDate) -> Unit) { // val current = LocalDate.now() // android.app.DatePickerDialog( // context, // { _, year, month, dayOfMonth -> // val selectedDate = LocalDate.of(year, month + 1, dayOfMonth) // onDateSelected(selectedDate) // }, // current.year, // current.monthValue - 1, // current.dayOfMonth // ).show() //} //
import type { GetServerSideProps, NextPage } from "next"; import { CommonLandingCustomSettings } from "service/landing-page"; import useTranslation from "next-translate/useTranslation"; import Navbar from "components/common/Navbar"; import { parseCookies } from "nookies"; import { useEffect } from "react"; import Footer from "components/common/footer"; import { useSelector } from "react-redux"; import { RootState } from "state/store"; import { SEO } from "components/SEO"; import UnAuthNav from "components/common/unAuthNav"; import Cover from "components/Homepage/Cover"; import SliderSection from "components/Homepage/SliderSection"; import MarketTrends from "components/Homepage/MarketTrends"; import DistributionSection from "components/Homepage/DistributionSection"; import BottomDetails from "components/Homepage/BottomDetails"; import GetInTouch from "components/Homepage/GetInTouch"; import StartTradingNow from "components/Homepage/StartTradingNow"; import CommunityHome from "components/community/CommunityHome"; const Home: NextPage = ({ landing, bannerListdata, announcementListdata, featureListdata, asset_coin_pairs, hourly_coin_pairs, latest_coin_pairs, loggedin, landing_banner_image, customSettings, }: any) => { const { settings: common } = useSelector((state: RootState) => state.common); useEffect(() => { //@ts-ignore window.$crisp = []; //@ts-ignore // window.CRISP_WEBSITE_ID = process.env.NEXT_PUBLIC_CRISP_ID; window.CRISP_WEBSITE_ID = common.live_chat_key; // live_chat_key (function () { //@ts-ignore if (common.live_chat_status == "1") { var d = document; var s = d.createElement("script"); s.src = "https://client.crisp.chat/l.js"; //@ts-ignore s.async = 1; d.getElementsByTagName("head")[0].appendChild(s); } })(); }, [common.live_chat_status]); return ( <SEO seoData={customSettings}> <div> <div> {loggedin ? ( <Navbar settings={customSettings} isLoggedIn={loggedin} /> ) : ( <UnAuthNav /> )} <> <Cover landing={landing} loggedin={loggedin} landing_banner_image={landing_banner_image} /> <SliderSection bannerListdata={bannerListdata} landing={landing} announcementListdata={announcementListdata} /> <MarketTrends landing={landing} asset_coin_pairs={asset_coin_pairs} hourly_coin_pairs={hourly_coin_pairs} latest_coin_pairs={latest_coin_pairs} /> {/* community section start*/} {common?.blog_news_module == "1" && <CommunityHome />} {/* community section end*/} <DistributionSection landing={landing} /> <BottomDetails landing={landing} /> {/* Trade. Anywhere. area end here */} {/* Get in touch. area start here */} <GetInTouch landing={landing} featureListdata={featureListdata} /> {/* Get in touch. area end here */} {/* Start trading area start here */} <StartTradingNow landing={landing} loggedin={loggedin} /> </> {/* Start trading area end here */} {/* footer area start here */} <Footer /> <a id="scrollUp" href="#top" style={{ position: "fixed", zIndex: 2147483647, display: "none" }} > <i className="fa fa-angle-up" /> </a> <div id="vanillatoasts-container" /> </div> </div> </SEO> ); }; export const getServerSideProps: GetServerSideProps = async (ctx: any) => { const { data: CommonLanding } = await CommonLandingCustomSettings(ctx.locale); const cookies = parseCookies(ctx); return { props: { customPageData: CommonLanding?.custom_page_settings ? CommonLanding?.custom_page_settings : null, socialData: CommonLanding?.landing_settings?.media_list ? CommonLanding?.landing_settings?.media_list : null, copyright_text: CommonLanding?.landing_settings?.copyright_text ? CommonLanding?.landing_settings?.copyright_text : null, landing: CommonLanding?.landing_settings, bannerListdata: CommonLanding?.landing_settings?.banner_list ? CommonLanding?.landing_settings.banner_list : null, announcementListdata: CommonLanding?.landing_settings?.announcement_list ? CommonLanding?.landing_settings?.announcement_list : null, featureListdata: CommonLanding?.landing_settings?.feature_list ? CommonLanding?.landing_settings?.feature_list : null, asset_coin_pairs: CommonLanding?.landing_settings?.asset_coin_pairs ? CommonLanding?.landing_settings?.asset_coin_pairs : null, hourly_coin_pairs: CommonLanding?.landing_settings?.hourly_coin_pairs ? CommonLanding?.landing_settings?.hourly_coin_pairs : null, latest_coin_pairs: CommonLanding?.landing_settings?.latest_coin_pairs ? CommonLanding?.landing_settings?.latest_coin_pairs : null, loggedin: cookies?.token ? true : false, landing_banner_image: CommonLanding?.landing_settings ?.landing_banner_image ? CommonLanding?.landing_settings?.landing_banner_image : null, customSettings: CommonLanding?.common_settings, }, }; }; export default Home;
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:gamingnews/firebase_options.dart'; import 'screen/screen.dart'; late FirebaseApp app; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); app = await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Gaming News App', theme: ThemeData( primarySwatch: Colors.grey, useMaterial3: true, ), initialRoute: '/', routes: { Home_Screen.routeName: (context) => const Home_Screen(), Discover_Screen.routeName: (context) => const Discover_Screen(), Article_Screen.routeName: (context) => const Article_Screen(), Profile_screen.routeName: (context) => const Profile_screen(), LogReg_Screen.routeName: (context) => const LogReg_Screen(), Login_Screen.routeName: (context) => const Login_Screen(), Register_Screen.routeName: (context) => const Register_Screen(), OnBoard_Screen.routeName: (context) => const OnBoard_Screen(), }, ); } }
import * as admin from "firebase-admin"; import * as vscode from 'vscode'; export abstract class Item extends vscode.TreeItem { abstract reference: admin.firestore.DocumentReference | admin.firestore.CollectionReference; } /** * A Tree View item representing a Firestore document. */ export class DocumentItem extends Item { constructor( public documentId: string, public reference: admin.firestore.DocumentReference, public size: number | undefined = undefined, ) { super(documentId, vscode.TreeItemCollapsibleState.None); this.command = { command: "firestore-explorer.openPath", title: "Open", arguments: [reference.path] }; this.id = reference.path; this.contextValue = 'document'; this.tooltip = reference.path; this.iconPath = new vscode.ThemeIcon("file"); this.collapsibleState = size === 0 ? vscode.TreeItemCollapsibleState.None : vscode.TreeItemCollapsibleState.Collapsed; } withSize(size: number): DocumentItem { return new DocumentItem(this.documentId, this.reference, size); } } /** * A Tree View item representing a Firestore collection. */ export class CollectionItem extends Item { constructor( public collectionId: string, public reference: admin.firestore.CollectionReference, public orderBy: { fieldName: string, direction: admin.firestore.OrderByDirection } = { fieldName: 'id', direction: 'asc' }, public size: number | undefined = undefined, ) { super(collectionId, vscode.TreeItemCollapsibleState.Collapsed); this.id = reference.path; this.contextValue = 'collection'; this.tooltip = reference.path; this.iconPath = new vscode.ThemeIcon("folder"); this.collapsibleState = size === 0 ? vscode.TreeItemCollapsibleState.None : vscode.TreeItemCollapsibleState.Collapsed; this.description = (orderBy.direction === 'asc' ? '↑' : '↓') + orderBy.fieldName; } withSize(size: number): CollectionItem { return new CollectionItem(this.collectionId, this.reference, this.orderBy, size); } } /** * A Tree View item representing the "Show more" button */ export class ShowMoreItemsItem extends Item { reference: admin.firestore.CollectionReference; offset: number; constructor(reference: admin.firestore.CollectionReference, offset: number) { const pagingLimit = vscode.workspace.getConfiguration().get("firestore-explorer.pagingLimit") as number; super(`Load ${pagingLimit} more`, vscode.TreeItemCollapsibleState.None,); this.reference = reference; this.id = reference.path + "///showMore"; this.offset = offset; this.iconPath = new vscode.ThemeIcon("more"); this.command = { command: "firestore-explorer.showMoreItems", title: "More Items", arguments: [reference.path] }; } // TODO: Show progress animation when loading more items }