text
stringlengths
184
4.48M
import GeoThailandAPI from "./GeoThailandAPI"; import WeatherDTO from "./WeatherDTO"; import kelvinToCelcius from "./kelvinToCelcius"; export default class WeatherAPI { #geoAPI; #apiKey; constructor() { this.#geoAPI = new GeoThailandAPI(); this.#apiKey = process.env.OPENWEATHER_API_KEY; } async fetchDataByCityName(name) { await this.#geoAPI.fetchDataByCityName(name); const lat = this.#geoAPI.getLat(); const lon = this.#geoAPI.getLon(); return this.fetchDataByLatAndLon(lat, lon) } async fetchDataByLatAndLon(lat, lon) { const url = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${this.#apiKey}`; const response = await fetch(url, { type: "cors" }); const data = await response.json(); const rawDataArray = data.list; return rawDataArray; } }
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2015 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.coeus.propdev.impl.attachment; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang3.StringUtils; import org.kuali.coeus.propdev.impl.core.ProposalDevelopmentDocument; import org.kuali.coeus.propdev.impl.core.ProposalDevelopmentDocumentForm; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.infrastructure.Constants; import org.kuali.coeus.propdev.impl.core.DevelopmentProposal; import org.kuali.coeus.propdev.impl.s2s.S2sOppForms; import org.kuali.rice.core.api.criteria.QueryByCriteria; import org.kuali.rice.core.api.exception.RiceRuntimeException; import org.kuali.rice.core.api.util.ConcreteKeyValue; import org.kuali.rice.core.api.util.KeyValue; import org.kuali.rice.coreservice.framework.parameter.ParameterService; import org.kuali.rice.krad.data.DataObjectService; import org.kuali.rice.krad.uif.control.UifKeyValuesFinderBase; import org.kuali.rice.krad.uif.field.InputField; import org.kuali.rice.krad.uif.view.ViewModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import java.util.*; /** * Finds the available set of supported Narrative Types. See * the method <code>getKeyValues()</code> for a full description. * * @author KRADEV team * * Rewrite of class to implement filterable KeyValue list. * * A complete rewrite had to be done because super class was not editable, but the patterns used * here should be incorporated into super class. This class would then be refactored to again rely * more on super class behavior. Super class rewrite should include isolating behaviors relying on * infrastructure into protected methods to allow unit tests to override with mocks and stub out * database and service lookups. */ public class ProposalNarrativeTypeValuesFinder extends UifKeyValuesFinderBase { private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(ProposalNarrativeTypeValuesFinder.class); public static final String NARRATIVE_TYPE_GROUP = "narrativeTypeGroup"; public static final String PROPOSAL_NUMBER = "proposalNumber"; public static final String FORM_NAME = "formName"; public static final String ALL = "ALL"; public static final String SELECT = "select"; @Autowired @Qualifier("dataObjectService") private DataObjectService dataObjectService; @Autowired @Qualifier("parameterService") private ParameterService parameterService; @Override public List<KeyValue> getKeyValues(ViewModel model, InputField field){ DevelopmentProposal developmentProposal = ((ProposalDevelopmentDocumentForm) model).getDevelopmentProposal(); Collection<NarrativeType> allNarrativeTypes = loadAllNarrativeTypes(developmentProposal); String narrativeTypeCode = ""; try { narrativeTypeCode = (String) PropertyUtils.getProperty(model, field.getBindingInfo().getBindingPath()); if (StringUtils.isNotEmpty(narrativeTypeCode)) { NarrativeType currentNarrativeType = getDataObjectService().find(NarrativeType.class,narrativeTypeCode); if (currentNarrativeType != null) { if (!allNarrativeTypes.contains(currentNarrativeType)) { allNarrativeTypes.add(currentNarrativeType); } } } } catch (Exception e) { throw new RiceRuntimeException("could not retrieve narrative type from the input field", e); } return getFilteredKeyValues(allNarrativeTypes, developmentProposal, narrativeTypeCode); } @Override public List<KeyValue> getKeyValues(ViewModel model) { DevelopmentProposal developmentProposal = ((ProposalDevelopmentDocumentForm) model).getDevelopmentProposal(); Collection<NarrativeType> allNarrativeTypes = loadAllNarrativeTypes(developmentProposal); return getFilteredKeyValues(allNarrativeTypes, developmentProposal, ""); } public List<KeyValue> getFilteredKeyValues(Collection<NarrativeType> allNarrativeTypes, DevelopmentProposal developmentProposal, String narrativeTypeCode) { Collection<NarrativeType> filteredCollection = filterCollection(allNarrativeTypes, developmentProposal, narrativeTypeCode); return buildKeyValuesCollection(filteredCollection); } protected Collection<NarrativeType> filterCollection(Collection<NarrativeType> narrativeTypes, DevelopmentProposal developmentProposal, String narrativeTypeCode) { Collection<NarrativeType> forRemoval = new ArrayList<>(); for (NarrativeType narrativeType : narrativeTypes) { for (Narrative narrative : developmentProposal.getNarratives()) { if (narrative.getNarrativeType() != null && filterCondition(narrative.getNarrativeType(), narrativeType) && !narrative.getNarrativeTypeCode().equals(narrativeTypeCode)) { forRemoval.add(narrativeType); } else { LOG.debug("Not removing narrative type " + narrativeType.getDescription()); } } } // Remove any instances for with these type codes already in the document narrativeTypes.removeAll(forRemoval); return narrativeTypes; } private List<KeyValue> buildKeyValuesCollection(Collection<NarrativeType> narrativeTypes) { List<KeyValue> KeyValues = new ArrayList<KeyValue>(); KeyValues.add(new ConcreteKeyValue(StringUtils.EMPTY, SELECT)); for (NarrativeType narrativeType : narrativeTypes) { String key = narrativeType.getCode(); String label = narrativeType.getDescription(); KeyValues.add(new ConcreteKeyValue(key, label)); } return KeyValues; } protected Collection<NarrativeType> loadAllNarrativeTypes(DevelopmentProposal developmentProposal) { List<NarrativeType> narrativeTypes = new ArrayList<>(); if(isS2sCandidate(developmentProposal)) { narrativeTypes.addAll(populateNarrativeTypesFrom(developmentProposal)); } else if (developmentProposal.isChild()) { narrativeTypes.addAll(populateNarrativeTypesFromParent(developmentProposal.getHierarchyParentProposalNumber())); } narrativeTypes.addAll(populateDefaultNarrativeForms()); return narrativeTypes; } private Collection<NarrativeType> populateNarrativeTypesFromParent(String hierarchyProposalNumber) { List<NarrativeType> validS2SFormNarratives = new ArrayList<>(); DevelopmentProposal parentProposal = getDevelopmentProposal(hierarchyProposalNumber); if (isS2sCandidate(parentProposal)) { validS2SFormNarratives.addAll(populateNarrativeTypesFrom(parentProposal)); } return validS2SFormNarratives; } public DevelopmentProposal getDevelopmentProposal(String proposalNumber) { return getDataObjectService().find(DevelopmentProposal.class,proposalNumber); } private boolean isS2sCandidate(DevelopmentProposal developmentProposal) { return !developmentProposal.getS2sOppForms().isEmpty(); } private List<NarrativeType> populateNarrativeTypesFrom(DevelopmentProposal developmentProposal) { List<NarrativeType> validNarrativeTypes = new ArrayList<>(); validNarrativeTypes.addAll(populateValidFormNarratives(developmentProposal)); return validNarrativeTypes; } private List<NarrativeType> populateDefaultNarrativeForms() { Map<String,String> queryMap = new HashMap<>(); queryMap.put(NARRATIVE_TYPE_GROUP, getProposalNarrativeTypeGroup()); List<ValidNarrForms> validNarrativeForms = getDataObjectService().findAll(ValidNarrForms.class).getResults(); List<NarrativeType> narrativeTypes = getDataObjectService().findMatching(NarrativeType.class, QueryByCriteria.Builder.andAttributes(queryMap).build()).getResults(); List<NarrativeType> filteredNarrativeTypes = populateGenericValidNarrativeTypes(); for (NarrativeType narrativeType : narrativeTypes) { if(!validNarrFormAlreadyExists(validNarrativeForms, narrativeType)){ filteredNarrativeTypes.add(narrativeType); } } return filteredNarrativeTypes; } private boolean validNarrFormAlreadyExists(List<ValidNarrForms> validNarrativeForms, NarrativeType narrativeType) { for (ValidNarrForms validNarrForm : validNarrativeForms) { if(validNarrForm.getNarrativeTypeCode().equals(narrativeType.getCode())){ return true; } } return false; } private List<NarrativeType> populateValidFormNarratives(DevelopmentProposal developmentProposal) { List<NarrativeType> validNarrativeTypes = new ArrayList<>(); List<S2sOppForms> s2sOpportunityForms = developmentProposal.getS2sOppForms(); for (S2sOppForms oppForms : s2sOpportunityForms) { Map<String, String> queryMap = new HashMap<>(); queryMap.put(FORM_NAME, oppForms.getFormName()); List<ValidNarrForms> validNarrativeForms = getDataObjectService().findMatching(ValidNarrForms.class,QueryByCriteria.Builder.andAttributes(queryMap).build()).getResults(); for (ValidNarrForms validNarrForms : validNarrativeForms) { if(isProposalGroup(validNarrForms.getNarrativeType().getNarrativeTypeGroup())){ if(!isNarrativeAlreadyAdded(validNarrativeTypes,validNarrForms.getNarrativeType()) && !validNarrForms.getNarrativeType().isSystemGenerated()){ validNarrativeTypes.add(validNarrForms.getNarrativeType()); } } } } return validNarrativeTypes; } private boolean isNarrativeAlreadyAdded(List<NarrativeType> validaNarrativeTypes, NarrativeType validNarrativeType) { for (NarrativeType narrativeType : validaNarrativeTypes) { if(narrativeType.getCode().equals(validNarrativeType.getCode())){ return true; } } return false; } private boolean isProposalGroup(String narrativeTypeCode) { return StringUtils.equals(narrativeTypeCode, getProposalNarrativeTypeGroup()); } private String getProposalNarrativeTypeGroup() { return getParameterService().getParameterValueAsString(ProposalDevelopmentDocument.class, Constants.PROPOSAL_NARRATIVE_TYPE_GROUP); } private List<NarrativeType> populateGenericValidNarrativeTypes() { List<NarrativeType> validNarrativeTypes = new ArrayList<>(); Map<String,String> queryMap = new HashMap<>(); queryMap.put(FORM_NAME, ALL); List<ValidNarrForms> validNarrativeForms = getDataObjectService().findMatching(ValidNarrForms.class, QueryByCriteria.Builder.andAttributes(queryMap).build()).getResults(); for (ValidNarrForms validNarrForms : validNarrativeForms) { if(isProposalGroup(validNarrForms.getNarrativeType().getNarrativeTypeGroup())){ validNarrativeTypes.add(validNarrForms.getNarrativeType()); } } return validNarrativeTypes; } protected boolean filterCondition(NarrativeType documentNarrativeType, NarrativeType narrativeType) { return documentNarrativeType.getCode().equals(narrativeType.getCode()) && multiplesNotAllowed(narrativeType); } private boolean multiplesNotAllowed(NarrativeType narrativeType) { return !narrativeType.isAllowMultiple(); } public ParameterService getParameterService() { if (parameterService == null) { parameterService = KcServiceLocator.getService(ParameterService.class); } return parameterService; } public void setParameterService(ParameterService parameterService) { this.parameterService = parameterService; } public DataObjectService getDataObjectService() { if (dataObjectService == null) { dataObjectService = KcServiceLocator.getService(DataObjectService.class); } return dataObjectService; } public void setDataObjectService(DataObjectService dataObjectService) { this.dataObjectService = dataObjectService; } }
<?php namespace App\Http\Controllers; use App\Models\clientes; use Illuminate\Http\Request; class cliente extends Controller { //create client public function createClient(Request $request) { $data = $request->validate($this->validateClient()); $client = clientes::create($data); return response([ 'Message'=> 'Client Created', 'id'=>$client['id'] ],201); } //get all clients public function getClients(){ $clients = clientes::all(); //$clients = clientes::paginate(10); return response($clients, 200); } //get only one client public function getClient($id){ $client = clientes::find($id); if($client != null){ return response($client, 200); } return response(['message' => "'Client not found'"], 404); } //get active chofers public function getClientesActivos(){ $clientes = clientes::where('status', '=', 1)->paginate(10); return response($clientes, 200); } //get inactive chofers public function getClientesInactivos(){ $clientes = clientes::where('status', '=', 0)->paginate(10); return response($clientes, 200); } //search like query public function lookForName($input){ $client = clientes::where('nombre', 'like', '%'.$input.'%')->paginate(10); if($client != null){ return response($client, 200); } return response(['message' => 'Clients not found'], 404); } //update a client public function updateClient($id, Request $request){ $client = clientes::find($id); if (!$client) { return response ([ 'message' => 'Client not found' ], 404); } $data = $request->validate($this->validateClient()); $client->update($data); return response([ 'message' => 'Client updated' ], 201); } //"eliminates" a client public function hideClient($id){ $client = clientes::find($id); if (!$client) { return response([ 'message' => 'Client with ID ' . $id . ' could not be found' ], 404); } $client->status = 0; if (!$client->save()) { return response ([ 'message' => 'Unexpected error' ], 500); }else{ return response([ 'message' => 'Client eliminated' ], 200); } } //real client elimination public function eliminateClient($id){ $client = clientes::find($id); if (!$client) { return response([ 'message' => 'Client with ID ' . $id . ' could not be found' ], 404); } $client->delete(); return response([ 'message' => 'Client eliminated' ]); } //client validation private function validateClient(){ return [ 'nombre'=>'required', 'rfc'=>'required' ]; } }
package matrix; import java.util.Iterator; import java.util.Optional; public final class PeekingIterator<T> implements Iterator<T> { private final Iterator<T> it; private Optional<T> next; private PeekingIterator(Iterator<T> iterator) { this.it = iterator; this.next = Optional.of(iterator.next()); } public static <T> PeekingIterator<T> from(Iterator<T> iterator) { return new PeekingIterator<>(iterator); } public static <T> PeekingIterator<T> from(Iterable<T> iterable) { return new PeekingIterator<>(iterable.iterator()); } @Override public boolean hasNext() { return next.isPresent(); } @Override public T next() { T value = next.get(); if(it.hasNext()) { next = Optional.of(it.next()); } else { next = Optional.empty(); } return value; } public Optional<T> peek() { if(!hasNext()) { return Optional.empty(); } return next; } public T element() { return next.get(); } }
import { Component, OnInit, ViewChild } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MatPaginator, PageEvent } from '@angular/material/paginator'; import { MatSnackBar } from '@angular/material/snack-bar'; import { MatTableDataSource } from '@angular/material/table'; import { VehicleTypesService } from 'src/app/dashboard/services/vehicle-types.service'; import { VehicleType } from 'src/app/models/VehicleType'; import { DeleteDialogComponent } from '../../dialogs/delete-dialog/delete-dialog.component'; @Component({ selector: 'app-list-vehicle-types', templateUrl: './list-vehicle-types.component.html', styleUrls: ['./list-vehicle-types.component.scss'] }) export class ListVehicleTypesComponent implements OnInit { filters: object = {}; isLoading: boolean = false; pageSizeOptions: number[] = [ 10, 25, 100 ]; displayedColumns: string[] = [ 'id', 'key', 'title', 'description', 'rate', 'createdAt', 'updatedAt', 'options', ]; dataSource: MatTableDataSource<VehicleType> = new MatTableDataSource<VehicleType>([]); @ViewChild(MatPaginator) paginator!: MatPaginator; constructor( private vehicleTypeService: VehicleTypesService, public dialog: MatDialog, private snackBar: MatSnackBar ) { } ngOnInit(): void { this.loadData() } applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.filters = {...this.filters, ...{ q: filterValue.trim().toLowerCase(), page: 1, }} this.loadData(this.filters) } pageChanged(event: PageEvent) { this.filters = {...this.filters, ...{ page: event.pageIndex + 1, per_page: event.pageSize, }} this.loadData(this.filters); } loadData(params: object = {}) { this.isLoading = true; this.vehicleTypeService.getAll(params) .subscribe((response) => { this.dataSource = new MatTableDataSource<VehicleType>(response.data.vehicle_types); this.paginator.pageIndex = response.data.meta.current_page - 1; this.paginator.length = response.data.meta.total; this.isLoading = false; }) } delete(id: number) { this.isLoading = true; this.vehicleTypeService.delete(id) .subscribe({ next: () => { this.snackBar.open('Tipo de vehículo eliminado correctamente.', 'Cerrar', { duration: 3000 }); }, error: () => { this.snackBar.open('Ocurrio un error al eliminar el tipo de vehículo.', 'Cerrar', { duration: 3000 }); } }); } openDeleteDialog(id: number) { const dialogRef = this.dialog.open(DeleteDialogComponent); dialogRef .afterClosed() .subscribe((confirmation: Boolean) => { if (confirmation) { this.delete(id) this.loadData() } }); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <script src="../../../webcomponentsjs/webcomponents-lite.js"></script> <script src="../../../web-component-tester/browser.js"></script> <link rel="import" href="../../pagination/view.html" /> </head> <body> <test-fixture id="pagination"> <template> <pagination-clab></pagination-clab> </template> </test-fixture> <script> describe('<pagination-clab>', function () { var pagination; beforeEach(function () { pagination = fixture('pagination'); }); context('Test Properties', function () { it('Default Properties', function (done) { expect(pagination.pages).to.be.an('array'); expect(pagination.currentPage).to.equal(1); done(); }); }); context('Test DOM Bindings', function () { it('Check pages', function (done) { var arr = ['#1', '#2', '#3', '#4', '#5', '#6', '#7', '#8']; pagination.pages = arr; setTimeout(function () { expect(pagination.querySelectorAll('.page').length).to.equal( arr.length ); done(); }, 150); }); it('Check currentPage', function (done) { var arr = ['#1', '#2', '#3', '#4', '#5', '#6', '#7', '#8']; pagination.pages = arr; pagination.currentPage = 3; setTimeout(function () { expect( pagination .querySelectorAll('.page') [3 - 1].classList.contains('active') ).to.equal(true); done(); }, 150); }); }); }); </script> </body> </html>
package com.yldbkd.www.seller.android.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import com.yldbkd.www.library.android.common.AppManager; import com.yldbkd.www.library.android.common.ToastUtils; import com.yldbkd.www.seller.android.R; import com.yldbkd.www.seller.android.fragment.LoginFragment; import com.yldbkd.www.seller.android.fragment.MainFragment; import com.yldbkd.www.seller.android.utils.Constants; import com.yldbkd.www.seller.android.utils.UserUtils; /** * 合伙人端首页页面Activity * <p/> * Created by linghuxj on 16/5/25. */ public class MainActivity extends BaseActivity { private boolean isDoubleExist = false; @Override Fragment newFragmentByTag(String tag) { return new MainFragment(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!UserUtils.isLogin()) { Intent intent = new Intent(this, LoginActivity.class); intent.setAction(LoginFragment.class.getSimpleName()); startActivityForResult(intent, Constants.RequestCode.LOGIN_CODE); return; } setCustomContentView(R.layout.activity_common); showFragment(getIntent().getAction(), getIntent().getExtras(), false); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constants.RequestCode.LOGIN_CODE && resultCode == Activity.RESULT_OK) { setCustomContentView(R.layout.activity_common); showFragment(getIntent().getAction(), getIntent().getExtras(), false); } } @Override public void onBackPressed() { if (isDoubleExist) { AppManager.getAppManager().appExit(); return; } isDoubleExist = true; ToastUtils.show(this, getString(R.string.double_exit_notify)); new Handler().postDelayed(new Runnable() { @Override public void run() { isDoubleExist = false; } }, 2000); } }
import { Component } from '@angular/core'; @Component({ selector: '<%= selector %>', <% if(inlineTemplate) { %>template: ` <dw-checkbox-group [(ngModel)]="checkOptionsOne" (ngModelChange)="log(checkOptionsOne)"></dw-checkbox-group> <br> <br> <dw-checkbox-group [(ngModel)]="checkOptionsTwo" (ngModelChange)="log(checkOptionsTwo)"></dw-checkbox-group> <br> <br> <dw-checkbox-group [(ngModel)]="checkOptionsThree" (ngModelChange)="log(checkOptionsThree)"></dw-checkbox-group> `<% } else { %>templateUrl: './<%= dasherize(name) %>.component.html'<% } %> }) export class <%= classify(name) %>Component { checkOptionsOne = [ { label: 'Apple', value: 'Apple', checked: true }, { label: 'Pear', value: 'Pear' }, { label: 'Orange', value: 'Orange' } ]; checkOptionsTwo = [ { label: 'Apple', value: 'Apple' }, { label: 'Pear', value: 'Pear', checked: true }, { label: 'Orange', value: 'Orange' } ]; checkOptionsThree = [ { label: 'Apple', value: 'Apple', disabled: true, checked: true }, { label: 'Pear', value: 'Pear', disabled: true }, { label: 'Orange', value: 'Orange' } ]; log(value: object[]): void { console.log(value); } }
"use client"; import { ContractTransactionReceipt, Network, ethers } from "ethers"; import { createContext, useContext, useState ,useEffect } from "react"; import Web3Modal from "web3modal"; import { contractAbi,contractAddress } from "./constants"; const getContract = (type) => { const contract = new ethers.Contract(contractAddress,contractAbi,type); return contract; } export const Web3Context = createContext(); export const Web3Provider = ({children}) => { const [account , setAccount] = useState(); const [isConnected , setIsConnected] = useState(false) //create post,etc. functions const createPost = async (post) => { const {img,descr,id} = post; const web3modal = new Web3Modal(id,addr) const connection =await web3modal.connect() const provider =new ethers.BrowserProvider(connection) const signer =await provider.getSigner() const contract = getContract(signer); try { const transaction = await contract.createPost(id,account,img,descr) await transaction.wait() console.log("success", transaction); } catch (error) { console.log("fail",error); } } const getposts = async () => { const provider = new ethers.JsonRpcProvider() const contract = getContract(provider); const posts =await contract.userToPosts(account,1); console.log(posts); return posts; } const checkIfWalletConnected= async () =>{ try{ if (!window.ethereum) { return alert("Install metamask") } const accounts = await window.ethereum.request({method:"eth_accounts",}) if (accounts.length) { setAccount(accounts[0]) setIsConnected(true) }else{ setIsConnected(false) } }catch (error) { console.log(error); setIsConnected(false) } } const connect =async () =>{ try { if (window.ethereum == undefined) { setIsConnected(false) return alert('Install Metamask') } const accounts = await window.ethereum.request({method:"eth_requestAccounts",}) if (accounts.length) { setAccount(accounts[0]) setIsConnected(true) }else{ setIsConnected(false) } } catch (error) { setIsConnected(false) console.log(error); } } useEffect(()=>{ checkIfWalletConnected() },[]) return( <Web3Context.Provider value={{account,isConnected,createPost,getposts,connect}}> {children} </Web3Context.Provider> ) } export const useWeb3 = () => useContext(Web3Context);
import { ThumbsUp, Trash } from "phosphor-react"; import { useState } from "react"; import { Avatar } from "../Avatar"; import styles from "./Comment.module.css"; interface CommentProps { content: string; onDeleteComment: (content: string) => void; } export function Comment({ content, onDeleteComment }: CommentProps) { const [lineCount, setLineCount] = useState(0); function handleDeleteComment() { onDeleteComment(content); } function handleLikeComment() { setLineCount((state) => { return state + 1; }); } return ( <div className={styles.comment}> <Avatar hasBorder={false} src="https://avatars.githubusercontent.com/u/42882103?v=4" /> <div className={styles.commentBox}> <div className={styles.commentContent}> <header> <div className={styles.authorAndTime}> <strong>Tharyon Feitosa</strong> <time title="03 de junho às 03:27h" dateTime="2022-06-08 03:27:30"> Publicado há 1h </time> </div> <button onClick={handleDeleteComment} title="Deletar comentário"> <Trash size={20} /> </button> </header> <p>{content}</p> </div> <footer> <button onClick={handleLikeComment}> <ThumbsUp size={25} /> Aplaudir <span>{lineCount}</span> </button> </footer> </div> </div> ); }
<?php namespace App\Http\Controllers; use App\Models\posisi; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; class posisiController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $data = posisi::orderBy('tipe', 'asc')->get(); return view('dashboard.posisi.index')->with('data', $data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('dashboard.posisi.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { Session::flash('tipe', $request->tipe); Session::flash('nama', $request->nama); $request->validate( [ 'tipe' =>'required', 'nama' =>'required', ], [ 'nama.required' => 'Nama wajib diisi', 'tipe.required' => 'Tipe wajib diisi', ] ); $data = [ 'nama' => $request->nama, 'tipe' => $request->tipe, ]; posisi::create($data); return redirect()->route('posisi.index')->with('success', 'Berhasil menambahkan data'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $data = posisi::where('id', $id)->first(); return view('dashboard.posisi.edit')->with('data', $data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $data = posisi::where('id', $id)->first(); return view('dashboard.posisi.edit')->with('data', $data); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $request->validate( [ 'tipe' =>'required', 'nama' =>'required', ], [ 'nama.required' => 'Nama wajib diisi', 'tipe.required' => 'Tipe wajib diisi', ] ); $data = [ 'nama' => $request->nama, 'tipe' => $request->tipe, ]; posisi::where('id', $id)->update($data); return redirect()->route('posisi.index')->with('success', 'Berhasil mengupdate data'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { posisi::where('id', $id)->delete(); return redirect()->route('posisi.index')->with('success', 'Berhasil menghapus data'); } }
package org.example; public class Cat extends Animal { private String color; private Integer age; public Cat(String name, String color, Integer age) { this.name = name; this.color = color; if (age < 0) { System.out.println("данные введены некоректно"); } else { this.age = age; } } // можно еще так, если нейминг другой, то можно избавиться от слова this. // this дает просто пренадлежность к классу, программа понимает что к чему присоединяется, // когда ставим this программа понимает, // что нейм который находится внутри данного класса (public class Cat) // присвоить то поле, которое было подано как параметр (String name) // когда нейминг одинаковый джава не понимает как можно в передаваемый нейм положить этот же нейм. // public Cat(String name1, String color1, Integer age1) { // name = name1; // color = color1; // age = age1; // } public Cat() { this.name = "Kotik"; // предзадали значение, чтобы избежать NPE (ошибка связана с null) } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public Integer getAge() { return age; } public void setAge(Integer age) { // валидация if (age < 0) { System.out.println("данные введены некоректно"); } else { this.age = age; } } @Override public void voice() { System.out.println(name + " meooow!!"); } }
''' Feature: Achievements Functionalities: - check_achievement() - view_achievement() - view_connected_tm_achievement() - toggle_achievement_visibility() - share_achievement() ''' import time from firebase_admin import firestore from .helper import * db = firestore.client() ############################################################ # Achievement Functions # ############################################################ def check_achievement(a_type, uid): ''' Check to see if an achievement is able to be acquired If requirements are met, grant the achievement to the user - This will append the achievement id in the user's doc Arguments: - a_type (a string value to decipher the type of achievement) - uid (user id) Returns: - 0, if achievement is granted - 1 or err if not Raises: - InputError for any incorrect values ''' user_ref = db.collection("users").document(uid).get() if a_type == "task_completion": n_tasks = user_ref.get("num_tasks_completed") if n_tasks >= 3 and check_user_has_achievement(uid, 0) == False: give_achievement(uid, 0) elif n_tasks >= 5 and check_user_has_achievement(uid, 1) == False: give_achievement(uid, 1) else: return 1 elif a_type == "project_completion": n_projs = user_ref.get("num_projs_completed") if n_projs >= 3 and check_user_has_achievement(uid, 2) == False: give_achievement(uid, 2) elif n_projs >= 5 and check_user_has_achievement(uid, 3) == False: give_achievement(uid, 3) elif check_lone_wolf(uid) == True and check_user_has_achievement(uid, 6) == False: give_achievement(uid, 6) else: return 1 elif a_type == "connection": n_conns = len(db.collection("users").document(uid).get().get("connections")) print(f"this is uid in ach: {uid}") print(f"this is ncons: {n_conns}") print(f"this is list of connections: {db.collection('users').document(uid).get().get('connections')}") if n_conns >= 3 and check_user_has_achievement(uid, 4) == False: give_achievement(uid, 4) else: return 1 elif a_type == "task_assigned": n_assigned = len(db.collection("users").document(uid).get().get("tasks")) if n_assigned >= 8 and check_user_has_achievement(uid, 5) == False: give_achievement(uid, 5) else: return 1 elif a_type == "reputation": n_reviews = get_number_of_reviews_written(uid) if n_reviews >= 3 and check_user_has_achievement(uid, 7) == False: give_achievement(uid, 7) else: return 1 else: raise InputError(f"ERROR: Invalid achievement type specified {a_type}") return 0 def view_achievement(uid): ''' View the list of achievements Arguments: - uid (user id) Returns: - list of achievements, order by latest achieved achievement Raises: - None ''' check_valid_uid(uid) curr_achievements = db.collection("users").document(uid).get().get("achievements") return curr_achievements[::-1] def view_connected_tm_achievement(uid, conn_uid): ''' View a connected Task Master's achievements If the two users are connected and their visibility setting doesn't forbid, view achievements Arguments: - uid (user id) - conn_uid (uid to view their achievements) Returns: - list of achievements - err Raises: - AccessError if uid is not connected ''' user_ref = db.collection("users").document(uid).get() if conn_uid not in user_ref.get("connections"): raise AccessError("ERROR: uid is not connected") conn_user_ref = db.collection("users").document(conn_uid).get() hidden = conn_user_ref.get("hide_achievements") if hidden == True: return [] curr_achievements = db.collection("users").document(conn_uid).get().get("achievements") return curr_achievements[::-1] def toggle_achievement_visibility(uid, action): ''' Toggle on, or off the visibility of the user's achievements - if on, the achievements are only visible to the user Arguments: - uid (user id) - action (boolean) Returns: - None Raises: - InputError if attempt to toggle on when visibility if already on (True), or otherwise same for off ''' user_ref = db.collection("users").document(uid) hidden = user_ref.get().get("hide_achievements") if action == True and hidden == True: raise InputError("ERROR: Visibility is already toggled ON") elif action == False and hidden == False: raise InputError("ERROR: Visibility is already toggled OFF") if action == True: user_ref.update({"hide_achievements": True}) elif action == False: user_ref.update({"hide_achievements": False}) def share_achievement(uid, receiver_uids, aid): ''' Share an achievements a user has gotten, to other connected TMs - this is done through sending a notification to them Arguments: - uid (user id) - receiver_uids (uids to send) - aid (aid to be shared) Returns: - 0 for success - err on error Raises: - InputError for invalid aid, receiver_uids ''' from .notifications import notification_achievement_share user_ref = db.collection("users").document(uid) cur_achievements = user_ref.get().get("achievements") aid_list = [] for i in cur_achievements: aid_list.append(i["aid"]) if aid not in aid_list: raise InputError("ERROR: Cannot share an achievement you have not gotten") for id in receiver_uids: if id not in user_ref.get().get("connections"): raise InputError("ERROR: Cannot share to a TM you are not connected with") notification_achievement_share(uid, id, aid) ############################################################ # Achievement Helpers # ############################################################ def add_achievements(): ''' Function to add the achievements to firestore db ''' achievements = { 0: { "aid": 0, "title": "Intermediate Task Master", "description": "Complete at least 3 assigned tasks", "time_acquired": "" }, 1: { "aid": 1, "title": "Advanced Task Master", "description": "Complete at least 5 assigned tasks", "time_acquired": "" }, 2: { "aid": 2, "title": "Intermediate Project Master", "description": "Complete at least 3 projects", "time_acquired": "" }, 3: { "aid": 3, "title": "Advanced Project Master", "description": "Complete at least 5 projects", "time_acquired": "" }, 4: { "aid": 4, "title": "I am BNOC", "description": "Have at least 3 connections", "time_acquired": "" }, 5: { "aid": 5, "title": "I am Octopus", "description": "Have more than 8 tasks assigned at one time", "time_acquired": "" }, 6: { "aid": 6, "title": "Woof Woof Lone Wolf", "description": "Complete a project with only yourself", "time_acquired": "" }, 7: { "aid": 7, "title": "I Also Leave Google Restaurant Reviews", "description": "Leave at least 3 unique reputation reviews", "time_acquired": "" } } for key, val in achievements.items(): db.collection("achievements").document(str(key)).set(val) def reset_time_acquired(aid): ''' Given an aid, reset the time acquired to "" Arguments: - aid (achievement id) Returns: - None ''' achievement = db.collection("achievements").document(str(aid)).get().to_dict() achievement.update({"time_acquired": ""}) def give_achievement(uid, aid): ''' Updates the achievements list of the user identified by Uid in firestore database Args: uid (str): uid of the user that can be found in auth database aid (int): aid of the new achievement acquired Returns: None ''' user_ref = db.collection("users").document(uid) new_achievement = get_achievement(aid) new_achievement.update({"time_acquired": time.time()}) user_achievements = user_ref.get().get("achievements") user_achievements.append(new_achievement) user_ref.update({"achievements": user_achievements}) from .notifications import notification_achievement notification_achievement(uid, aid) reset_time_acquired(aid) def check_user_has_achievement(uid, aid): ''' Check if the user has already gotten a specific achievement Args: - uid (str): uid of the user that can be found in auth database - aid (int): aid of the achievement to be checked Returns: - True, if the achievement has already been achieved - False, if otherwise ''' curr_achievements = db.collection("users").document(uid).get().get("achievements") for ach in curr_achievements: if aid == ach["aid"]: return True return False def check_lone_wolf(uid): ''' Specific helper to check if a user can get the lone wolf achievement - checks if the user has completed a project by themself Args: - uid (str): uid of the user that can be found in auth database Returns: - True, if the achievement can be given - False, if otherwise ''' user_ref = db.collection("users").document(uid).get() for pid in user_ref.get("projects"): proj_ref = db.collection("projects").document(str(pid)).get() if len(proj_ref.get("project_members")) == 1 and proj_ref.get("status") == "Completed": return True return False def list_unachieved(uid): ''' Specific helper to return a list of achievement ids the user has not achieved Args: - uid (str): uid of the user that can be found in auth database Returns: - list of aids that hasnt been achieved ''' achievements = db.collection("users").document(uid).get().get("achievements") has_got = [] for ach in achievements: has_got.append(ach["aid"]) not_got = [] for doc in db.collection('achievements').stream(): data = doc.to_dict() if data['aid'] not in has_got: not_got.append(data) return not_got def check_achievement_visibility(uid): ''' Check if the user has turned on or off achievement visibility Args: - uid (user id) Returns: - hide_achievements (boolean) ''' return db.collection("users").document(uid).get().get("hide_achievements")
package ca.liashova.notesapp.database import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import ca.liashova.notesapp.model.Note @Dao interface NoteDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertNote(note: Note) @Update suspend fun updateNote(note: Note) @Delete suspend fun deleteNote(note: Note) @Query("SELECT * FROM NOTES ORDER BY DATEEDITED DESC") fun getAllNotes(): LiveData<List<Note>> @Query("SELECT * FROM NOTES WHERE noteBody LIKE '%' || :query || '%'") fun searchNote(query: String?): LiveData<List<Note>> }
<.header> Listing Trucks <:actions> <.link patch={~p"/trucks/new"}> <.button>New Truck</.button> </.link> </:actions> </.header> <.table id="trucks" rows={@streams.trucks} row_click={fn {_id, truck} -> JS.navigate(~p"/trucks/#{truck}") end} > <:col :let={{_id, truck}} label="Vin"> <%= truck.vin %> </:col> <:col :let={{_id, truck}} label="Unit number"> <%= truck.unit_number %> </:col> <:col :let={{_id, truck}} label="Model year"> <%= truck.model_year %> </:col> <:col :let={{_id, truck}} label="Make"> <%= Ecto.Enum.mappings(ShopSquad.Assets.Truck, :make)[truck.make] %> </:col> <:col :let={{_id, truck}} label="Model"> <%= truck.model %> </:col> <:col :let={{_id, truck}} label="Odometer"> <%= truck.odometer %> </:col> <:col :let={{_id, truck}} label="Engine hours"> <%= truck.engine_hours %> </:col> <:action :let={{_id, truck}}> <div class="sr-only"> <.link navigate={~p"/trucks/#{truck}"}>Show</.link> </div> <.link patch={~p"/trucks/#{truck}/edit"}>Edit</.link> </:action> <:action :let={{id, truck}}> <.link phx-click={JS.push("delete", value: %{id: truck.id}) |> hide("##{id}")} data-confirm="Are you sure?" > Delete </.link> </:action> </.table> <.modal :if={@live_action in [:new, :edit]} id="truck-modal" show on_cancel={JS.patch(~p"/trucks")}> <.live_component module={ShopSquadWeb.TruckLive.FormComponent} id={@truck.id || :new} title={@page_title} action={@live_action} truck={@truck} patch={~p"/trucks"} /> </.modal>
/* * Copyright (c) 2024, Quo <https://github.com/Quoded> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 com.pokescape; import java.awt.Color; import net.runelite.client.config.Config; import net.runelite.client.config.ConfigGroup; import net.runelite.client.config.ConfigItem; import net.runelite.client.config.ConfigSection; @ConfigGroup("pokescape") public interface PokescapeConfig extends Config { String PLUGIN_VERSION = "0.5.3"; enum SnapMode { INV("Top of Inventory"), CHATBOX("Top of Chatbox"), OFF("Off (Alt-Drag)"); private final String stringValue; SnapMode(final String s) { stringValue = s; } public String toString() { return stringValue; } } @ConfigItem( position = 1, keyName = "panel_visibility", name = "Show Side Panel", description = "Displays PokeScape PvM in the side panel." ) default boolean showPokescapeSidePanel() { return true; } @ConfigSection( name = "Overlay", description = "Overlay configuration.", position = 2 ) String overlaySection = "Overlay section"; @ConfigItem( position = 3, keyName = "overlay_visibility", name = "Display Overlay", description = "Displays the overlay on your game screen.", section = overlaySection ) default boolean overlayVisibility() { return true; } @ConfigItem( position = 4, keyName = "overlay_timestamp", name = "Timestamp", description = "Adds a timestamp to the overlay.", section = overlaySection ) default boolean timeStampVisibility() { return true; } @ConfigItem( position = 5, keyName = "overlay_password", name = "Event Password:", description = "Adds the event password to the overlay.", section = overlaySection ) default String eventPassword() { return ""; } @ConfigItem( position = 5, keyName = "overlay_password", name = "Event Password:", description = "Adds the event password to the overlay.", section = overlaySection, hidden = true ) void setEventPassword(String password); @ConfigItem( position = 6, keyName = "overlay_snapmode", name = "Snap Position", description = "Controls the snap position of the overlay.", section = overlaySection ) default SnapMode overlaySnapping() { return SnapMode.INV; } @ConfigItem( position = 7, keyName = "overlay_passcolor", name = "Password Color", description = "Sets the color of the event password.", section = overlaySection ) default Color passwordColor() { return Color.GREEN; } @ConfigItem( position = 8, keyName = "overlay_passtime", name = "Timestamp Color", description = "Sets the color of the timestamp.", section = overlaySection ) default Color timestampColor() { return Color.WHITE; } }
/* * 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.shindig.gadgets.http; import com.google.common.collect.Maps; import com.google.common.collect.Lists; import org.apache.shindig.common.uri.Uri; import org.apache.shindig.common.Pair; import org.apache.shindig.gadgets.GadgetException; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import java.util.List; import java.util.Map; /** * This class provides simple way for doing parallel fetches for multiple * resourcs using FutureTask's. */ public class MultipleResourceHttpFetcher { private final RequestPipeline requestPipeline; private final Executor executor; public MultipleResourceHttpFetcher(RequestPipeline requestPipeline, Executor executor) { this.requestPipeline = requestPipeline; this.executor = executor; } /** * Issue parallel requests to all resources that are needed. * * @param requests list of requests for which we want the resourses * @return futureTasks List of Pairs of url,futureTask for all the requests * in same order as specified. */ public List<Pair<Uri, FutureTask<RequestContext>>> fetchAll(List<HttpRequest> requests) { List<Pair<Uri, FutureTask<RequestContext>>> futureTasks = Lists.newArrayList(); for (HttpRequest request : requests) { futureTasks.add(Pair.of(request.getUri(), createHttpFetcher(request))); } return futureTasks; } /** * Issue parallel requests to all the resources that are needed ignoring * duplicates. * * @param requests list of urls for which we want the image resourses * @return futureTasks map of url -> futureTask for all the requests sent. */ public Map<Uri, FutureTask<RequestContext>> fetchUnique(List<HttpRequest> requests) { Map<Uri, FutureTask<RequestContext>> futureTasks = Maps.newHashMap(); for (HttpRequest request : requests) { Uri uri = request.getUri(); if (!futureTasks.containsKey(uri)) { futureTasks.put(uri, createHttpFetcher(request)); } } return futureTasks; } // Fetch the content of the requested uri. private FutureTask<RequestContext> createHttpFetcher(HttpRequest request) { // Fetch the content of the requested uri. FutureTask<RequestContext> httpFetcher = new FutureTask<RequestContext>(new HttpFetchCallable(request, requestPipeline)); executor.execute(httpFetcher); return httpFetcher; } private static class HttpFetchCallable implements Callable<RequestContext> { private final HttpRequest httpReq; private final RequestPipeline requestPipeline; public HttpFetchCallable(HttpRequest httpReq, RequestPipeline requestPipeline) { this.httpReq = httpReq; this.requestPipeline = requestPipeline; } public RequestContext call() { HttpResponse httpResp = null; GadgetException gadgetException = null; try { httpResp = requestPipeline.execute(httpReq); } catch (GadgetException e){ gadgetException = e; } return new RequestContext(httpReq, httpResp, gadgetException); } } // Encapsulates the response context of a single resource fetch. public static class RequestContext { private final HttpRequest httpReq; private final HttpResponse httpResp; private final GadgetException gadgetException; public HttpRequest getHttpReq() { return httpReq; } public HttpResponse getHttpResp() { return httpResp; } public GadgetException getGadgetException() { return gadgetException; } public RequestContext(HttpRequest httpReq, HttpResponse httpResp, GadgetException ge) { this.httpReq = httpReq; this.httpResp = httpResp; this.gadgetException = ge; } @Override public int hashCode() { return httpReq.hashCode() ^ httpResp.hashCode() ^ gadgetException.hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof RequestContext)) { return false; } RequestContext reqCxt = (RequestContext)obj; return httpReq.equals(reqCxt.httpReq) && (httpResp != null ? httpResp.equals(reqCxt.httpResp) : reqCxt.httpResp == null) && (gadgetException != null ? gadgetException.equals(reqCxt.gadgetException) : reqCxt.gadgetException == null); } } }
"use client" import Breadcrumb from '@/app/components/breadcrumb/Breadcrumb'; import Image from 'next/image'; import React, { useState } from 'react' const BlogForm = () => { const [formData, setFormData] = useState({ title: '', content: '', author: '', image: '', }); const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => { const { name, value } = e.target; setFormData(prevState => ({ ...prevState, [name]: value, })); }; const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => { const file = e.target.files[0]; const reader = new FileReader(); reader.onloadend = () => { setFormData(prevState => ({ ...prevState, image: reader.result as string, })); }; if (file) { reader.readAsDataURL(file); } }; const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); await fetch('/api/blogs', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(formData), }); setFormData({ title: '', content: '', author: '' ,image:''}); }; return ( <div className='mb-8 mt-8 '> <div className='ml-8 mt-4'> <Breadcrumb/> </div> <div className="max-w-lg mx-auto bg-white p-8 rounded-lg shadow-md"> <h2 className="text-2xl font-bold mb-4">Blog Ekle</h2> <form onSubmit={handleSubmit} className="space-y-4"> <div> <label htmlFor="title" className="block text-sm font-medium text-gray-700"> Başlık </label> <input type="text" name="title" value={formData.title} onChange={handleChange} className="mt-1 p-3 block w-full border border-gray-300 rounded-md focus:outline-none focus:border-indigo-500" required /> </div> <div> <label htmlFor="author" className="block text-sm font-medium text-gray-700"> Yazar </label> <input type="text" name="author" value={formData.author} onChange={handleChange} className="mt-1 p-3 block w-full border border-gray-300 rounded-md focus:outline-none focus:border-indigo-500" required /> </div> <div> <label htmlFor="content" className="block text-sm font-medium text-gray-700"> İçerik </label> <textarea name="content" value={formData.content} onChange={handleChange} className="mt-1 p-3 block w-full border border-gray-300 rounded-md focus:outline-none focus:border-indigo-500" rows={6} required /> </div> <div> <label htmlFor="image" className="block text-sm font-medium text-gray-700"> Resim </label> <input type="file" name="image" accept="image/*" onChange={handleImageChange} className="mt-1 p-3 block w-full border border-gray-300 rounded-md focus:outline-none focus:border-indigo-500" required /> {formData.image && ( <Image src={formData.image} alt="Seçilen Resim" className="mt-2 rounded-md" width={250} height={250} /> )} </div> <div> <button type="submit" className="w-full bg-indigo-600 text-white py-3 px-6 rounded-md hover:bg-indigo-700 focus:outline-none focus:bg-indigo-700" > Gönder </button> </div> </form> </div> </div> ) } export default BlogForm
from __future__ import annotations from typing import Dict, Any, Union import numpy as np import wigners import torch ArrayLike = Any Array = Any class ClebschGordanReal: def __init__(self, l_max: int) -> None: self._l_max = l_max self._cg = {} # real-to-complex and complex-to-real transformations as matrices r2c = {} c2r = {} for L in range(0, self._l_max + 1): r2c[L] = _real2complex(L) c2r[L] = np.conjugate(r2c[L]).T for l1 in range(self._l_max + 1): for l2 in range(self._l_max + 1): for L in range( max(l1, l2) - min(l1, l2), min(self._l_max, (l1 + l2)) + 1 ): rcg = _real_clebsch_gordan_matrix(l1, l2, L, r2c=r2c, c2r=c2r) # sparsify: take only the non-zero entries (indices # of m1 and m2 components) for each M new_cg = [] for M in range(2 * L + 1): cg_nonzero = np.where(np.abs(rcg[:, :, M]) > 1e-15) cg_M = np.zeros( len(cg_nonzero[0]), dtype=[("m1", ">i4"), ("m2", ">i4"), ("cg", ">f8")], ) cg_M["m1"] = cg_nonzero[0] cg_M["m2"] = cg_nonzero[1] cg_M["cg"] = rcg[cg_nonzero[0], cg_nonzero[1], M] new_cg.append(cg_M) self._cg[(l1, l2, L)] = new_cg def combine_einsum( self, rho1: ArrayLike, rho2: ArrayLike, L: int, combination_string: str ) -> Array: # automatically infer l1 and l2 from the size of the coefficients vectors l1 = (rho1.shape[1] - 1) // 2 l2 = (rho2.shape[1] - 1) // 2 if L > self._l_max or l1 > self._l_max or l2 > self._l_max: raise ValueError( "Requested CG entry ", (l1, l2, L), " has not been precomputed" ) n_items = rho1.shape[0] if rho1.shape[0] != rho2.shape[0]: raise IndexError( "Cannot combine feature blocks with different number of items" ) # infers the shape of the output using the einsum internals features = np.einsum(combination_string, rho1[:, 0, ...], rho2[:, 0, ...]).shape rho = np.zeros((n_items, 2 * L + 1) + features[1:]) if (l1, l2, L) in self._cg: for M in range(2 * L + 1): for m1, m2, cg in self._cg[(l1, l2, L)][M]: rho[:, M, ...] += np.einsum( combination_string, rho1[:, m1, ...], rho2[:, m2, ...] * cg ) return rho def couple(self, decoupled: Union[Array, Dict], iterate: int = 0) -> Dict: r"""uncoupled basis -> coupled basis transformation Goes from an uncoupled product basis to a coupled basis. A (2l1+1)x(2l2+1) matrix transforming like the outer product of Y^m1_l1 Y^m2_l2 can be rewritten as a list of coupled vectors, each transforming like a Y^M_L. This transformation is accomplished through the following relation: |L M> = |l1 l2 L M> = \sum_{m1 m2} <l1 m1 l2 m2|L M> |l1 m1> |l2 m2> The process can be iterated: a D dimensional array that is the product of D Y^m_l can be turned into a set of multiple terms transforming as a single Y^M_L. Args: decoupled: (...)x(2l1+1)x(2l2+1) array containing coefficients that transform like products of Y^l1 and Y^l2 harmonics. Can also be called on a array of higher dimensionality, in which case the result will contain matrices of entries. If the further index also correspond to spherical harmonics, the process can be iterated, and couple() can be called onto its output, in which case the coupling is applied to each entry. iterate: calls couple iteratively the given number of times. Equivalent to: couple(couple(... couple(decoupled))) Returns: coupled: A dictionary tracking the nature of the coupled objects. When called one time, it returns a dictionary containing (l1, l2) [the coefficients of the parent Ylm] which in turns is a dictionary of coupled terms, in the form L:(...)x(2L+1)x(...) When called multiple times, it applies the coupling to each term, and keeps track of the additional l terms, so that, e.g., when called with iterate=1 the return dictionary contains terms of the form (l3,l4,l1,l2) : { L: array } Note that this coupling scheme is different from the NICE-coupling where angular momenta are coupled from left to right as (((l1 l2) l3) l4)... ) Thus results may differ when combining more than two angular channels. """ coupled = {} # when called on a matrix, turns it into a dict form to which we can # apply the generic algorithm if not isinstance(decoupled, dict): l2 = (decoupled.shape[-1] - 1) // 2 decoupled = {(): {l2: decoupled}} # runs over the tuple of (partly) decoupled terms for ltuple, lcomponents in decoupled.items(): # each is a list of L terms for lc in lcomponents.keys(): # this is the actual matrix-valued coupled term, # of shape (..., 2l1+1, 2l2+1), transforming as Y^m1_l1 Y^m2_l2 dec_term = lcomponents[lc] l1 = (dec_term.shape[-2] - 1) // 2 l2 = (dec_term.shape[-1] - 1) // 2 # there is a certain redundance: the L value is also the last entry # in ltuple if lc != l2: raise ValueError( "Inconsistent shape for coupled angular momentum block." ) # in the new coupled term, prepend (l1,l2) to the existing label coupled[(l1, l2) + ltuple] = {} for L in range( max(l1, l2) - min(l1, l2), min(self._l_max, (l1 + l2)) + 1 ): # ensure that Lterm is created on the same device as the dec_term device = dec_term.device Lterm = torch.zeros( size=dec_term.shape[:-2] + (2 * L + 1,), device=device ) for M in range(2 * L + 1): for m1, m2, cg in self._cg[(l1, l2, L)][M]: Lterm[..., M] += dec_term[..., m1, m2] * cg coupled[(l1, l2) + ltuple][L] = Lterm # repeat if required if iterate > 0: coupled = self.couple(coupled, iterate - 1) return coupled def decouple(self, coupled: Dict, iterate: int = 0) -> Union[Dict, Array]: r""" Undoes the transformation enacted by couple. |l1 m1> |l2 m2> = \sum_{L M} <L M |l1 m1 l2 m2> |l1 l2 L M> """ decoupled = {} # applies the decoupling to each entry in the dictionary for ltuple, lcomponents in coupled.items(): # the initial pair in the key indicates the decoupled terms that generated # the L entries l1, l2 = ltuple[:2] # shape of the coupled matrix (last entry is the 2L+1 M terms) shape = next(iter(lcomponents.values())).shape[:-1] device = next(iter(lcomponents.values())).device dec_term = torch.zeros( shape + ( # noqa 2 * l1 + 1, 2 * l2 + 1, ), device=device, ) for L in range(max(l1, l2) - min(l1, l2), min(self._l_max, (l1 + l2)) + 1): # supports missing L components, e.g. if they are zero because of symmetry if L not in lcomponents: continue for M in range(2 * L + 1): for m1, m2, cg in self._cg[(l1, l2, L)][M]: dec_term[..., m1, m2] += cg * lcomponents[L][..., M] # stores the result with a key that drops the l's we have just decoupled if not ltuple[2:] in decoupled: decoupled[ltuple[2:]] = {} decoupled[ltuple[2:]][l2] = dec_term # rinse, repeat if iterate > 0: decoupled = self.decouple(decoupled, iterate - 1) # if we got a fully decoupled state, just return an array if ltuple[2:] == (): decoupled = next(iter(decoupled[()].values())) return decoupled def _real2complex(L: int) -> Array: """transformation matrix between spherical harmonics Computes the transformation matrix that goes from a set of real spherical harmonics, ordered as: (l, -l), (l, -l + 1), ..., (l, l - 1), (l, l) to a set of complex spherical harmonics (in the same order). The transformation matrix can be found in several places, e.g.: https://en.wikipedia.org/wiki/Spherical_harmonics#Real_form Taking the conjugate transpose of the matrix gives the transformation from complex to real spherical harmonics. As an example, using scipy: >>> from scipy.special import sph_harm >>> U = _real2complex(1) >>> # complex spherical harmonics, ordered from m=-l to m=l >>> comp_sph = np.array([ ... sph_harm(-1, 1, 0.2, 0.2), ... sph_harm(0, 1, 0.2, 0.2), ... sph_harm(1, 1, 0.2, 0.2) ... ]) >>> real_sph = np.conjugate(U).T @ comp_sph >>> assert np.max(abs(comp_sph - U @ real_sph)) < 1e-15 """ mult = 2 * L + 1 mat = np.zeros((mult, mult), dtype=np.complex128) # m = 0 mat[L, L] = 1.0 if L == 0: return mat isqrt2 = 1.0 / 2**0.5 for m in range(1, L + 1): # m > 0 mat[L + m, L + m] = isqrt2 * (-1) ** m mat[L + m, L - m] = isqrt2 * 1j * (-1) ** m # m < 0 mat[L - m, L + m] = isqrt2 mat[L - m, L - m] = -isqrt2 * 1j return mat def _complex_clebsch_gordan_matrix(l1: int, l2: int, L: int) -> Array: r"""clebsch-gordan matrix Computes the Clebsch-Gordan (CG) matrix for transforming complex-valued spherical harmonics. The CG matrix is computed as a 3D array of elements < l1 m1 l2 m2 | L M > where the first axis loops over m1, the second loops over m2, and the third one loops over M. The matrix is real. For example, using the relation: | l1 l2 L M > = \sum_{m1, m2} <l1 m1 l2 m2 | L M > | l1 m1 > | l2 m2 > (https://en.wikipedia.org/wiki/Clebsch–Gordan_coefficients, section "Formal definition of Clebsch-Gordan coefficients", eq 2) one can obtain the spherical harmonics L from two sets of spherical harmonics with l1 and l2 (up to a normalization factor). E.g.: >>> from scipy.special import sph_harm >>> C_112 = _complex_clebsch_gordan_matrix(1, 1, 2) >>> comp_sph_1 = np.array([ ... sph_harm(m, 1, 0.2, 0.2) for m in range(-1, 1+1) ... ]) >>> # obtain the (unnormalized) spherical harmonics with >>> l = 2 by contraction over m1 and m2 >>> comp_sph_2_u = np.einsum("ijk,i,j->k", C_112, comp_sph_1, comp_sph_2) >>> # we can check that they differ from the spherical harmonics by a >>> # constant factor >>> comp_sph_2 = np.array([sph_harm(m, 2, 0.2, 0.2) for m in range(-2, 2+1)]) >>> print(comp_sph2 / comp_sph_2_u) ... [3.23604319-1.69568664e-16j 3.23604319+7.31506235e-17j ... 3.23604319+0.00000000e+00j 3.23604319-7.31506235e-17j ... 3.23604319+1.69568664e-16j] Args: l1: l number for the first set of spherical harmonics l2: l number for the second set of spherical harmonics L: l number for the third set of spherical harmonics Returns: real_cg: CG matrix for transforming complex-valued spherical harmonics """ if np.abs(l1 - l2) > L or np.abs(l1 + l2) < L: return np.zeros((2 * l1 + 1, 2 * l2 + 1, 2 * L + 1), dtype=np.double) else: return wigners.clebsch_gordan_array(l1, l2, L) def _real_clebsch_gordan_matrix( l1: int, l2: int, L: int, r2c: Dict[int, Array], c2r: Dict[int, Array] ) -> Array: """clebsch gordan matrix Clebsch Gordan (CG) matrix for real values spherical harmonics, constructed by contracting the CG matrix for complex-valued spherical harmonics with the matrices that transform between real-valued and complex-valued spherical harmonics. Args: l1: l number for the first set of spherical harmonics l2: l number for the second set of spherical harmonics L: l number for the third set of spherical harmonics r2c: transformation matrices from real to complex spherical harmonics c2r: transformation matrices from complex to real spherical harmonics Returns: real_cg: CG matrix for transforming real-valued spherical harmonics """ complex_cg = _complex_clebsch_gordan_matrix(l1, l2, L) real_cg = np.einsum("ijk,il,jm,nk->lmn", complex_cg, r2c[l1], r2c[l2], c2r[L]) if (l1 + l2 + L) % 2 == 0: return np.real(real_cg) else: return np.imag(real_cg)
#include "mass.hpp" #include <format> #include <iostream> #include <string> template <typename LHS, typename RHS> std::string spaceshipCompare(const LHS& lhs, const RHS& rhs) { if (lhs <=> rhs == std::strong_ordering::less || lhs <=> rhs == std::partial_ordering::less) { return "less"; } else if (lhs <=> rhs == std::strong_ordering::greater || lhs <=> rhs == std::partial_ordering::greater) { return "greater"; } else if (lhs <=> rhs == std::strong_ordering::equal || lhs <=> rhs == std::partial_ordering::equivalent) { return "equal"; } return "unordered"; } // ------------------------------------------------------------------ // // Operator overloading, various constructors, more templates, etc // // ------------------------------------------------------------------ int main() { usu::microgram mcg{ 1000000 }; usu::gram g = usu::mass_cast<usu::gram>(mcg); usu::pound lb = usu::mass_cast<usu::pound>(g); usu::ounce oz = usu::mass_cast<usu::ounce>(lb); usu::ton ton = usu::mass_cast<usu::ton>(lb); std::cout << "--- mass_cast<> From micrograms ---" << std::endl; std::cout << std::format("micrograms : {:>12d}\n", mcg.count()); std::cout << std::format("grams : {:>12d}\n", g.count()); std::cout << std::format("lbs : {:>12.10f}\n", lb.count()); std::cout << std::format("ounces : {:>12.10f}\n", oz.count()); std::cout << std::format("tons : {:>12.10f}\n", ton.count()); usu::pound somePounds(2000); usu::microgram ugFromPounds = usu::mass_cast<usu::microgram>(somePounds); usu::gram gramsFromPounds = usu::mass_cast<usu::gram>(somePounds); usu::ounce ouncesFromPounds = usu::mass_cast<usu::ounce>(somePounds); usu::ton tonsFromPounds = usu::mass_cast<usu::ton>(ouncesFromPounds); std::cout << "\n--- mass_cast<> From pounds ---\n"; std::cout << std::format("micrograms : {:>12d}\n", ugFromPounds.count()); std::cout << std::format("grams : {:>12d}\n", gramsFromPounds.count()); std::cout << std::format("lbs : {:>12.4f}\n", somePounds.count()); std::cout << std::format("ounces : {:>12.4f}\n", ouncesFromPounds.count()); std::cout << std::format("tons : {:>12.4f}\n", tonsFromPounds.count()); std::cout << "\n--- Arithmetic Operators ---\n"; // Addition { usu::pound a{ 1 }; usu::pound b{ 0.5 }; usu::pound c = a + b; std::cout << std::format("(pound + pound) : {:.2f} + {:.2f} = {:.2f} ==> grams: {}\n", a.count(), b.count(), c.count(), usu::mass_cast<usu::gram>(c).count()); usu::pound d{ 1 }; usu::pound before{ d }; d += b; std::cout << std::format("(pound += pound) : {:.2f} += {:.2f} = {:.2f} ==> grams: {}\n", before.count(), b.count(), d.count(), usu::mass_cast<usu::gram>(d).count()); usu::gram e = usu::mass_cast<usu::gram>(usu::pound{ .5 }); usu::pound f{ 1 }; before = f; f += e; std::cout << std::format("(pound += gram) : {:.2f} += {} = {:.2f} ==> grams: {}\n", before.count(), e.count(), f.count(), usu::mass_cast<usu::gram>(f).count()); } // Subtraction { std::cout << std::endl; usu::pound a{ 1 }; usu::pound b{ 0.5 }; usu::pound c = a - b; std::cout << std::format("(pound - pound) : {:.2f} - {:.2f} = {:.2f} ==> grams: {}\n", a.count(), b.count(), c.count(), usu::mass_cast<usu::gram>(c).count()); usu::pound d{ 1 }; usu::pound before{ d }; d -= b; std::cout << std::format("(pound -= pound) : {:.2f} -= {:.2f} = {:.2f} ==> grams: {}\n", before.count(), b.count(), d.count(), usu::mass_cast<usu::gram>(d).count()); usu::gram e = usu::mass_cast<usu::gram>(usu::pound{ 0.5 }); usu::pound f{ 1 }; before = f; f -= e; std::cout << std::format("(pound -= gram) : {:.2f} -= {} = {:.2f} ==> grams: {}\n", before.count(), e.count(), f.count(), usu::mass_cast<usu::gram>(f).count()); } // Scalar multiplication { std::cout << std::endl; usu::pound a{ 1 }; usu::pound b = a * 2.2; usu::pound c = 3.2 * a; std::cout << std::format("(pound * scalar) : {:.2f} * 2.20 = {:.2f} ==> grams: {}\n", a.count(), b.count(), usu::mass_cast<usu::gram>(b).count()); std::cout << std::format("(scalar * pound) : 3.20 * {:.2f} = {:.2f} ==> grams: {}\n", a.count(), c.count(), usu::mass_cast<usu::gram>(c).count()); usu::pound d{ 1.5 }; usu::pound before{ d }; d *= 2; std::cout << std::format("(pound *= scalar) : {:.2f} *= 2 = {:.2f} ==> grams: {}\n", before.count(), d.count(), usu::mass_cast<usu::gram>(d).count()); } // Scalar division { std::cout << std::endl; usu::pound a{ 2 }; usu::pound b = a / 2; std::cout << std::format("(pound / scalar) : {:.2f} / 2 = {:.2f} ==> grams: {}\n", a.count(), b.count(), usu::mass_cast<usu::gram>(b).count()); usu::gram c{ 6 }; usu::gram d = c / 2; usu::gram e = c / 4; std::cout << std::format("(gram / scalar) : {0:d} / 2 = {1:d} ==> grams: {1:d}\n", c.count(), d.count()); std::cout << std::format("(gram / scalar) : {0:d} / 4 = {1:d} ==> grams: {1:d}\n", c.count(), e.count()); usu::pound f{ 3 }; usu::pound before{ f }; f /= 2; std::cout << std::format("(pound /= scalar) : {:.2f} /= 2 = {:.2f} ==> grams: {}\n", before.count(), f.count(), usu::mass_cast<usu::gram>(f).count()); } // Adding mixed types { std::cout << std::endl; usu::gram gramResult = g + lb + oz; usu::ounce ozResult = oz + g + lb; usu::pound lbResult = lb + g + oz; std::cout << std::format("(gram + pound + ounce) : {:d} + {:.6f} + {:.6f} = {:d} grams\n", g.count(), lb.count(), oz.count(), gramResult.count()); std::cout << std::format("(ounce + gram + pound) : {:.6f} + {:d} + {:.6f} = {:.6f} ounces\n", oz.count(), g.count(), lb.count(), ozResult.count()); std::cout << std::format("(pound + gram + ounce) : {:.6f} + {:d} + {:.6f} = {:.6f} pounds\n", lb.count(), g.count(), oz.count(), lbResult.count()); usu::gram gramPlusEqual = g; gramPlusEqual += lb; std::cout << std::format("(gram += lb) : {:d} += {:.6f} = {:d} grams\n", g.count(), lb.count(), gramPlusEqual.count()); gramPlusEqual = g; gramPlusEqual += oz; std::cout << std::format("(gram += oz) : {:d} += {:.6f} = {:d} grams\n", g.count(), oz.count(), gramPlusEqual.count()); } std::cout << "\n--- Logical Operators ---\n"; { usu::ounce a{ 16 }; usu::pound b{ 1 }; usu::kilogram c{ 4 }; usu::kilogram d{ 1 }; std::cout << std::format("{} oz == {} lb : {}\n", a.count(), b.count(), a == b); std::cout << std::format("{} oz == {} kg : {}\n", a.count(), c.count(), a == c); std::cout << std::format("{} kg == {} kg : {}\n", c.count(), d.count(), c == d); std::cout << std::endl; std::cout << std::format("{} oz != {} lb : {}\n", a.count(), b.count(), a != b); std::cout << std::format("{} oz != {} kg : {}\n", a.count(), c.count(), a != c); std::cout << std::format("{} kg != {} kg : {}\n", c.count(), d.count(), c != d); std::cout << std::endl; std::cout << std::format("{} oz < {} lb : {}\n", a.count(), b.count(), a < b); std::cout << std::format("{} oz < {} kg : {}\n", a.count(), c.count(), a < c); std::cout << std::format("{} kg < {} kg : {}\n", c.count(), d.count(), c < d); std::cout << std::endl; std::cout << std::format("{} oz > {} lb : {}\n", a.count(), b.count(), a > b); std::cout << std::format("{} oz > {} kg : {}\n", a.count(), c.count(), a > c); std::cout << std::format("{} kg > {} kg : {}\n", c.count(), d.count(), c > d); std::cout << std::endl; std::cout << std::format("{} oz <= {} lb : {}\n", a.count(), b.count(), a <= b); std::cout << std::format("{} oz <= {} kg : {}\n", a.count(), c.count(), a <= c); std::cout << std::format("{} kg <= {} kg : {}\n", c.count(), d.count(), c <= d); std::cout << std::endl; std::cout << std::format("{} oz >= {} lb : {}\n", a.count(), b.count(), a >= b); std::cout << std::format("{} oz >= {} kg : {}\n", a.count(), c.count(), a >= c); std::cout << std::format("{} kg >= {} kg : {}\n", c.count(), d.count(), c >= d); std::cout << std::endl; std::cout << std::format("{} oz <=> {} lb : {}\n", a.count(), b.count(), spaceshipCompare(a, b)); std::cout << std::format("{} oz <=> {} kg : {}\n", a.count(), c.count(), spaceshipCompare(a, c)); std::cout << std::format("{} kg <=> {} kg : {}\n", c.count(), d.count(), spaceshipCompare(c, d)); return 0; } }
import { useState, useEffect } from 'react'; import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import { fetchApiImg } from '../services/api'; import Searchbar from './Searchbar'; import ImageGallery from './ImageGallery'; import Button from './Button'; import Modal from './Modal'; import Loader from './Loader'; import css from './App.module.css'; // import ImageGalleryItem from './ImageGalleryItem'; const App = () => { const [images, setImages] = useState([]); const [search, setSearch] = useState(''); const [page, setPage] = useState(1); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [currentImage, setCurrentImage] = useState(null); useEffect(() => { if (!search) { return; } const getImages = async () => { try { setLoading(true); const data = await fetchApiImg(search, page); if (data.hits.length === 0) { return toast.error('Oops, there are no such pictures. Try again'); } setImages(prevImages => [...prevImages, ...data.hits]); } catch (error) { setError(error.message); } finally { setLoading(false); } }; getImages(); }, [search, page]); const onSearchImages = ({ search }) => { if (search.trim() === '') { setImages([]); setPage(1); return toast.error('Repeat the question again please'); } setSearch(search); setImages([]); setPage(1); }; const openModal = data => { setCurrentImage(data); }; const onClick = () => { setPage(prevPage => prevPage + 1); }; const onClose = () => { setCurrentImage(null); }; return ( <> <Searchbar onSubmit={onSearchImages} /> {error && <p>Something went wrong. Try reloading the page</p>} {images.length > 0 && ( <ImageGallery images={images} openModal={openModal} search={search} /> )} {images.length > 0 && !loading && <Button onClick={onClick} />} <ToastContainer /> {loading && <Loader />} {currentImage && ( <Modal className={css.CurrentImage} onClose={onClose} currentImage={currentImage} search={search} /> )} </> ); }; export default App;
<h1 id="gnome-blasting">Gnome Blasting</h1> <p><a href="https://github.com/mrjmac/competitive-programming/blob/main/UIL/westwoodInv23/Gnome.java">GitHub link</a></p> <p>This was a problem from the 2023 Westwood UIL invitational.</p> <p>The problem goes like this: You are given an array of &quot;.&quot;s and &quot;g&quot;s, where the g&#39;s represent gnomes. You can &quot;shoot&quot; at any spot in the array which will remove all connected gnomes. However, the blast cannot travel downwards. What is the minimum number of blasts to eliminate all gnomes?</p> <p>This problem is pretty simple. We can simulate the removal of all gnomes by using dfs. Greedily, we can recognize that the best way to clear gnomes is from bottom to top. Combining these two things, we can blast every position that has a gnome from bottom to top and simulate what happens to figure out the number of required blasts. However, this problem had a sneaky test case. While for most cases an array was provided, the problem stipulated that you would occasionally be given dimensions for an array but no array as there were no gnomes. We wasted a lot of time because we didn&#39;t read the problem carefully enough. Here&#39;s the code for this problem: </p> <pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> Gnome { <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-keyword">String</span> args[]) throws IOException { Scanner test = <span class="hljs-keyword">new</span> Scanner(<span class="hljs-keyword">new</span> <span class="hljs-built_in">File</span>(<span class="hljs-string">"gnome.dat"</span>)); <span class="hljs-keyword">int</span> n = test.nextInt(); <span class="hljs-built_in">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; n; i++) { <span class="hljs-keyword">int</span> <span class="hljs-built_in">height</span> = test.nextInt(), ans = <span class="hljs-number">0</span>; test.nextLine(); <span class="hljs-keyword">String</span> <span class="hljs-built_in">line</span> = test.nextLine(); <span class="hljs-keyword">char</span>[][] <span class="hljs-built_in">map</span> = <span class="hljs-keyword">new</span> <span class="hljs-keyword">char</span>[<span class="hljs-built_in">height</span>][<span class="hljs-built_in">line</span>.length()]; <span class="hljs-built_in">map</span>[<span class="hljs-number">0</span>] = <span class="hljs-built_in">line</span>.toCharArray(); <span class="hljs-built_in">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">1</span>; j &lt; <span class="hljs-built_in">height</span>; j++) { <span class="hljs-built_in">map</span>[j] = test.nextLine().toCharArray(); } <span class="hljs-built_in">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-built_in">map</span>.length - <span class="hljs-number">1</span>; j &gt;= <span class="hljs-number">0</span>; j--) { <span class="hljs-built_in">for</span> (<span class="hljs-keyword">int</span> k = <span class="hljs-built_in">map</span>[<span class="hljs-number">0</span>].length - <span class="hljs-number">1</span>; k &gt;= <span class="hljs-number">0</span>; k--) { <span class="hljs-built_in">if</span> (<span class="hljs-built_in">map</span>[j][k] == <span class="hljs-string">'g'</span>) { ans += <span class="hljs-number">1</span>; dfs(j, k, <span class="hljs-built_in">map</span>); } } } System.out.<span class="hljs-built_in">println</span>(ans); } } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> dfs(<span class="hljs-keyword">int</span> x, <span class="hljs-keyword">int</span> y, <span class="hljs-keyword">char</span>[][] <span class="hljs-built_in">map</span>) { <span class="hljs-built_in">if</span> (x &gt;= <span class="hljs-number">0</span> &amp;&amp; x &lt; <span class="hljs-built_in">map</span>.length &amp;&amp; y &gt;= <span class="hljs-number">0</span> &amp;&amp; y &lt; <span class="hljs-built_in">map</span>[x].length) { <span class="hljs-built_in">if</span> (<span class="hljs-built_in">map</span>[x][y] == <span class="hljs-string">'g'</span>) { <span class="hljs-built_in">map</span>[x][y] = <span class="hljs-string">'.'</span>; dfs(x, y - <span class="hljs-number">1</span>, <span class="hljs-built_in">map</span>); dfs(x - <span class="hljs-number">1</span>, y, <span class="hljs-built_in">map</span>); dfs(x, y + <span class="hljs-number">1</span>, <span class="hljs-built_in">map</span>); } } } } </code></pre><p>Entry written 6/10/2023</p>
import { RegisterInput } from '../inputs/register.input'; import { Request } from 'express'; import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import * as jwt from 'jsonwebtoken'; import * as bcrypt from 'bcrypt'; import { User } from '../model/user.model'; import { LoginInput } from '../inputs/login.input'; import { SocialAccountInput } from '../inputs/social-account.input'; import { Sequelize, Transaction } from 'sequelize'; import { SocialAccount } from '../model/social-account.model'; @Injectable({}) export class AuthService { constructor( private configService: ConfigService, @Inject('USER_REPOSITORY') private userRepo: typeof User, @Inject('SOCIAL_REPOSITORY') private socialAccountRepo: typeof SocialAccount, @Inject('SEQUELIZE') private readonly sequelize: Sequelize, ) {} async register(input: RegisterInput) { const hashedPassword = await bcrypt.hash(input.password, 10); const user = await this.userRepo.create({ ...input, password: hashedPassword, }); const token = this.generateToken(user.id); return Object.assign(user, { token }); } async login(input: LoginInput) { const user = await this.getUserOrError({ email: input.email }); const token = this.generateToken(user.id); const passwordCheck = await bcrypt.compare(input.password, user.password); if (!passwordCheck) throw new HttpException('Forbidden', HttpStatus.FORBIDDEN); return Object.assign(user, { token }); } async getUserFromReqHeaders(req: Request): Promise<User> { let token = this.getAuthToken(req); if (!token) return null; const userId = this.verifyToken(token); const user = await this.userRepo.findOne({ where: { id: userId } }); return user ? (user.toJSON() as User) : null; } getAuthToken(req: Request): string { if ( req && req.headers && (req.headers.authorization || req.headers.Authorization) ) { let auth: string; if (req.headers.authorization) auth = req.headers.authorization; if (req.headers.Authorization) auth = <string>req.headers.Authorization; return auth.split(' ')[1]; } return null; } generateToken(userId: string) { return jwt.sign({ userId }, this.configService.get<string>('JWTKEY')); } verifyToken(token: string) { const { userId } = jwt.verify( token, this.configService.get<string>('JWTKEY'), ); return userId; } async socialLoginOrRegister(input: SocialAccountInput) { let currentUser, user; const userSocialAccount = await this.socialAccountRepo.findOne({ where: { providerId: input.providerId }, }); if (userSocialAccount) { user = await this.userRepo.findOne({ where: { id: userSocialAccount.userId }, }); } else { user = await this.userRepo.findOne({ where: { email: input.email }, }); } if (!userSocialAccount && !user) { currentUser = await this.registerSocial(input); } if (user && userSocialAccount) { currentUser = await this.loginSocial(user, input); } if (user && !userSocialAccount) { currentUser = await this.mergeAccount(user, input); } return currentUser; } private async mergeAccount(user: User, input: SocialAccountInput) { const currentUser = user; return this.sequelize.transaction(async (transaction) => { await this.socialAccountRepo.create( { userId: currentUser.id, provider: input.provider, providerId: input.providerId, }, { transaction }, ); const updateCurrentUser = await this.userRepo.findOne({ where: { id: currentUser.id }, }); updateCurrentUser.update({ ...input }); updateCurrentUser.save; const token = this.generateToken(updateCurrentUser.id); return Object.assign(updateCurrentUser, { token }); }); } private async loginSocial( user: User, input: SocialAccountInput, transaction?: Transaction, ) { const currentUser = await this.userRepo.findOne({ where: { id: user.id } }); currentUser.update({ ...input }); currentUser.save; const token = this.generateToken(user.id); return Object.assign(currentUser, { token, }); } async registerSocial(input: SocialAccountInput) { return this.sequelize.transaction(async (transaction) => { const user = await this.createUserAndSocialAccount(input, transaction); const token = this.generateToken(user.id); return Object.assign(user, { token }); }); } private async createUserAndSocialAccount( input: SocialAccountInput, transaction: Transaction, ) { const user = await this.userRepo.create({ ...input }, { transaction }); await this.socialAccountRepo.create( { providerId: input.providerId, provider: input.provider, userId: user.id, }, { transaction }, ); return user; } async getUserOrError(input: any) { const user = await this.userRepo.findOne({ where: input }); if (!user) { throw new HttpException('Forbidden', HttpStatus.FORBIDDEN); } return user; } }
import { useState } from 'react'; import { FiSearch } from 'react-icons/fi'; import { Btn, Header, Input, SearchForm } from './Searchbar.styled'; export const Searchbar = ({ onSubmit }) => { const [query, setQuery] = useState(''); const handleChange = evt => { setQuery(evt.target.value.trim().toLowerCase()); }; const handleSubmit = evt => { evt.preventDefault(); onSubmit(query); evt.target.reset(); }; return ( <Header> <SearchForm onSubmit={handleSubmit}> <Btn type="submit"> <FiSearch size={20} /> </Btn> <Input type="text" autoComplete="off" name="query" autoFocus placeholder="Search images and photos" onChange={handleChange} /> </SearchForm> </Header> ); };
# Tixar Mobile App **Tixar** is a mobile application that allows fans to get verified and purchase event tickets. As we don't have developer accounts on the App Store or Google Play Store, we will run our app on Expo. You will need Yarn installed as we have dependencies in our yarn.lock file. ## Prerequisites - **Yarn**: You can install Yarn as from [yarnpkg.com](https://classic.yarnpkg.com/en/docs/install). - **Expo CLI**: Install the Expo CLI globally using npm or Yarn. ```bash # Using Yarn: yarn global add expo-cli ``` ## Installation and Usage **Cloning the Repository**: ```bash git clone https://github.com/yourusername/Tixar-Client.git cd Tixar-Client ``` **Install Dependencies**: ```bash # install yarn dependencies: yarn install ``` **Start the App**: ```bash npx expo start ``` **Debugging**: Should you face any bugs. Follow the instructions on terminal or run this command. ```bash npx expo install --fix ``` **Viewing the App on Mobile (Recommended)**: Install the Expo Go app on the [App store](https://apps.apple.com/sg/app/expo-go/id982107779) or [Google Play Store](https://play.google.com/store/apps/details?id=host.exp.exponent&pcampaignid=web_share) Ensure that your mobile device and laptop are on the same network. Scan the QR code generated in the terminal using your native camera app. This will open the app in Expo Go. **Viewing the App on a Mobile Emulator (Requires Emulator Setup)**: For Android, install Android Studio and set up an Android emulator. Then press `a` in the terminal to run the app on the emulator. For iOS, install Xcode and set up an iOS simulator. Then press `i` in the terminal to run the app on the simulator. **Account Registration**: Register for an account by filling out the relevant fields in the app. **OTP Service**: To use the OTP service, we have integrated a Telegram bot. Follow these steps: - Add the [Tixar Telegram Bot](https://t.me/Tixar_bot) to your Telegram app. - Start a chat with the bot by typing `/start`. - Follow the instructions to add your phone number. This will register your phone number with our OTP service. **Logging In**: When logging in to the Tixar app, enter your phone number. An OTP will be sent to you via Telegram. ## Enquiries If you have any questions or encounter issues, feel free to contact us.
const fs = require('fs').promises; const path = require('path'); const { nanoid } = require('nanoid'); const contactsPath = path.join(__dirname, 'db/contacts.json'); async function listContacts() { const contacts = await fs.readFile(contactsPath); return JSON.parse(contacts); } async function getContactById(contactId) { const contact = await listContacts(); const result = contact.find((item) => item.id === contactId); return result; } async function removeContact(contactId) { const contact = await listContacts(); const index = contact.findIndex((item) => item.id === contactId); if (index === -1) { return null; } const [result] = contact.splice(index, 1); await fs.writeFile(contactsPath, JSON.stringify(contact, null, 2)); return result; } async function addContact(name, email, phone) { const contacts = await listContacts(); const newContact = { name, email, phone, id: nanoid() }; contacts.push(newContact); await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2)); return newContact; } module.exports = { listContacts, addContact, removeContact, getContactById, };
#include <Arduino_FreeRTOS.h> #include <semphr.h> // add the FreeRTOS functions for Semaphores (or Flags). #define HEATING_PIN 4 #define LED_PIN 5 #define COOLING_PIN 6 #define TEMP_PIN A0 #define BLINK_SLOW 30 #define BLINK_MID 20 #define BLINK_FAST 10 #define DISP_STATUS_COOL "COLD" #define DISP_STATUS_MID "Normal" #define DISP_STATUS_HOT "Alert" #define COOLING_RESPONSE 20 #define READING_REFRESH_TIME 10 #define DISP_REFRESH_TIME 50 #define DATA_COLUMN 7 #define ADC_RESOLUTION 1023 #define MAP_MV_MAX_RANGE 5000 #define TEMP 0 #define FAN 1 #define HEAT 2 #define LED 3 #define TEMP_LOW 25 #define TEMP_HIGH 45 uint16_t uint16BlinkSpeed = BLINK_SLOW; String msg2disp[4]; bool cool = true; bool heat = false; // Declare a mutex Semaphore Handle which we will use to manage the Serial Port. // It will be used to ensure only one Task is accessing this resource at any time. SemaphoreHandle_t xSerialSemaphore; //LiquidCrystal_I2C lcd(0x20, 20, 4); // define one Task for AnalogRead void TaskAnalogRead( void *pvParameters ); void TaskLedBlink ( void *pvParameters ); void TaskCooling ( void *pvParameters ); void TaskHeating ( void *pvParameters ); void TaskDisplaying( void *pvParameters ); // the setup function runs once when you press reset or power the board void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); pinMode(LED_PIN, OUTPUT); pinMode(COOLING_PIN, OUTPUT); pinMode(HEATING_PIN, OUTPUT); /* Semaphores are useful to stop a Task proceeding, where it should be paused to wait, because it is sharing a resource, such as the Serial port. Semaphores should only be used whilst the scheduler is running, but we can set it up here. */ if ( xSerialSemaphore == NULL ) // Check to confirm that the Serial Semaphore has not already been created. { xSerialSemaphore = xSemaphoreCreateMutex(); // Create a mutex semaphore we will use to manage the Serial Port if ( ( xSerialSemaphore ) != NULL ) xSemaphoreGive( ( xSerialSemaphore ) ); // Make the Serial Port available for use, by "Giving" the Semaphore. } xTaskCreate( TaskAnalogRead , "AnalogRead" // A name just for humans , 128 // Stack size , NULL //Parameters for the task , 2 // Priority , NULL ); //Task Handle xTaskCreate( TaskLedBlink , "LedBlink" // A name just for humans , 128 // Stack size , NULL //Parameters for the task , 4 // Priority , NULL ); //Task Handle xTaskCreate( TaskCooling , "Cooling" // A name just for humans , 128 // Stack size , NULL //Parameters for the task , 1 // Priority , NULL ); //Task Handle xTaskCreate( TaskDisplaying , "Displaying" // A name just for humans , 128 // Stack size , NULL //Parameters for the task , 3 // Priority , NULL ); //Task Handle xTaskCreate( TaskHeating , "Heating" // A name just for humans , 128 // Stack size , NULL //Parameters for the task , 2 // Priority , NULL ); //Task Handle // Now the Task scheduler, which takes over control of scheduling individual Tasks, is automatically started. } void loop() { // Empty. Things are done in Tasks. } /*--------------------------------------------------*/ /*---------------------- Tasks ---------------------*/ /*--------------------------------------------------*/ void TaskAnalogRead( void *pvParameters __attribute__((unused)) ) // This is a Task. { for (;;) { // read the input on analog pin 0: int sensorValue = analogRead(TEMP_PIN); float analogValue; float tempValue; // See if we can obtain or "Take" the Serial Semaphore. // If the semaphore is not available, wait 5 ticks of the Scheduler to see if it becomes free. if ( xSemaphoreTake( xSerialSemaphore, ( TickType_t ) 5 ) == pdTRUE ) { // We were able to obtain or "Take" the semaphore and can now access the shared resource. // We want to have the Serial Port for us alone, as it takes some time to print, // so we don't want it getting stolen during the middle of a conversion. // print out the value you read: //sensorValue on range 0-1023 digital //Serial.println("ADC " + String(sensorValue)); analogValue = (sensorValue * 4.88 ); tempValue = (analogValue / 10 ); //Serial.println(String(tempValue) + " C"); msg2disp[TEMP] = String(tempValue); if ((int)tempValue < TEMP_LOW) { uint16BlinkSpeed = BLINK_SLOW; msg2disp[LED] = "Cold"; msg2disp[FAN] = "OFF"; msg2disp[HEAT] = "ON"; cool = true; heat = false; } else if ((int)tempValue < TEMP_HIGH ) { uint16BlinkSpeed = BLINK_MID; msg2disp[LED] = "Normal"; msg2disp[FAN] = "OFF"; msg2disp[HEAT] = "OFF"; cool = false; heat = false; } else if ((int)tempValue >= TEMP_HIGH ) { uint16BlinkSpeed = BLINK_FAST; msg2disp[LED] = "Alert"; msg2disp[FAN] = "ON"; msg2disp[HEAT] = "OFF"; cool = false; heat = true; } xSemaphoreGive( xSerialSemaphore ); // Now free or "Give" the Serial Port for others. } vTaskDelay(READING_REFRESH_TIME); // one tick delay (15ms) in between reads for stability } } void TaskLedBlink( void *pvParameters __attribute__((unused)) ) // This is a Task. { for (;;) { // See if we can obtain or "Take" the Serial Semaphore. // If the semaphore is not available, wait 5 ticks of the Scheduler to see if it becomes free. if ( xSemaphoreTake( xSerialSemaphore, ( TickType_t ) 5 ) == pdTRUE ) { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // We were able to obtain or "Take" the semaphore and can now access the shared resource. // We want to have the Serial Port for us alone, as it takes some time to print, // so we don't want it getting stolen during the middle of a conversion. // print out the value you read: xSemaphoreGive( xSerialSemaphore ); // Now free or "Give" the Serial Port for others. } vTaskDelay(uint16BlinkSpeed); // one tick delay (15ms) in between reads for stability } } void TaskCooling( void *pvParameters __attribute__((unused)) ) // This is a Task. { for (;;) { // See if we can obtain or "Take" the Serial Semaphore. // If the semaphore is not available, wait 5 ticks of the Scheduler to see if it becomes free. if ( xSemaphoreTake( xSerialSemaphore, ( TickType_t ) 5 ) == pdTRUE ) { if ( (cool == false) && (heat == true) ){ digitalWrite(COOLING_PIN , HIGH); } else { digitalWrite(COOLING_PIN , LOW); } // We were able to obtain or "Take" the semaphore and can now access the shared resource. // We want to have the Serial Port for us alone, as it takes some time to print, // so we don't want it getting stolen during the middle of a conversion. // print out the value you read: xSemaphoreGive( xSerialSemaphore ); // Now free or "Give" the Serial Port for others. } vTaskDelay(COOLING_RESPONSE); // one tick delay (15ms) in between reads for stability } } void TaskHeating( void *pvParameters __attribute__((unused)) ) // This is a Task. { for (;;) { // See if we can obtain or "Take" the Serial Semaphore. // If the semaphore is not available, wait 5 ticks of the Scheduler to see if it becomes free. if ( xSemaphoreTake( xSerialSemaphore, ( TickType_t ) 5 ) == pdTRUE ) { if ( (cool == true) && (heat == false) ){ digitalWrite(HEATING_PIN , HIGH); } else { digitalWrite(HEATING_PIN , LOW); } // We were able to obtain or "Take" the semaphore and can now access the shared resource. // We want to have the Serial Port for us alone, as it takes some time to print, // so we don't want it getting stolen during the middle of a conversion. // print out the value you read: xSemaphoreGive( xSerialSemaphore ); // Now free or "Give" the Serial Port for others. } vTaskDelay(COOLING_RESPONSE); // one tick delay (15ms) in between reads for stability } } void TaskDisplaying( void *pvParameters __attribute__((unused)) ) // This is a Task. { for (;;) { // See if we can obtain or "Take" the Serial Semaphore. // If the semaphore is not available, wait 5 ticks of the Scheduler to see if it becomes free. if ( xSemaphoreTake( xSerialSemaphore, ( TickType_t ) 5 ) == pdTRUE ) { Serial.println("Temp: "+String(msg2disp[TEMP])); Serial.println("FAN : "+String(msg2disp[FAN])); Serial.println("HEAT: "+String(msg2disp[HEAT])); Serial.println("LED : "+String(msg2disp[LED])); // We were able to obtain or "Take" the semaphore and can now access the shared resource. // We want to have the Serial Port for us alone, as it takes some time to print, // so we don't want it getting stolen during the middle of a conversion. // print out the value you read: xSemaphoreGive( xSerialSemaphore ); // Now free or "Give" the Serial Port for others. } vTaskDelay(DISP_REFRESH_TIME); // one tick delay (15ms) in between reads for stability } }
****************************************************************************************************** * Unless you are a developer or absolutely must have the bleeding-edge latest version of retcon, * * you should stop reading this and download a pre-built Windows binary from the URL in README.md * ****************************************************************************************************** Continue reading if you really want to build a Windows binary yourself Do not expect to be done in 5 minutes. Toolchain: You will need a version of MinGW which supports C++11, including std::thread. The easiest way to satisfy this is to download a suitable build from one of: * http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win32/Personal%20Builds/rubenvb/gcc-4.8-experimental-stdthread/ for 32-bit builds * http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/rubenvb/gcc-4.8-experimental-stdthread/ for 64-bit builds It is possible to compile a more recent MinGW build which will work, how to do so is left as an exercise for the reader. (Your author checked part of the build instructions, and decided against it). Note that attempting a 64-bit build will make finding suitable pre-compiled libraries more difficult. Your author has not yet built for 64-bit Windows in part because of this. Do not be fooled by the presence of a makefile section dedicated to 64-bit Windows builds. Note: All paths labelled as expected by the makefile, are relative to the repository root. wxWidgets: You will need to compile wxWidgets 2.8.12 using the MinGW installed above. * At present USE_EXCEPTIONS in build/msw/config.gcc should be set to 0 to match the retcon makefile * Exactly how you do this step depends on your platform/setup, read the wxWidgets documentation You will then need to copy/symlink/etc. the resulting static libraries and the wxWidgets includes, or edit the makefile, so that gcc can find them. Currently the makefile expects: * wxWidgets includes in wxinclude/ * static libs in wxlib/ zlib, libcurl: You will need to compile zlib and libcurl, or find usable pre-compiled versions. libcurl will need to be compiled with some form of SSL support, the retcon makefile currently assumes that this is OpenSSL. The makefile currently expects: * curl includes in curl/ * zlib includes in zlib/ * zlib/libcurl/ssl/etc. static libs in lib/ Fortunately, usable pre-compiled versions of libcurl with all the dependency libs (zlib and OpenSSL/its dependencies) included exist already. Places to start looking include: * http://curl.haxx.se/download.html * http://curl.haxx.se/gknw.net/ * Your favourite search engine *** YOU MUST ENSURE THAT THE ANY PRE-COMPILED SSL YOU USE IS FREE OF NASTY BUGS *** In particular, do not use compiled versions of OpenSSL with the Heartbleed bug, which also have TLS heart-beats enabled. In practice this means using the very latest version of OpenSSL which is available. Those with sufficiently fortified constitutions can try compiling OpenSSL, some other SSL, zlib and/or libcurl themselves. (Your author has so far successfully refrained from doing this). You will also need to make a cacert.pem, or find an existing one from somewhere. This must be placed in the root of the repository when building, as it is zlibed and embedded into the executable. This uses zpipe, if this is not available you will need to edit the makefile to use something else. Your attention is also drawn to the existance of as of yet unresolved issues associated with linking OpenSSL with GPL code. PCRE: You will need to compile libpcre, or find a usable pre-compiled version. The makefile currently expects: * pcre.h in / * static lib in lib/ sqlite: The Windows section of the retcon makefile includes rules to compile sqlite3. The all-in-one-file sqlite3.c blob and the sqlite3.h header should be placed in sqlite/ Unfortunately, my Windows MinGW/cross build environment is sufficiently old and crufty that I do not remember or have recorded all of the details of how I put it together in the first place. Consequently a large number of details are omitted. Everything not specified is left as an exercise for the reader. Good luck. You are again reminded that pre-built Windows binaries are available at the URL in the readme. Ordinary users do not have to do any of the stuff listed above. Ordinary developers will probably find it easier to just develop on *nix platforms.
#pragma once #include "cappch.h" #include "Cappuccino/Core.h" #include "Cappuccino/Events/Event.h" namespace Cappuccino { struct WindowProps { std::string Title; unsigned int Width; unsigned int Height; WindowProps(const std::string title = "Cappuccino Engine", unsigned int width = 1280, unsigned int height = 720) : Title(title), Width(width), Height(height) {} }; // OS based wondow, that is why it's interface class CAP_API Window { public: using EventCallbackFn = std::function<void(Event&)>; virtual ~Window() {} virtual void OnUpdate() = 0; virtual unsigned int GetWidth() const = 0; virtual unsigned int GetHeight() const = 0; //Window attributes virtual void SetEventCallback(const EventCallbackFn& callback) = 0; virtual void SetVSync(bool enabled) = 0; virtual bool IsVSync() const = 0; virtual void* GetNativeWindow() const = 0; static Window* Create(const WindowProps& props = WindowProps()); }; }
package com.example.runpal.filters import android.location.Location import com.example.runpal.models.PathPoint /** * Even when a device is stationary, the location provided by the GPS satellite will oscillate. * These oscillations should not count as running distance. * Therefore, this class filters them out. * The prinicple is simple - if the location is within 20 meters of the previous n locations, * the previous location is returned. * * On the other hand, since oscillations sometimes, though infrequently, reach up to 100m, * additional moving average filters are used. * * @param posBuff Location moving average filter buffer size. * @param altBuff Altitude moving average filter buffer size. * @property rate Defines the number n of previous locations to check for. * @property radius Defines the minimum distance difference necessary for a position change to be accepted. * @property maxUpdateInterval Defines the maximum allowed interval between two consecutive updates. */ class LocationFilter(posBuff: Int = 10, altBuff: Int = 20, private val rate: Int = 1, private val radius: Double = 15.0, private val maxUpdateInterval: Long = 10000L) { private val latFilter = MovingAverageFilter(posBuff) private val lngFilter = MovingAverageFilter(posBuff) private val altFilter = MovingAverageFilter(altBuff) private val buffer = Array(rate){ Location("") } private var i = 0 fun filter(cur: Location): Location? { cur.latitude = latFilter.filter(cur.latitude) cur.longitude = lngFilter.filter(cur.longitude) cur.altitude = if (cur.altitude == 0.0) buffer[i].altitude else altFilter.filter(cur.altitude) var pass = true for (prev in buffer) if (prev.distanceTo(cur) < radius) { pass = false; break; } if (pass || (cur.time - buffer[i].time > maxUpdateInterval)) { buffer[i++] = cur i %= rate return cur } return null } }
import { Component } from 'react'; import { nanoid } from 'nanoid'; import ContactForm from './ContactForm/ContactForm'; import Filter from './Filter/Filter'; import ContactList from './ContactList/ContactList'; import styles from './App.module.css'; export class App extends Component { state = { contacts: [ { id: 'id-1', name: 'Rosie Simpson', number: '459-12-56' }, { id: 'id-2', name: 'Hermione Kline', number: '443-89-12' }, { id: 'id-3', name: 'Eden Clements', number: '645-17-79' }, { id: 'id-4', name: 'Annie Copeland', number: '227-91-26' }, ], filter: '', }; addContact = ({ name, number }) => { if (this.isDublicate(name)) { alert(`${name} is already in contacts.`); return; } const newContact = { id: nanoid(), name, number, }; this.setState(({ contacts }) => ({ contacts: [newContact, ...contacts], })); }; isDublicate(name) { const normalizedName = name .toLowerCase() .split(' ') .filter(item => item) .join(' '); const { contacts } = this.state; return contacts.some(item => normalizedName === item.name.toLowerCase()); } deleteContact = id => { this.setState(prevState => { const resultList = prevState.contacts.filter(item => item.id !== id); return { contacts: resultList, }; }); }; hangleFilter = e => { const { value } = e.currentTarget; this.setState({ filter: value, }); }; getFilteredContacts() { const { contacts, filter } = this.state; if (!filter) { return contacts; } const normalizedFilter = filter.toLowerCase(); return contacts.filter( item => item.name.toLowerCase().includes(normalizedFilter) || item.number.toLowerCase().includes(normalizedFilter) ); } render() { const filteredContacts = this.getFilteredContacts(); return ( <div className={styles.phonebook}> <h2>Phonebook</h2> <ContactForm onSubmit={this.addContact} /> <h2>Contacts</h2> <Filter hangleFilter={this.hangleFilter} /> <ContactList items={filteredContacts} onDelete={this.deleteContact} /> </div> ); } }
class Node: def __init__(self, key, color, parent, left=None, right=None): self.key = key self.color = color self.parent = parent self.left = left self.right = right class RedBlackTree: def __init__(self): self.NIL_LEAF = Node(None, "black", None) self.root = self.NIL_LEAF def insert(self, key): new_node = Node(key, "red", None, self.NIL_LEAF, self.NIL_LEAF) if self.root == self.NIL_LEAF: self.root = new_node self.root.color = "black" return parent = None current = self.root while current != self.NIL_LEAF: parent = current if key < current.key: current = current.left else: current = current.right new_node.parent = parent if key < parent.key: parent.left = new_node else: parent.right = new_node if new_node.parent == None: new_node.color = "black" return if new_node.parent.parent == None: return self.fix_insert(new_node) def fix_insert(self, node): while node.color == "red" and node.parent.color == "red": if node.parent == node.parent.parent.right: uncle = node.parent.parent.left if uncle.color == "red": node.parent.color = "black" uncle.color = "black" node.parent.parent.color = "red" node = node.parent.parent else: if node == node.parent.left: node = node.parent self.rotate_right(node) node.parent.color = "black" node.parent.parent.color = "red" self.rotate_left(node.parent.parent) else: uncle = node.parent.parent.right if uncle.color == "red": node.parent.color = "black" uncle.color = "black" node.parent.parent.color = "red" node = node.parent.parent else: if node == node.parent.right: node = node.parent self.rotate_left(node) node.parent.color = "black" node.parent.parent.color = "red" self.rotate_right(node.parent.parent) if node == self.root: break self.root.color = "black" def rotate_left(self, node): right_child = node.right node.right = right_child.left if right_child.left != self.NIL_LEAF: right_child.left.parent = node right_child.parent = node.parent if node.parent == None: self.root = right_child elif node == node.parent.left: node.parent.left = right_child else: node.parent.right = right_child right_child.left = node node.parent = right_child def rotate_right(self, node): left_child = node.left node.left = left_child.right if left_child.right != self.NIL_LEAF: left_child.right.parent = node left_child.parent = node.parent if node.parent == None: self.root = left_child elif node == node.parent.right: node.parent.right = left_child else: node.parent.left = left_child left_child.right = node node.parent = left_child def inorder_traversal(self, node): if node != self.NIL_LEAF: self.inorder_traversal(node.left) print(f"{node.key} ({node.color})", end=" ") self.inorder_traversal(node.right) # Example usage: if __name__ == "__main__": rb_tree = RedBlackTree() keys = [10, 20, 30, 40, 50, 60, 70] for key in keys: rb_tree.insert(key) print("Inorder Traversal of Red-Black Tree:") rb_tree.inorder_traversal(rb_tree.root)
<template> <Row :gutter="10" class="set-message-center-page"> <i-col span="24"> <Row> <Form ref="searchForm" :model="searchForm" :label-width="100" inline> <Row> <FormItem :label="$t('userDetail.billLists.time')"> <Row> <Col span="11"> <DatePicker type="date" ref="createTimeStart" :placeholder="$t('userDetail.timeStart')" v-model="searchForm.outAccountDateStart" style="width:100%;" ></DatePicker> </Col> <Col span="2" style="text-align: center"> ~ </Col> <Col span="11"> <DatePicker type="date" ref="createTimeEnd" :placeholder="$t('userDetail.timeEnd')" v-model="searchForm.outAccountDateEnd" ></DatePicker> </Col> </Row> </FormItem> <FormItem :label="$t('userDetail.billLists.type')"> <Row> <Col span="24"> <Select clearable v-model="searchForm.accountType" class="search-select-item" :placeholder="$t('userDetail.billLists.prompt.type')" > <Option v-for="(item, i) in $t('userDetail.billLists.accountType')" :value="item.value" :key="i">{{item.desc}}</Option> </Select> </Col> </Row> </FormItem> <FormItem :label="$t('userDetail.billLists.state')"> <Row> <Col span="24"> <Select clearable v-model="searchForm.status" class="search-select-item" :placeholder="$t('userDetail.billLists.prompt.state')" > <Option v-for="(item, i) in $t('userDetail.billLists.status')" :value="item.value" :key="i">{{item.desc}}</Option> </Select> </Col> </Row> </FormItem> <FormItem :label="$t('userDetail.billLists.accountName')"> <Input v-model="searchForm.accountName" :placeholder="$t('userDetail.billLists.prompt.accountName')"></Input> </FormItem> </Row> <FormItem> <Button type="primary" @click="search">{{$t('common.search')}}</Button> <Button style="margin-left: 30px" @click="cleanSearch">{{$t('common.reset')}}</Button> </FormItem> </Form> </Row> <Row> <Table border class="person-table" :columns="columns" :data="tableData" :loading="tableLoading" style="margin-top: 10px" /> <div style="margin: 10px;overflow: hidden"> <div style="float: right;margin-bottom: 2px;"> <Page :total="totalNumber" :current="currentPage" :page-size-opts="[10, 20, 30, 50]" @on-change="changePage" @on-page-size-change="pageSizeChange" show-elevator show-sizer show-total ></Page> </div> </div> </Row> </i-col> </Row> </template> <script> import { bill } from "@/api/user"; import { formatDate } from "@/assets/js/date"; export default { name: "billList", props: ['id'], data(){ return{ imgLoading: false, tableLoading: false, pageSize: 10, totalNumber: 0, currentPage: 1, searchForm: { outAccountDateStart:null, outAccountDateEnd:null, accountType: null, accountName: null, status: null }, tableData: [], columns: [ { title: this.$t("userDetail.billLists.id"), key: "id", align: "center", minWidth:150 }, { title: this.$t("userDetail.billLists.accountName"), key: "accountName", align: "center", tooltip: true, minWidth:150 }, { title: this.$t("userDetail.billLists.type"), key: "accountType", align: "center", render: (h, params) => { let data = this.$t("userDetail.billLists.accountType"); let type = data.filter(v => { return v.value === params.row.accountType; }); let state = type.length > 0 && type[0].desc ? type[0].desc : ""; return h("div", state); }, minWidth:150 }, { title: this.$t("userDetail.billLists.time"), key: "outAccountDate", align: "center", tooltip: true, minWidth:150 }, { title: this.$t("userDetail.billLists.repaymentTime"), key: "repaymentDate", align: "center", tooltip: true, minWidth:150 }, { title: this.$t("userDetail.billLists.amountDue"), key: "outAccountMoney", align: "center", tooltip: true, minWidth:150 }, { title: this.$t("userDetail.billLists.account"), key: "lastRepayAccount", align: "center", tooltip: true, minWidth:150 }, { title: this.$t("userDetail.billLists.repaidAmount"), key: "repaymentMoney", align: "center", tooltip: true, minWidth:150 }, { title: this.$t("userDetail.billLists.state"), key: "status", align: "center", render: (h, params) => { let data = this.$t("userDetail.billLists.status"); let type = data.filter(v => { return v.value === params.row.status; }); let state = type.length > 0 && type[0].desc ? type[0].desc : ""; return h("div", state); }, minWidth:150 }, ] } }, mounted: function () { this.getTable(); }, methods: { search() { this.currentPage=1; this.getTable(); }, cleanSearch() { this.currentPage=1; this.searchForm.outAccountDateStart = null; this.searchForm.outAccountDateEnd=null; this.searchForm.accountType = null; this.searchForm.accountName = null; this.searchForm.status = null; this.getTable(); }, getTable(){ let queryData=JSON.parse(sessionStorage.getItem("user-details")); let params = { userId:queryData['id'], outAccountDateStart: this.searchForm.outAccountDateStart && formatDate(new Date(this.searchForm.outAccountDateStart), "yyyy-MM-dd hh:mm:ss"), outAccountDateEnd: this.searchForm.outAccountDateEnd && formatDate(new Date(this.searchForm.outAccountDateEnd), "yyyy-MM-dd") + ' 23:59:59', accountType: this.searchForm.accountType, accountName: this.searchForm.accountName, status: this.searchForm.status, pageSize: this.pageSize, currentPage: this.currentPage, }; this.tableLoading = true; bill(params).then(res => { this.tableLoading = false; if(res.data.success){ if( res.data.data && res.data.data.length !==0 ){ this.tableData = res.data.data }else{ this.tableData = [] } this.currentPage = res.data.page.currentPage; this.pageSize = res.data.page.pageSize; this.totalNumber = res.data.page.totalNumber; }else{ this.$Message.error(res.data.message) } }) }, changePage (params) { this.currentPage = params; this.getTable(); }, pageSizeChange (params) { this.pageSize = params; this.getTable() }, } } </script> <style scoped> </style>
import express from "express"; import bodyParser from "body-parser"; import pg from "pg"; const app = express(); const port = 3000; const db = new pg.Client({ user: "postgres", host: 'localhost', database: 'todo', password: 'Divya123', port: 5432, }); db.connect() .then(() => { console.log('Connected to database'); }) .catch(err => { console.error('Error connecting to database:', err); }); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static("public")); async function fetchItems() { try { const result = await db.query("SELECT * FROM items"); return result.rows; } catch (error) { console.error("Error fetching items:", error); return []; } } app.get("/", async (req, res) => { try { const items = await fetchItems(); res.render("index.ejs", { listTitle: "Today", listItems: items, }); } catch (error) { console.error("Error rendering index:", error); res.status(500).send("Internal Server Error"); } }); app.post("/add", async (req, res) => { const item = req.body.newItem; try { await db.query("INSERT INTO items (title) VALUES ($1)", [item]); res.redirect("/"); } catch (err) { console.log(err); } }); app.post("/edit", async (req, res) => { const item = req.body.updatedItemTitle; const id = req.body.updatedItemId; try { await db.query("UPDATE items SET title = ($1) WHERE id = $2", [item, id]); res.redirect("/"); } catch (error) { console.error("Error editing item:", error); // Log the error message res.status(500).send("Error editing item"); } }); app.post("/delete", async(req, res) => { const id = req.body.deleteItemId; try { await db.query("DELETE FROM items WHERE id = ($1)",[id]); res.redirect("/"); } catch (error) { console.error("Error editing item:", error); res.status(500).send("Error editing item"); } // Handle item deletion }); app.listen(port, () => { console.log(`Server running on port ${port}`); });
<template> <form class="mb-3 p-3 shadow" @submit.prevent="submitData"> <div class="mb-3"> <label for="first_name" class="form-label">Name</label> <input ref="name" type="text" class="form-control" :class="{'is-invalid': processing && invalidName}" id="first_name" placeholder="Type first name user" v-model="user.name"> </div> <div class="mb-3"> <label for="last_name" class="form-label">Last Name</label> <input type="text" class="form-control" :class="{'is-invalid': processing && invalidLastName}" id="last_name" placeholder="Type last name user" v-model="user.last_name"> </div> <div class="mb-3"> <label for="email" class="form-label">Email</label> <input type="email" class="form-control" :class="{'is-invalid': processing && invalidEmail}" id="email" placeholder="Type email user" v-model="user.email"> </div> <button type="submit" class="btn btn-primary w-100" @click="submit">Submit</button> <div v-if="error" class="alert alert-danger mt-3 mb-1" role="alert"> You must fill in all the fields </div> <div v-else-if="done" class="alert alert-success mt-3 mb-1"> User added succesfully </div> </form> </template> <script> export default { name: 'FormularioPersona', data() { return { processing: false, error: false, done: false, user: { name: '', last_name: '', email: '' } } }, methods: { submitData() { this.resetStatus() if (this.invalidName || this.invalidLastName || this.invalidEmail) { this.processing = true this.error = true } else { this.$emit('add-user', this.user) this.processing = true this.error = false this.done = true setTimeout(() => { this.done = false }, 3000) this.user = { name: '', last_name: '', email: '' } this.processing = false this.$refs.name.focus() } }, resetStatus() { this.done = false this.error = false } }, computed: { invalidName() { return this.user.name.length < 1 }, invalidLastName() { return this.user.last_name.length < 1 }, invalidEmail() { return this.user.email.length < 1 } } } </script> <style scoped> .invalid { border: 2px solid red; } </style>
package com.springboot.microservice.customer.config; import com.springboot.microservice.customer.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthEntryPointJWT unauthorizedHandler; @Autowired private UserService userService; @Bean public AuthTokenFilter authJwtTokenFilter(){ return new AuthTokenFilter(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(getPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .exceptionHandling() .authenticationEntryPoint(unauthorizedHandler) .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/v1/auth/**").permitAll() .antMatchers("/api/v1/customer","/api/v1/customer/*").hasRole("USER") .antMatchers("/swagger-ui.html","/v2/api-docs","/swagger-resources/**","/webjars/**").permitAll().anyRequest().authenticated(); http.addFilterBefore(authJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); } @Bean public PasswordEncoder getPasswordEncoder(){ return new BCryptPasswordEncoder(); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
from dataclasses import dataclass, asdict from datetime import datetime from math import sqrt, cos, sin from typing import Union, TextIO import numpy as np import serial def convert_to_quaternion(euler: tuple) -> np.ndarray: """Convert euler angle orientation to ndarray quaternion Inputs * euler: 3-tuple of euler angle floats in YPR order Returns * 4x1 quaternion with scalar last """ yaw = euler[0] pitch = euler[1] roll = euler[2] dcm = np.array([ [1, 0, 0], [0, cos(roll), sin(roll)], [0, -sin(roll), cos(roll)], ]) @ np.array([ [cos(pitch), 0, -sin(pitch)], [0, 1, 0], [sin(pitch), 0, cos(pitch)], ]) @ np.array([ [cos(yaw), sin(yaw), 0], [-sin(yaw), cos(yaw), 0], [0, 0, 1], ]) q_sq = (np.array([ [1, 1, -1, -1], [1, -1, 1, -1], [1, -1, -1, 1], [1, 1, 1, 1], ]) @ np.array([ [1], [dcm[0, 0]], [dcm[1, 1]], [dcm[2, 2]], ]) / 4).reshape((4,)) idx = np.argmax(q_sq) if idx == 0: quat = np.array([ 4 * q_sq[0], dcm[0, 1] + dcm[1, 0], dcm[2, 0] + dcm[0, 2], dcm[1, 2] - dcm[2, 1], ]) / (4 * sqrt(q_sq[0])) elif idx == 1: quat = np.array([ dcm[0, 1] + dcm[1, 0], 4 * q_sq[1], dcm[1, 2] + dcm[2, 1], dcm[2, 0] - dcm[0, 2], ]) / (4 * sqrt(q_sq[1])) elif idx == 2: quat = np.array([ dcm[2, 0] + dcm[0, 2], dcm[1, 2] + dcm[2, 1], 4 * q_sq[2], dcm[0, 1] - dcm[1, 0], ]) / (4 * sqrt(q_sq[2])) else: quat = np.array([ dcm[1, 2] - dcm[2, 1], dcm[2, 0] - dcm[0, 2], dcm[0, 1] - dcm[1, 0], 4 * q_sq[3], ]) / (4 * sqrt(q_sq[3])) return quat def checksum(line: str) -> int: chk = 0 if line[0] != '$': raise ValueError(f'checksum line should start with $ but starts with {line[0]}') if '*' in line: raise ValueError("checksum line should have the * and tail removed but didn't") for c in line[1:].encode('ascii'): chk ^= c return chk @dataclass class NavMsg: raw: str timestamp: datetime accel: (float, float, float) gyro: (float, float, float) orientation: (float, float, float) mag: (float, float, float) header: str = '$VNYMR' @classmethod def from_str(cls, raw: str) -> "NavMsg": (msg, chksm) = raw.strip().split('*') (header, ori_y, ori_p, ori_r, gyro_x, gyro_y, gyro_z, accel_x, accel_y, accel_z, mag_x, mag_y, mag_z) = msg.split(',') if header != cls.header: raise ValueError(f'not a {cls.header} message, header was {header}') timestamp = datetime.now() try: accel = ( float(accel_x), float(accel_y), float(accel_z), ) except ValueError: raise ValueError(f'invalid accel {accel_x},{accel_y},{accel_z}') try: gyro = ( float(gyro_x), float(gyro_y), float(gyro_z), ) except ValueError: raise ValueError(f'invalid gyro {gyro_x},{gyro_y},{gyro_z}') try: ori = ( float(ori_r), float(ori_p), float(ori_y), ) except ValueError: raise ValueError(f'invalid orientation {ori_r},{ori_p},{ori_y}') try: mag = ( float(mag_x), float(mag_y), float(mag_z), ) except ValueError: raise ValueError(f'invalid mag {mag_x},{mag_y},{mag_z}') try: chksm = int(chksm, base=16) except ValueError: raise ValueError(f'invalid checksum {chksm}') c = checksum(msg) if chksm != c: raise ValueError(f'invalid checksum {chksm}, expected {c}') return cls( raw=raw, timestamp=timestamp, accel=accel, gyro=gyro, orientation=ori, mag=mag, ) to_dict = asdict class NavDriver: stream: Union[serial.SerialBase, TextIO] def __init__(self, stream: Union[serial.SerialBase, TextIO]): self.stream = stream def setup(self): # Write to reg reg = 75 # async mode 2 -> send to port 2 at fixed rate async_mode = 2 # rate divisor 20 -> 800/20 = 40Hz rate_divisor = 20 # group 1 only groups = 0b0000_0001 # group 1 field # b3 YawPitchRoll # b5 AngularRate # b8 Accel # b10 MagPres group_1_field = 0b0000_0101_0010_1000 self.write(f'$VNWRG,{reg:02},{async_mode:01},{rate_divisor:02},{groups:02x},{group_1_field:04x}') def write(self, line: str): chksm = checksum(line) line_with_chksm = line + f'*{chksm:02x}\r\n' self.stream.write(line_with_chksm.encode('ascii')) def __next__(self) -> NavMsg: while b := self.stream.readline(): if isinstance(b, bytes): header_idx = b.rfind(b'$') if header_idx == -1: continue try: line = b[header_idx:].decode('ascii') except UnicodeDecodeError: print('Failed to decode:', repr(b)) continue else: header_idx = b.rfind('$') if header_idx == -1: continue line = b[header_idx:] try: return NavMsg.from_str(line) except ValueError as e: print(f'Error {e}, skipping "{line.strip()}"') raise StopIteration def __bool__(self): return self.stream.readable() and self.stream.writable() def __iter__(self): return self def close(self): self.stream.close() # Just a quick example/test if __name__ == '__main__': import sys port = sys.argv[1] print(f'Setting up VectorNav on port {port}') # stream = serial.Serial(port, timeout=1) # driver = NavDriver(stream) # driver.setup() file = sys.argv[1] stream = open(file, 'r') driver = NavDriver(stream) for msg in driver: print(msg) print(convert_to_quaternion(msg.orientation))
import React from "react"; import { Modal, ModalProps } from "react-bootstrap"; export default function HelpModal(props: ModalProps) { return ( <Modal show={props.show} onHide={() => { if (props.onHide) props.onHide(); }} aria-labelledby="help-modal-title" > <Modal.Header closeButton> <Modal.Title id="help-modal-title"> How to use FAB Eco Proxy </Modal.Title> </Modal.Header> <Modal.Body> <h3>Usage</h3> <ol> <li>Click "Add Cards"</li> <li>Enter card names in the search field</li> <li>Click "Add" on the cards you wish to print</li> <li>Exit the modal and eventually adjust card quantities</li> <li> Print using your browsers print fuctionality (landscape for US Letter, portrait for A4) </li> </ol> <h3>Feedback</h3> <p> If you have any feedback, please create a{" "} <a href="https://github.com/aongaro/fab-eco-proxy/issues"> github issue </a> , and I will try to respond within a reasonable time. </p> </Modal.Body> </Modal> ); }
#!/usr/bin/python3 #coding:utf-8 import os import numpy as np import time from lib.utils.convert_RGB import convert import torch import torch.nn as nn from torch.autograd import Variable from lib.loss.mse_loss import get_mse_loss_function from lib.loss.L1_loss import get_l1_loss_function from lib.utils.utils import ReplayBuffer, LambdaLR from torchvision.utils import save_image from tensorboardX import SummaryWriter from lib.dataset.landsat_8_dataloader_DA import Get_dataloader from tqdm import tqdm class u2netGANTrainer(object): def __init__(self,gen,dis,optimizer_G,optimizer_D): self.gen = gen.train() self.dis = dis.train() self.optimizer_G = optimizer_G self.optimizer_D = optimizer_D def train(self,args,train_dataloader,test_dataloader,start_epoch,end_epoch): begin_time = time.time() trainloader, testloader = Get_dataloader(enhance=False) patch = (1,args.img_height//(2**args.n_D_layers*4), args.img_width//(2**args.n_D_layers*4)) fake_img_buffer = ReplayBuffer() fake_gt_buffer = ReplayBuffer() writer = SummaryWriter(log_dir='{}'.format(args.log_dir),comment='train_loss') print("======== begin train model ========") best_loss = 3 os.makedirs(args.results_gen_model_dir, exist_ok=True) os.makedirs(args.results_dis_model_dir, exist_ok=True) os.makedirs(args.results_img_dir, exist_ok=True) os.makedirs(args.results_gt_dir, exist_ok=True) os.makedirs(args.log_dir, exist_ok=True) for epoch in range(start_epoch,end_epoch): self.gen.train() self.dis.train() data_loader = tqdm(trainloader) data_loader.set_description('[{} {}/{}'.format('train',epoch,args.end_epoch)) for i, (img,gt,name) in enumerate(data_loader): if torch.cuda.is_available(): img = Variable(img.cuda()) gt = Variable(gt.cuda()) else: img = Variable(img) gt = Variable(gt) valid = Variable(torch.FloatTensor(np.ones((img.size(0), *patch))).cuda(), requires_grad=False) fake = Variable(torch.FloatTensor(np.zeros((img.size(0), *patch))).cuda(), requires_grad=False) ##### Train Generator ####### self.optimizer_G.zero_grad() # identity loss L1_loss = get_l1_loss_function() d0, d1, d2, d3, d4, d5, d6 = self.gen(img) loss_l1 = L1_loss(d0,gt) mse_loss = get_mse_loss_function() loss0 = mse_loss(d0, gt) loss1 = mse_loss(d1, gt) loss2 = mse_loss(d2, gt) loss3 = mse_loss(d3, gt) loss4 = mse_loss(d4, gt) loss5 = mse_loss(d5, gt) loss6 = mse_loss(d6, gt) loss_mse = loss0 + loss1 + loss2 + loss3 + loss4 + loss5 + loss6 # GAN loss fake_gt = self.gen(img)[0] pred_fake = self.dis(fake_gt) gan_loss = get_mse_loss_function() loss_GAN = gan_loss(pred_fake,valid) # Tota loss loss_G = loss_GAN + args.lambda_id * loss_l1 + loss_mse loss_G.backward() nn.utils.clip_grad_norm_(self.gen.parameters(), 2.0) self.optimizer_G.step() batches_done = epoch * len(data_loader) + i ####### Train Discriminator ####### self.optimizer_D.zero_grad() pred_real = self.dis(img) loss_real = gan_loss(pred_real,valid) fake_gt = fake_gt_buffer.push_and_pop(fake_gt) pred_fake = self.dis(fake_gt.detach()) loss_fake = gan_loss(pred_fake,fake) loss_D = (loss_real + loss_fake) / 2 loss_D.backward() nn.utils.clip_grad_norm_(self.dis.parameters(), 2.0) self.optimizer_D.step() writer.add_scalars('{}_train_loss'.format(args.model.arch),{'loss_G':loss_G.data.cpu(),'loss_D':loss_D.data.cpu()}, batches_done) if i % args.interval == 0: print('[epoch %d/%d] [batch %d/%d] [loss: %f]' %(epoch,end_epoch,batches_done,(end_epoch*len(data_loader)),loss_G.item())) if epoch % args.interval == 0 or epoch > args.end_epoch -5: torch.save(self.gen.state_dict(), args.results_gen_model_dir + '/%d-%d_gen.pkl' % (epoch, batches_done)) torch.save(self.dis.state_dict(), args.results_dis_model_dir + '/%d-%d_dis.pkl' % (epoch, batches_done)) fake_gt_RGB = convert(fake_gt[0]) fake_gt_RGB.save(args.results_gt_dir + '%d-%d.png' % (epoch, batches_done)) #test if epoch % 100 ==0 or epoch > args.end_epoch-5: self.gen.eval() self.dis.eval() total_test_loss = 0 data_loader = tqdm(testloader) data_loader.set_description('[{} {}/{}'.format('test', epoch, args.end_epoch)) for i, (img, gt, name) in enumerate(data_loader): if torch.cuda.is_available(): img = Variable(img.cuda()) gt = Variable(gt.cuda()) else: img = Variable(img) gt = Variable(gt) valid = Variable(torch.FloatTensor(np.ones((img.size(0), *patch))).cuda(), requires_grad=False) fake = Variable(torch.FloatTensor(np.zeros((img.size(0), *patch))).cuda(), requires_grad=False) # identity loss L1_loss = get_l1_loss_function() loss_l1 = L1_loss(self.gen(img)[0], gt) # GAN loss fake_gt = self.gen(img)[0] pred_fake = self.dis(fake_gt) gan_loss = get_mse_loss_function() loss_GAN = gan_loss(pred_fake, valid) # Tota loss loss_G = loss_GAN + args.lambda_id * loss_l1 total_test_loss += loss_G.data.cpu() avg_test_loss = total_test_loss/len(testloader) if avg_test_loss < best_loss : best_loss = avg_test_loss torch.save(self.gen.state_dict(),args.results_gen_model_dir + '/best_model_G.pkl') torch.save(self.dis.state_dict(),args.results_dis_model_dir + 'best_model_D.pkl') fake_gt_RGB = convert(fake_gt[0]) fake_gt_RGB.save(args.results_gt_dir + '%d-%d.png' % (epoch, batches_done)) writer.close() print("total_consum_time = %.2f s" % (time.time()-begin_time))
<?php namespace Tests\Controllers; use App\Models\Factories\ImageFactory; use App\Models\Factories\UserFactory; use App\Models\ThreadModel; use App\Models\UserModel; use CodeIgniter\Exceptions\PageNotFoundException; use CodeIgniter\I18n\Time; use Exception; use Tests\Support\Database\Seeds\TestDataSeeder; use Tests\Support\TestCase; /** * @internal */ final class ThreadControllerTest extends TestCase { protected $seed = TestDataSeeder::class; /** * @throws Exception */ public function testCanUserSeeTheCreateADiscussionPage() { $user = fake(UserFactory::class, [ 'username' => 'testuser', ]); $user->addGroup('user'); $response = $this->actingAs($user)->get('discussions/new'); $response->assertOK(); $response->assertSeeElement('.thread-create'); $response->assertSee('Start a new Discussion'); } /** * @throws Exception */ public function testCanUserCreateADiscussion() { $user = fake(UserFactory::class, [ 'username' => 'testuser', ]); $user->addGroup('user'); fake(ImageFactory::class, [ 'user_id' => $user->id, 'name' => 'test_image1.jpg', ]); fake(ImageFactory::class, [ 'user_id' => $user->id, 'name' => 'test_image2.jpg', ]); $fileUrl = base_url('uploads/' . $user->id . '/test_image1.jpg'); $response = $this ->withHeaders([csrf_header() => csrf_hash()]) ->actingAs($user)->post('discussions/new', [ 'title' => 'A new thread', 'category_id' => 2, 'body' => 'Sample body ![](' . $fileUrl . ')', ]); $response->assertStatus(200); $response->assertHeader('hx-redirect', site_url(implode('/', [ 'discussions', 'cat-1-sub-category-1', 'a-new-thread', ]))); $this->seeInDatabase('threads', ['title' => 'A new thread']); $this->seeInDatabase('images', ['name' => 'test_image1.jpg', 'is_used' => 1, 'thread_id' => 3]); $this->seeInDatabase('images', ['name' => 'test_image2.jpg', 'is_used' => 0, 'thread_id' => null]); } /** * @throws Exception */ public function testCanUserCreateADiscussionWithTags() { $user = fake(UserFactory::class, [ 'username' => 'testuser', ]); $user->addGroup('user'); $response = $this ->withHeaders([csrf_header() => csrf_hash()]) ->actingAs($user)->post('discussions/new', [ 'title' => 'A new thread', 'category_id' => 2, 'tags' => 'tag1,tag2', 'body' => 'Sample body', ]); $response->assertStatus(200); $response->assertHeader('hx-redirect', site_url(implode('/', [ 'discussions', 'cat-1-sub-category-1', 'a-new-thread', ]))); $this->seeInDatabase('threads', ['title' => 'A new thread']); $this->seeInDatabase('tags', ['name' => 'tag1']); $this->seeInDatabase('tags', ['name' => 'tag2']); $this->seeInDatabase('taggable', ['taggable_id' => 3, 'taggable_type' => 'threads', 'tag_id' => 1]); $this->seeInDatabase('taggable', ['taggable_id' => 3, 'taggable_type' => 'threads', 'tag_id' => 2]); } /** * @throws Exception */ public function testCanGuestSeeCreateADiscussionPage() { $response = $this->withHeaders([ 'HX-Request' => 'true', ])->get('discussions/new'); $response->assertHeader('HX-Location', '{"path":"\/display-error"}'); $response->assertSessionHas('message', 'You are not allowed to create threads.'); $response->assertSessionHas('status', '403'); } /** * @throws Exception */ public function testCanGuestCreateADiscussion() { $response = $this->withHeaders([ 'HX-Request' => 'true', csrf_header() => csrf_hash(), ])->post('discussions/new', [ 'title' => 'A new thread', 'category_id' => 2, 'body' => 'Sample body', ]); $response->assertHeader('HX-Location', '{"path":"\/display-error"}'); $response->assertSessionHas('message', 'You are not allowed to create threads.'); $response->assertSessionHas('status', '403'); } /** * @throws Exception */ public function testCanUserSeeEditPageOfSomeoneElseThread() { $user = fake(UserFactory::class, [ 'username' => 'testuser', ]); $user->addGroup('user'); $response = $this->actingAs($user)->withHeaders([ 'HX-Request' => 'true', ])->get('discussions/1/edit'); $response->assertHeader('HX-Location', '{"path":"\/display-error"}'); $response->assertSessionHas('message', 'You are not allowed to edit this thread.'); $response->assertSessionHas('status', '403'); } /** * @throws Exception */ public function testCanUserUpdateSomeoneElseThread() { $user = fake(UserFactory::class, [ 'username' => 'testuser', ]); $user->addGroup('user'); $response = $this->actingAs($user)->withHeaders([ 'HX-Request' => 'true', csrf_header() => csrf_hash(), ])->withBody(http_build_query([ 'title' => 'A updated thread', 'category_id' => 2, 'body' => 'Sample updated body', ]))->put('discussions/1/edit'); $response->assertHeader('HX-Location', '{"path":"\/display-error"}'); $response->assertSessionHas('message', 'You are not allowed to edit this thread.'); $response->assertSessionHas('status', '403'); } /** * @throws Exception */ public function testCanUserSeeEditPageOfHisOwnThread() { $user = model(UserModel::class)->find(1); $response = $this->actingAs($user)->get('discussions/1/edit'); $response->assertOK(); $response->assertSee('Edit the thread', 'div'); } /** * @throws Exception */ public function testCanUserUpdateHisOwnThread() { $user = model(UserModel::class)->find(1); fake(ImageFactory::class, [ 'user_id' => $user->id, 'name' => 'test_image1.jpg', ]); fake(ImageFactory::class, [ 'user_id' => $user->id, 'name' => 'test_image2.jpg', ]); $fileUrl = base_url('uploads/' . $user->id . '/test_image2.jpg'); $response = $this->actingAs($user)->withBody(http_build_query([ 'title' => 'A updated thread', 'category_id' => 2, 'body' => 'Sample updated body ![](' . $fileUrl . ')', ]))->withHeaders([csrf_header() => csrf_hash()])->put('discussions/1/edit'); $response->assertOK(); $response->assertSee('A updated thread', 'h3'); $this->seeInDatabase('threads', ['title' => 'A updated thread']); $this->seeInDatabase('images', ['name' => 'test_image1.jpg', 'is_used' => 0, 'thread_id' => null]); $this->seeInDatabase('images', ['name' => 'test_image2.jpg', 'is_used' => 1, 'thread_id' => 1]); } /** * @throws Exception */ public function testCanUserUpdateHisOwnThreadWithTags() { $user = model(UserModel::class)->find(1); $response = $this->actingAs($user)->withBody(http_build_query([ 'title' => 'A updated thread', 'category_id' => 2, 'tags' => 'tag1,tag2', 'body' => 'Sample updated body', ]))->withHeaders([csrf_header() => csrf_hash()])->put('discussions/1/edit'); $response->assertOK(); $response->assertSee('A updated thread', 'h3'); $this->seeInDatabase('threads', ['title' => 'A updated thread']); $this->seeInDatabase('tags', ['name' => 'tag1']); $this->seeInDatabase('tags', ['name' => 'tag2']); $this->seeInDatabase('taggable', ['taggable_id' => 1, 'taggable_type' => 'threads', 'tag_id' => 1]); $this->seeInDatabase('taggable', ['taggable_id' => 1, 'taggable_type' => 'threads', 'tag_id' => 2]); } /** * @throws Exception */ public function testIsUnusedTagsAreCleared() { $user = model(UserModel::class)->find(2); $response = $this->actingAs($user)->withBody(http_build_query([ 'title' => 'A updated thread', 'category_id' => 2, 'tags' => 'tag1,tag2', 'body' => 'Sample updated body', ]))->withHeaders([csrf_header() => csrf_hash()])->put('discussions/2/edit'); $response->assertOK(); $response->assertSee('A updated thread', 'h3'); $this->seeInDatabase('threads', ['title' => 'A updated thread']); $this->seeInDatabase('tags', ['name' => 'tag1']); $this->seeInDatabase('tags', ['name' => 'tag2']); $this->dontSeeInDatabase('tags', ['name' => 'tag3']); $this->seeInDatabase('taggable', ['taggable_id' => 2, 'taggable_type' => 'threads', 'tag_id' => 1]); $this->seeInDatabase('taggable', ['taggable_id' => 2, 'taggable_type' => 'threads', 'tag_id' => 2]); $this->dontSeeInDatabase('taggable', ['taggable_id' => 2, 'taggable_type' => 'threads', 'tag_id' => 3]); } public function testManageAnswerSet() { Time::setTestNow('January 10, 2023 21:50:00'); $user = model(UserModel::class)->find(1); $response = $this->actingAs($user)->withHeaders([ csrf_header() => csrf_hash(), ])->post('thread/1/set-answer', [ 'post_id' => 2, ]); $response->assertHeader('HX-Redirect', site_url('discussions/cat-1-sub-category-1/sample-thread-1')); $this->seeInDatabase('threads', ['id' => 1, 'answer_post_id' => 2]); $this->seeInDatabase('posts', ['id' => 2, 'marked_as_answer' => '2023-01-10 21:50:00']); } public function testManageAnswerUnset() { model(ThreadModel::class)->update(1, ['answer_post_id' => 2]); $user = model(UserModel::class)->find(1); $response = $this->actingAs($user)->withHeaders([ csrf_header() => csrf_hash(), ])->post('thread/1/unset-answer', [ 'post_id' => 2, ]); $response->assertHeader('HX-Redirect', site_url('discussions/cat-1-sub-category-1/sample-thread-1')); $this->seeInDatabase('threads', ['id' => 1, 'answer_post_id' => null]); $this->seeInDatabase('posts', ['id' => 2, 'marked_as_answer' => null]); } public function testManageAnswerNoThread() { $this->expectException(PageNotFoundException::class); $this->expectExceptionMessage('This thread does not exist.'); $user = model(UserModel::class)->find(1); $this->actingAs($user)->withHeaders([ csrf_header() => csrf_hash(), ])->post('thread/999999/set-answer', [ 'post_id' => 2, ]); } public function testManageAnswerNoCredentials() { $user = model(UserModel::class)->find(3); $response = $this->actingAs($user)->withHeaders([ csrf_header() => csrf_hash(), 'HX-Request' => 'true', ])->post('thread/1/set-answer', [ 'post_id' => 2, ]); $response->assertRedirect(); $response->assertHeader('HX-Location', json_encode(['path' => '/display-error'])); $response->assertSessionHas('message', 'You are not allowed to manage an answer for this thread.'); } public function testManageAnswerAlreadySet() { model(ThreadModel::class)->update(1, ['answer_post_id' => 2]); $user = model(UserModel::class)->find(1); $response = $this->actingAs($user)->withHeaders([ csrf_header() => csrf_hash(), ])->post('thread/1/set-answer', [ 'post_id' => 2, ]); $response->assertSessionHas('alerts', ['error' => [ ['message' => 'An answer has already been selected in this thread.', 'seconds' => 5], ]]); } public function testManageAnswerAlreadyUnset() { $user = model(UserModel::class)->find(1); $response = $this->actingAs($user)->withHeaders([ csrf_header() => csrf_hash(), ])->post('thread/1/unset-answer', [ 'post_id' => 2, ]); $response->assertSessionHas('alerts', ['error' => [ ['message' => 'This thread has no answer selected yet.', 'seconds' => 5], ]]); } public function testManageAnswerInvalidPostId() { $user = model(UserModel::class)->find(1); $response = $this->actingAs($user)->withHeaders([ csrf_header() => csrf_hash(), ])->post('thread/1/set-answer', [ 'post_id' => 999999, ]); $response->assertSessionHas('alerts', ['error' => [ ['message' => 'This post does not belong in this thread', 'seconds' => 5], ]]); } }
# *Dasypops schirchi* Miranda-Ribeiro, 1924 **Autores(as)**: Tatianne P. F. Abreu-Jardim, Monira Bruno Bicalho, Bruno R. Ribeiro, Karlo Guidoni, André Yves e Henrique C. Costa ![Fonte: Lucas Aosf - Inaturalist](media/rId20.jpg){width="6.486111111111111in" height="5.119183070866142in"}![Fonte: Lucas Aosf - Inaturalist](media/rId23.png){width="6.486111111111111in" height="4.668665791776028in"} **Nomes populares**: sapo-cara-de-porco **Filo**: Chordata **Classe**: Amphibia **Ordem**: Anura **Família**: Microhylidae ## AVALIAÇÃO DE RISCO DE EXTINÇÃO **Critério**: B1ab(i,ii,iii,iv)+B2ab(i,ii,iii,iv) **Categoria**: EN **Justificativa**: *Dasypops schirchi* é um anfíbio associado a áreas de florestas primárias e secundárias, sendo a única espécie do gênero. Apesar de aparentar ser localmente abundante, sua reprodução explosiva dificulta o avistamento e a obtenção de informações detalhadas sobre a espécie. Na bacia do Rio Doce, sua Extensão de Ocorrência (EOO) é de 2.908 km², com Área de Ocupação (AOO) de 88 km² e entre três a cinco localizações condicionadas a ameaças. O rompimento da barragem de Fundão provavelmente impactou de maneira distinta os locais de ocorrência da espécie, sendo as áreas a montante mais afetadas do que as áreas a jusante do rio. Esse desastre resultou no acúmulo de água e sedimentos, comprometendo a qualidade do habitat. Como anfíbio dependente de ambientes úmidos e reprodução aquática, os rejeitos impactaram negativamente a sobrevivência e o sucesso reprodutivo da espécie. Além disso, cerca de 60% da EOO da espécie foi convertida em pastagens e silvicultura. Diante desse cenário, infere-se declínio contínuo de EOO, AOO, qualidade de habitat e número de localizações condicionadas a ameaças. Como resultado, a espécie foi avaliada como "Em Perigo (EN)" na bacia do Rio Doce. Não há informações disponíveis sobre migração significativa de populações de fora para a bacia do Rio Doce, portanto, a categoria aplicada é mantida. ## INFORMAÇÕES GERAIS *Dasypops schirchi* é um anfíbio terrestre, de atividade diurna e noturna, que tem como habitat áreas de floresta primária e secundária de dossel fechado e bordas florestais (Pereira‐Ribeiro *et al.* 2020). Possui reprodução explosiva, que ocorre por um breve período em poças temporárias na floresta e na borda da floresta (Pombal Jr & Cruz 2016). Ao longo de sua distribuição geográfica, a espécie é considerada rara, embora localmente abundante. Não há informações sobre tamanho e tendência populacional (Pombal Jr & Cruz 2016). Além disso, devido a perda da qualidade de habitat, suspeita-se que a espécie esteja em declínio populacional. ## DISTRIBUIÇÃO GEOGRÁFICA Espécie endêmica da Mata Atlântica, ocorrendo nos estados do Espírito Santo e sul da Bahia (IUCN SSC Amphibian Specialist Group & Instituto Boitatá de Etnobiologia e Conservação da Fauna 2023). ## PRESENÇA EM UNIDADES DE CONSERVAÇÃO NA BACIA DO RIO DOCE A espécie está presente nas seguintes unidades de conservação: REBIO de Sooretama; FLONA de Goytacazes ## ESTRATÉGIAS DE CONSERVAÇÃO **Presença em outras avaliações de risco de extinção:** - Global: VU (IUCN 2023) - Nacional: NT (Brasil 2022) **PATs/PANs**: Espécie-alvo para a conservação da biodiversidade do estado da Bahia (WWF-Brasil 2015). Além disso, ocorre na área de abrangência do projeto Corredor Central da Mata Atlântica -- CCMA, que inclui áreas de extrema importância biológica, prioritárias para a conservação da biodiversidade da Mata Atlântica da região sul do estado da Bahia (Brasil & MMA 2015; WWF-Brasil 2015). **CITES**: Não consta ## PRINCIPAIS AMEAÇAS As ameaças para essa espécie estão relacionadas à modificação e fragmentação do habitat devido ao desmatamento, pastagens e silvicultura. No contexto do rompimento da barragem de Fundão, há registros da espécie na área afetada, e os possíveis impactos para a espécie podem estar relacionados às alterações na condição do habitat decorrentes da erosão e da deposição de rejeitos e detritos, redução na taxa de sobrevivência e/ou sucesso reprodutivo devido a alterações nas cadeias alimentares, bem como por mortalidade direta de indivíduos por inundação (Golder Associates 2016). ## PESQUISAS RECOMENDADAS Pesquisas relacionadas à distribuição, tendência populacional e ameaças. ## REFERÊNCIAS Brasil. (2022). [Portaria MMA Nº 148, de 7 de junho de 2022. Altera os Anexos da Portaria no 443, de 17 de dezembro de 2014, da Portaria no 444, de 17 de dezembro de 2014, e da Portaria no 445, de 17 de dezembro de 2014, referentes à atualização da Lista Nacional de Espécies Ameaçadas de Extinção. Ministério do Meio Ambiente.](https://in.gov.br/en/web/dou/-/portaria-mma-n-148-de-7-de-junho-de-2022-406272733) *Diário Oficial da União*. Brasil & MMA. (2015). Série corredores ecológicos: 12 anos de trabalho pela conservação da biodiversidade animal. Golder Associates. (2016). *Avaliação de Impacto Sobre as Espécies Terrestres Ameaçadas de Extinção* (Relatório No. RT-031_159-515-2282_02-J). Golder Associates Brasil Consultoria e Projetos Ltda; Samarco Mineração S.A./Fundação Renova. IUCN. (2023). [The IUCN Red List of Threatened Species. Version 2023-1.](https://www.iucnredlist.org.) IUCN SSC Amphibian Specialist Group & Instituto Boitatá de Etnobiologia e Conservação da Fauna. (2023). *Dasypops schirchi*. *The IUCN Red List of Threatened Species 2023: e.T57803A172232060*. Disponível em: [https://dx.doi.org/10.2305/IUCN.UK.2023-1.RLTS.T57803A172232060.en.](https://dx.doi.org/10.2305/IUCN.UK.2023-1.RLTS.T57803A172232060.en) Acesso em 11 de abril de 2023. Pereira‐Ribeiro, J., Ferreguetti, Á.C., Bergallo, H.G. & Rocha, C.F.D. (2020). [Changes in the community structure of anurans in the Coastal plain forest, southeastern Brazil](https://doi.org/10.1111/1440-1703.12108). *Ecological Research*, 35, 540--549. Pombal Jr, J.P. & Cruz, C.A.G. (2016). Records on breeding behaviour of a rare neotropical microhylid frog, Dasypops schirchi (Gastrophryninae). *Herpetology Notes*, 9, 317--320. WWF-Brasil. (2015). [Áreas Prioritárias para Conservação da Biodiversidade do Estado da Bahia](hhtp://paisagem.wwf.org.br/projeto.php?id=16).
import kotlin.math.sqrt fun Regex.findAllWithOverlap(input: CharSequence) = generateSequence({ find(input) }, { find(input, it.range.first + 1) }) object Regexp { val integer = "-?\\d+".toRegex() } fun Boolean.toInt() = if (this) 1 else 0 fun String.toLongs() = Regexp.integer.findAll(this).map { it.value.toLong() } fun String.toInts() = Regexp.integer.findAll(this).map { it.value.toInt() } fun quadraticRoots(a: Float, b: Float, c: Float): Pair<Float, Float> { val discriminant = b * b - 4 * a * c val sqrtDiscriminant = sqrt(discriminant) return (-b + sqrtDiscriminant) / (2 * a) to (-b - sqrtDiscriminant) / (2 * a) } fun Sequence<String>.toInts() = map(String::toInts) fun <T> Sequence<T>.repeatForever() = sequence { while (true) { yieldAll(this@repeatForever) } } fun <T> Sequence<T>.repeat(n: Int) = sequence { for (i in 0..<n) { yieldAll(this@repeat) } } fun Sequence<Long>.lcm(): Long = reduce(::lcm) fun lcm(a: Long, b: Long) = (a * b) / gcd(a, b) tailrec fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) fun <T> List<T>.pairs(): List<Pair<T, T>> { val result = ArrayList<Pair<T, T>>(size * (size - 1) / 2) for (i in indices) for (j in i + 1..<size) result.add(this[i] to this[j]) return result } fun <T> List<T>.splitBy(func: (T) -> Boolean): Sequence<List<T>> { var index = 0 val source = this return generateSequence { if (index >= source.size) return@generateSequence null buildList { var next = source.getOrNull(index++) while (next != null && !func(next)) { add(next) next = source.getOrNull(index++) } } } } inline fun BooleanArray.runningSum(func: (Boolean) -> Int) = runningFold(0) { sum, bool -> sum + func(bool) } enum class Direction(val dx: Int, val dy: Int) { Up(0, -1), Down(0, 1), Left(-1, 0), Right(1, 0), ; val vertical = dx == 0 val horizontal = dy == 0 val bitValue = 1 shl ordinal val orthagonals by lazy { if (vertical) arrayOf(Left, Right) else arrayOf(Up, Down) } } data class Position(var x: Int, var y: Int) { operator fun plus(direction: Direction) = Position(x + direction.dx, y + direction.dy) operator fun plusAssign(direction: Direction) { x += direction.dx y += direction.dy } } fun Array<List<Int>>.getOrNull(position: Position) = getOrNull(position.y)?.getOrNull(position.x) fun IntRange.size() = last - first + 1 fun IntRange.gt(x: Int) = if (x >= last) null else maxOf(x+1, first)..last fun IntRange.lt(x: Int) = if (x <= first) null else first..minOf(last, x-1) fun IntRange.gte(x: Int) = if (x > last) null else maxOf(x, first)..last fun IntRange.lte(x: Int) = if (x < first) null else first..minOf(last, x)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- 动态查询 --> <mapper namespace="top.jionjion.mybatis.mapper.StudentDynamicQueryMapper"> <!-- Bean映射规则,当Bean属性与数据库表字段类型不同时,需要指定 --> <resultMap id="StudentResultMap" type="top.jionjion.mybatis.dto.Student"> <id property="id" javaType="java.lang.Integer" column="ID" jdbcType="INTEGER"/> <result property="name" javaType="java.lang.String" column="NAME" jdbcType="VARCHAR"/> <result property="age" javaType="java.lang.Integer" column="AGE" jdbcType="INTEGER"/> <result property="address" javaType="java.lang.String" column="ADDRESS" jdbcType="VARCHAR"/> <result property="birthday" javaType="java.time.LocalDate" column="BIRTHDAY" jdbcType="DATE"/> </resultMap> <!-- if 查询 --> <select id="findStudentByIf" resultMap="StudentResultMap" parameterType="java.lang.Integer"> SELECT s.id, s.name, s.age, s.address, s.birthday FROM student s WHERE s.age > 0 <if test="id != null"> AND s.id = #{id,jdbcType=INTEGER} </if> </select> <!-- choose, when, otherwise 查询 --> <select id="findStudentByExampleChoose" resultMap="StudentResultMap" parameterType="top.jionjion.mybatis.dto.Student"> SELECT s.id, s.name, s.age, s.address, s.birthday FROM student s WHERE s.id >= 0 <choose> <when test="student != null and student.name != null "> AND s.name like concat('%', #{student.name}, '%') </when> <when test="student != null and student.age != null"> AND s.age >= #{student.age} </when> <otherwise> AND s.id != 0 </otherwise> </choose> </select> <!-- where 查询 --> <select id="findStudentByExampleWhere" resultMap="StudentResultMap" parameterType="top.jionjion.mybatis.dto.Student"> SELECT s.id, s.name, s.age, s.address, s.birthday FROM student s <where> <if test="student != null and student.name != null "> AND s.name like concat('%', #{student.name}, '%') </if> <if test="student != null and student.age != null"> AND s.age >= #{student.age} </if> </where> </select> <!-- foreach 查询 --> <select id="findStudentByForeach" resultMap="StudentResultMap" parameterType="java.util.List"> SELECT s.id, s.name, s.age, s.address, s.birthday FROM student s WHERE s.id in <foreach item="item" index="index" collection="ids" open="(" separator="," close=")"> #{item} </foreach> </select> </mapper>
<!DOCTYPE html> <html lang="en"> <head> <title>Title of the document</title> </head> <body> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id='root'></div> <script type="text/babel"> //------------Membuat UI dengan Javascript--------------- //memilih media untuk menampung element //const root = document.querySelector('#root'); //console.log(root); //menambahkan element //const element = document.createElement('h1'); //element.textContent = "Hello with Javascript"; //element.className = 'heading-1' //console.log(element); //melakukan rendering untuk menampilkan konten //root.appendChild(element); //memilih media untuk menampung element const root = document.querySelector('#root'); //menambahkan multiple element //const element = React.createElement('ul', //{className: 'list'}, //React.createElement('li',null,'Apel'), //React.createElement('li',null,'Jeruk'), //React.createElement('li',null,'Anggur') //); //const element = ( //<ul> //<li>Apel</li> //<li>Jeruk</li> //<li>Anggur</li> //</ul> //); const className = 'heading-1'; const element = <h1 className={className}> Hello Ragowo </h1>; //melakukan rendering untuk element ReactDOM.render(element,root); </script> </body> </html>
import BaseCommand from "../structures/BaseCommand"; import { MessageEmbed } from "discord.js"; import type Disc_11 from "../structures/Disc_11"; import type { IMessage } from "../../typings"; export default class SkipCommand extends BaseCommand { public constructor(public client: Disc_11, public readonly path: string) { super(client, path, {}, { name: "skip", description: "Skip the current track", usage: "{prefix}skip" }); } public execute(message: IMessage): any { if (!message.member?.voice.channel) return message.channel.send(new MessageEmbed().setDescription("You're not in a voice channel").setColor("YELLOW")); if (!message.guild?.queue) return message.channel.send(new MessageEmbed().setDescription("There is nothing playing.").setColor("YELLOW")); if (message.member.voice.channel.id !== message.guild.queue.voiceChannel?.id) { return message.channel.send( new MessageEmbed().setDescription("You need to be in the same voice channel as mine").setColor("RED") ); } message.guild.queue.playing = true; message.guild.queue.connection?.dispatcher.resume(); message.guild.queue.connection?.dispatcher.end(); message.channel.send( new MessageEmbed() .setDescription(`⏭ **|** Skipped **[${message.guild.queue.songs.first()?.title as string}](${message.guild.queue.songs.first()?.url as string})**`) .setColor(this.client.config.embedColor) ) .catch(e => this.client.logger.error("SKIP_CMD_ERR:", e)); } }
package com.team2.service.member; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import com.team2.domain.member.MemberDTO; import com.team2.mapper.member.MemberMapper; import com.team2.util.BCrypt; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @Service @AllArgsConstructor @Slf4j public class MemberServiceImpl implements MemberService<MemberDTO> { @Autowired MemberMapper mapper; @Override public boolean isAdmin(MemberDTO dto) { // TODO Auto-generated method stub return false; } @Override public boolean isValid(MemberDTO dto) { // TODO Auto-generated method stub return false; } @Override public MemberDTO preLogin(MemberDTO dto) { MemberDTO result = mapper.preLogin(dto); if (result != null) { return result; } else { return null; } } @Override public MemberDTO login(MemberDTO dto) { MemberDTO plain = dto; MemberDTO hashed = preLogin(plain); // 로그인이 유효한 회원인지 체크 if (hashed != null) { boolean isCorrect = BCrypt.checkpw(plain.getPw(), hashed.getPw()); if (isCorrect) { // 비밀번호 일치 return mapper.login(dto); } else { // 비밀번호 불일치 log.error("** MemberServiceImpl login(): 비밀번호 불일치 **"); dto.setSerial_no(-2); return dto; } } else { log.error("** MemberServiceImpl login(): 입력한 ID에 해당하는 회원이 없음 **"); dto.setSerial_no(-1); return dto; } } @Override public void logout() { // Controller에서 session에 저장된 Attribute 제거 } @Override public Integer join(MemberDTO dto) throws DataIntegrityViolationException { dto.setPw(encrypt(dto.getPw())); return mapper.join(dto); } @Override public Integer modify(MemberDTO dto) throws DataIntegrityViolationException { dto.setPw(encrypt(dto.getPw())); return mapper.update(dto); } @Override public Integer remove(MemberDTO dto) { MemberDTO plain = dto; MemberDTO hashed = preLogin(plain); if (hashed != null) { boolean isCorrect = BCrypt.checkpw(plain.getPw(), hashed.getPw()); if (isCorrect) { // 비밀번호 일치 return mapper.updateValid(dto); } else { // 비밀번호 불일치 log.error("** MemberServiceImpl remove(): 비밀번호 불일치 **"); return -2; } } else { log.error("** MemberServiceImpl remove(): 입력한 ID에 해당하는 회원이 없음 **"); return -1; } } private String encrypt(String plain) { return BCrypt.hashpw(plain, BCrypt.gensalt(12)); } }
var database_uri = 'mongodb+srv://DevonteWhitely:August01@cluster0.fnaqv.mongodb.net/Cluster0?retryWrites=true&w=majority'; // server.js // where your node app starts // init project var express = require('express'); var mongo = require('mongodb'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var shortid = require('shortid'); var dns = require('dns'); var app = express(); var port = process.env.PORT || 3000; // mongoose.connect(process.env.DB_URI); mongoose.connect(database_uri, {useNewUrlParser: true, useUnifiedTopology: true}); // enable CORS (https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) // so that your API is remotely testable by FCC var cors = require('cors'); app.use(cors({optionsSuccessStatus: 200})); // some legacy browsers choke on 204 // http://expressjs.com/en/starter/static-files.html app.use(express.static('public')); // http://expressjs.com/en/starter/basic-routing.html app.get('/', (req, res) => { res.sendFile(__dirname + '/views/index.html'); }); app.get('/timestamp', (req, res) => { res.sendFile(__dirname + '/views/timestamp.html'); }); app.get('/requestHeaderParser', (req, res) => { res.sendFile(__dirname + '/views/requestHeaderParser.html'); }); app.get('/urlShortenerMicroservice', (req, res) => { res.sendFile(__dirname + '/views/urlShortenerMicroservice.html'); }); app.get('/exerciseTracker', (req, res) => { res.sendFile(__dirname + '/views/exerciseTracker.html') }); // your first API endpoint... app.get('/api/hello', function (req, res) { res.json({greeting: 'hello API'}); }); // Handle requests for Header Parser Microservice app.get('/api/whoami', (req, res) => { res.json({ ipaddress: req.ip, language: req.headers["accept-language"], software: req.headers["user-agent"] }); }); // Handle requests for Timestamp Microservice app.get('/api/:date?', (req, res) => { let dateString = req.params.date; let passedInDate = new Date(dateString); let nullDate = new Date(); if (req.params.date == null) { return ( res.json({ unix: nullDate.getTime(), utc: nullDate.toUTCString() }) ); } else if (parseInt(dateString) > 10000) { let unixTime = new Date(parseInt(dateString)); return ( res.json({ unix: unixTime.getTime(), utc: unixTime.toUTCString() }) ); } else if (passedInDate == 'Invalid Date') { return ( res.json({ error : 'Invalid Date' }) ); } else if (passedInDate) { return ( res.json({ unix: passedInDate.getTime(), utc: passedInDate.toUTCString() }) ); } }); // Handle requests for URL Shortener Microservice var ShortURL = mongoose.model('Test', new mongoose.Schema({ short_url: String, original_url: String, suffix: String })); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.post('/api/shorturl', (req, res) => { let client_requested_url = req.body.url; let suffix = shortid.generate(); let newURL = new ShortURL({ original_url: client_requested_url, suffix: suffix }) let badURL = new ShortURL({ error: 'invalid url' }) let shortenedURL = client_requested_url.replace(/(^\w+:|^)\/\//, ''); if (shortenedURL === client_requested_url) { badURL.save((err, doc) => { if (err) return console.log(err); res.json({ error: 'invalid url' }) }) } else { newURL.save((err, doc) => { if (err) return console.log(err); res.json({ short_url: newURL.suffix, original_url: newURL.original_url }); }); } }); app.get('/api/shorturl/:suffix', (req, res) => { let userGeneratedSuffix = req.params.suffix; ShortURL.find({suffix: userGeneratedSuffix}).then(foundUrls => { let urlForRedirect = foundUrls[0]; res.redirect(urlForRedirect.original_url); }); }); // Handle requests for Exercise Tracker var ExerciseUser = mongoose.model('ExerciseUser', new mongoose.Schema({ _id: String, username: String, description: String, duration: Number, date: Date })); app.post('/api/users', (req, res) => { let mongooseGeneratedID = mongoose.Types.ObjectId(); var exerciseUser = new ExerciseUser({ username: req.body.username, _id: mongooseGeneratedID }) exerciseUser.save((err, doc) => { if (err) return console.log(err); res.json({ username: exerciseUser.username, _id: exerciseUser['_id'] }); }); }); app.get('/api/users', (req, res) => { ExerciseUser.find({}, (err, exerciseUsers) => { if (err) return console.log(err); res.json(exerciseUsers); }); }); app.post('/api/users/:_id/exercises', (req, res) => { let currentDate = new Date(); let mongooseGeneratedID = mongoose.Types.ObjectId(); let exerciseUser = new ExerciseUser({ username: req.body.username, _id: mongooseGeneratedID, description: req.body.description, duration: req.body.duration, date: req.body.date }) exerciseUser.save((err, doc) => { if (err) return console.log(err); res.json({ username: exerciseUser.username, _id: exerciseUser['_id'], description: exerciseUser.description, duration: exerciseUser.duration, date: exerciseUser.date === null ? currentDate.toUTCString() : exerciseUser.date.toUTCString() }); }); }); // listen for requests :) var listener = app.listen(port, () => { console.log('Your app is listening on port ' + listener.address().port + '...'); });
<template> <div> <a-card :bordered="false" style="margin-bottom: 10px;"> <!-- 条件搜索 --> <div class="table-page-search-wrapper"> <a-form :labelCol="labelCol" :wrapperCol="wrapperCol"> <a-row :gutter="48"> <a-col :md="6" :sm="24"> <a-form-item label="登录地址"> <a-input v-model="queryParam.ipaddr" placeholder="请输入登录地址" allow-clear @keyup.enter.native="handleQuery"/> </a-form-item> </a-col> <a-col :md="6" :sm="24"> <a-form-item label="操作信息"> <a-input v-model="queryParam.msg" placeholder="请输入操作信息" allow-clear @keyup.enter.native="handleQuery"/> </a-form-item> </a-col> <a-col :md="6" :sm="24"> <a-form-item label="使用状态"> <a-select placeholder="请选择状态" v-model="queryParam.status" style="width: 100%" allow-clear> <a-select-option v-for="(d, index) in statusOptions" :key="index" :value="d.dictValue">{{ d.dictLabel }}</a-select-option> </a-select> </a-form-item> </a-col> <a-col :md="6" :sm="24" v-if="advanced"> <a-form-item label="登录名称"> <a-input v-model="queryParam.loginName" style="width: 100%" allow-clear/> </a-form-item> </a-col> <a-col :md="6" :sm="24" v-if="advanced"> <a-form-item label="登陆时间"> <a-range-picker style="width: 100%" v-model="dateRange" valueFormat="YYYY-MM-DD" format="YYYY-MM-DD" allow-clear/> </a-form-item> </a-col> <a-col> <span class="table-page-search-submitButtons" style="float: right;"> <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button> <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button> <a @click="toggleAdvanced" style="margin-left: 8px"> {{ advanced ? '收起' : '展开' }} <a-icon :type="advanced ? 'up' : 'down'"/> </a> </span> </a-col> </a-row> </a-form> </div> </a-card> <a-card :bordered="false" class="table-card"> <advance-table :columns="columns" :data-source="list" title="登录日志" :loading="loading" rowKey="id" tableKey="monitor-logininfo-Logininfo-table" :isTableConfig="false" :isShowSetBtn="false" @refresh="getList" size="middle" :format-conditions="true" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :pagination="{ current: queryParam.pageNum, pageSize: queryParam.pageSize, total: total, showSizeChanger: true, showLessItems: true, showQuickJumper: true, showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条,总计 ${total} 条`, onChange: changeSize, onShowSizeChange: onSizeChange, }" > <div class="table-operations" slot="button"> <a-button type="danger" v-if="!multiple" :disabled="multiple" @click="handleDelete" v-hasPermi="['monitor:LoginLog:remove']"> <a-icon type="delete" />删除 </a-button> <a-button type="danger" @click="handleClean" v-hasPermi="['monitor:LoginLog:remove']"> <a-icon type="delete" />清空 </a-button> <a-button @click="handleExport" v-hasPermi="['system:LoginLog:export']"> <a-icon type="download" />导出 </a-button> </div> <span slot="status" slot-scope="{text, record}"> <a-badge :status="record.status == '0' ? 'processing' : 'error'" :text=" statusFormat(record) " /> </span> </advance-table> </a-card> </div> </template> <script> import { list, delLoginLog, cleanLoginLog, exportLoginLog } from '@/api/monitor/loginLog' import AdvanceTable from '@/components/pt/table/AdvanceTable' export default { name: 'LoginLog', components: { AdvanceTable }, data () { return { list: [], selectedRowKeys: [], selectedRows: [], // 高级搜索 展开/关闭 advanced: false, // 非单个禁用 single: true, // 非多个禁用 multiple: true, ids: [], loading: false, sunloading: false, total: 0, // 状态数据字典 statusOptions: [], // 日期范围 dateRange: [], labelCol: { span: 6 }, wrapperCol: { span: 18 }, queryParam: { pageNum: 1, pageSize: 10, ipaddr: null, userName: undefined, status: undefined }, addModalRefName: 'addModal', // 添加弹窗ref名称 columns: [ { title: '用户名称', dataIndex: 'userName', align: 'center' }, { title: '登录地址', dataIndex: 'ipaddr', align: 'center' }, { title: '登录地点', dataIndex: 'loginLocation', align: 'center' }, { title: '浏览器', dataIndex: 'browser', align: 'center' }, { title: '操作系统', dataIndex: 'os', align: 'center' }, { title: '状态', dataIndex: 'status', scopedSlots: { customRender: 'status' }, align: 'center' }, { title: '操作信息', dataIndex: 'msg', align: 'center' }, { title: '登录时间', dataIndex: 'loginTime', align: 'center' } ] } }, filters: { }, created () { this.getList() this.getDicts('sys_common_status').then(response => { this.statusOptions = response.data }) }, computed: { }, watch: { }, methods: { onSizeChange (current, size) { this.queryParam.pageNum = 1 this.queryParam.pageSize = size this.getList() }, /** 查询定时任务列表 */ getList () { this.loading = true list(this.addDateRange(this.queryParam, this.dateRange)).then(response => { this.list = response.data.list this.total = response.data.total this.loading = false } ) }, // 执行状态字典翻译 statusFormat (row) { return this.selectDictLabel(this.statusOptions, row.status) }, /** 搜索按钮操作 */ handleQuery () { this.queryParam.pageNum = 1 this.getList() }, /** 重置按钮操作 */ resetQuery () { this.dateRange = [] this.queryParam = { pageNum: 1, pageSize: 10, ipaddr: null, userName: undefined, status: undefined } this.handleQuery() }, onShowSizeChange (current, pageSize) { this.queryParam.pageSize = pageSize this.getList() }, changeSize (current, pageSize) { this.queryParam.pageNum = current this.queryParam.pageSize = pageSize this.getList() }, onSelectChange (selectedRowKeys, selectedRows) { this.selectedRowKeys = selectedRowKeys this.selectedRows = selectedRows this.ids = this.selectedRows.map(item => item.id) this.multiple = !selectedRowKeys.length }, toggleAdvanced () { this.advanced = !this.advanced }, /** 删除按钮操作 */ handleDelete (row) { var that = this const infoIds = row.id || this.ids this.$confirm({ title: '确认删除所选中数据?', // content: '当前选中访问编号为' + infoIds + '的数据', onOk () { return delLoginLog(infoIds) .then(() => { that.onSelectChange([], []) that.getList() that.$message.success( '删除成功', 3 ) }) }, onCancel () {} }) }, /** 清空按钮操作 */ handleClean () { var that = this this.$confirm({ title: '是否确认清空?', content: '此操作将会清空所有登录日志数据项', onOk () { return cleanLoginLog() .then(() => { that.onSelectChange([], []) that.getList() that.$message.success( '清空成功', 3 ) }) }, onCancel () {} }) }, /** 导出按钮操作 */ handleExport () { var that = this this.$confirm({ title: '是否确认导出?', content: '此操作将导出当前条件下所有数据而非选中数据', onOk () { return exportLoginLog(that.queryParam) .then(response => { that.download(response.msg) that.$message.success( '导出成功', 3 ) }) }, onCancel () {} }) } } } </script>
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program 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. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ namespace pocketmine\block; use pocketmine\item\Item; use pocketmine\item\Tool; class GoldOre extends Solid { protected $id = self::GOLD_ORE; /** * GoldOre constructor. */ public function __construct($meta = 0){ $this->meta = $meta; } /** * @return string */ public function getName() : string{ return "Gold Ore"; } /** * @return int */ public function getHardness(){ return 3; } /** * @return int */ public function getToolType(){ return Tool::TYPE_PICKAXE; } /** * @param Item $item * * @return array */ public function getDrops(Item $item) : array{ if($item->isPickaxe() >= 4){ return [ [Item::GOLD_ORE, 0, 1], ]; }else{ return []; } } }
import React from "react"; import PropTypes from "prop-types"; import "./orderItem.css"; function OrderItem(props) { return ( <div className="Order-Item clearfix"> <span className="delete-btn mr-2" onClick={props.delete}> <span className="oi oi-x" title="x" aria-hidden="true" /> </span> <div className="order-item-info"> <span className="name h5"> <strong>{`${props.name} Sandwich`}</strong> </span> <span className="price h5"> <strong>{`$${props.price}`}</strong> </span> <ul>{props.children}</ul> </div> </div> ); }; OrderItem.propTypes = { name: PropTypes.string, price: PropTypes.number, delete: PropTypes.func } export { OrderItem };
package com.fun_todo.memesandtodocombine.ui.todo.roomDbPackage import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase //todo learn why we use version in database - Migration @Database(entities = [TodoEntity::class], version = 1, exportSchema = false) abstract class TodoDatabase : RoomDatabase() { abstract fun getTodoDao(): TodoDAO companion object { // Singleton prevents multiple instances of database opening at the // same time. @Volatile private var INSTANCE: TodoDatabase? = null fun getDatabase(context: Context): TodoDatabase { // if the INSTANCE is not null, then return it, // if it is, then create the database // ?: this is an Elvis operator below return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, TodoDatabase::class.java, "todo_database" ).build() INSTANCE = instance // return instance instance } } } }
import React, { useEffect, useState } from 'react'; import { Loader } from "./"; import { useDispatch, useSelector } from 'react-redux'; import { postQuestion, SET_ERROR, getQuestion, updateQuestion } from '../redux/actions'; import { ToastContainer, toast } from 'react-toastify'; import { BsPlusLg, BsCheck2 } from "react-icons/bs"; import 'react-toastify/dist/ReactToastify.css'; export const Modal = ({ setModalActive, questionId, question }) => { const [isLoading, setIsLoading] = useState(false); const error = useSelector(store => store.error); const [data, setData] = useState({ title: "", topic: "", description: "", link: "", platform: "", difficulty: "1", intuition: "", code: "", solved: false, isFav: false, isPublic: false, }); const user = useSelector(store => store.user); const dispatch = useDispatch(); // useEffect(() => { // // Stopping the scrolling function when the modal was opened // // window.onscroll = function () { // // window.scrollTo(0, 0); // // }; // }, [window.onscroll]) const handleChange = (e) => { if (e.target.type === "checkbox") { // console.log(e.target.name, ":", e.target.checked); setData({ ...data, [e.target.name]: e.target.checked }); } else { // console.log(e.target.name, ":", e.target.value); setData({ ...data, [e.target.name]: e.target.value }); } } const handlePostQuestion = () => { setIsLoading(true); // console.log(46, data); dispatch(postQuestion(user, data)); setTimeout(() => { setIsLoading(false); setModalActive(false); }, 3000) } const handleUpdateQuestion = () => { setIsLoading(true); // console.log(56, data); dispatch(updateQuestion(user, questionId, data)); setTimeout(() => { setIsLoading(false); setModalActive(false); }, 3000) } useEffect(() => { if (questionId) { setData(question); } }, []) return (<> <div className='py-16 absolute bg-[rgba(0,0,0,0.5)] w-full z-[9] h-full mt-12'> <div id="modal-container" className='container m-auto bg-white rounded-lg'> <div className='flex text-lg flex-row-reverse mr-4 pt-4' onClick={() => { setModalActive(false) }}> <BsPlusLg className='rotate-45' /> </div> <form className="space-y-4 p-8" onSubmit={questionId ? (e) => { e.preventDefault(); handleUpdateQuestion() } : (e) => { e.preventDefault(); handlePostQuestion() }} > <div className='flex gap-6'> <div className='grow-[2]'> <label htmlFor="title" className="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">Title <span className='text-red-800'>*</span></label> <input value={data.title} onChange={(e) => { handleChange(e) }} type="text" name="title" id="title" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white" placeholder="Search in sorted and rotated array" required /> </div> <div className='grow'> <label htmlFor="topic" className="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">Topic <span className='text-red-800'>*</span></label> <input value={data.topic} onChange={(e) => { handleChange(e) }} type="text" name="topic" id="topic" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white" placeholder="Array,Binary Search,..." required /> </div> </div> <div> <label htmlFor="description" className="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">Description <span className='text-red-800'>*</span></label> <textarea value={data.description} onChange={(e) => { handleChange(e) }} type="text" name="description" id="description" placeholder={`Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [1, 4, 6, 8, 11, 13, 15] might become [8, 11, 13, 15, 1, 4, 6]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm’s runtime complexity must be in the order of O(log n).`} className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white h-[8rem]" required /> </div> <div className='flex flex-row gap-6'> <div className='grow'> <label htmlFor="link" className="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">Link <span className='text-red-800'>*</span></label> <input value={data.link} onChange={(e) => { handleChange(e) }} type="text" name="link" id="link" placeholder="https://leetcode.com/problems/search-in-rotated-sorted-array/" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white h-12" required /> </div> <div className='grow'> <label htmlFor="platform" className="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">Platform <span className='text-red-800'>*</span></label> <input value={data.platform} onChange={(e) => { handleChange(e) }} type="text" name="platform" id="platform" placeholder="Leetcode" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white h-12" required /> </div> <div className='grow'> <label htmlFor="difficulty" className="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">Difficulty <span className='text-red-800'>*</span></label> <select onChange={(e) => { handleChange(e) }} id="difficulty" name="difficulty" defaultValue={data.difficulty || "1"} className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 h-[3rem]"> <option value="1">Easy</option> <option value="2">Medium</option> <option value="3">Hard</option> </select> </div> </div> <div className='flex flex-row gap-6'> <div className='grow'> <label htmlFor="intuition" className="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">Intuition <span className='text-red-800'>*</span></label> <textarea value={data.intuition} onChange={(e) => { handleChange(e) }} type="text" name="intuition" id="intuition" placeholder="You have given an array which is sorted and rotated, and a target value, you need to return return the index of the target." className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white h-[12rem]" required /> </div> <div className='grow'> <label htmlFor="code" className="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">Code <span className='text-red-800'>*</span></label> <textarea value={data.code} onChange={(e) => { handleChange(e) }} type="text" name="code" id="code" placeholder="You have given an array which is sorted and rotated, and a target value, you need to return return the index of the target." className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white h-[12rem]" required /> </div> </div> <div className='flex flex-row gap-10'> <div> <input onChange={(e) => { handleChange(e) }} type="checkbox" name="solved" id="" className='mr-2 w-4 h-4' checked={data.solved || false} /> <span className="text-sm font-medium text-gray-900 dark:text-gray-300">Solved <span className='text-red-800'>*</span></span> </div> <div> <input onChange={(e) => { handleChange(e) }} type="checkbox" name="isFav" id="" className='mr-2 w-4 h-4' checked={data.isFav || false} /> <span className="text-sm font-medium text-gray-900 dark:text-gray-300">Add a Bookmark <span className='text-red-800'>*</span></span> </div> <div> <input onChange={(e) => { handleChange(e) }} type="checkbox" name="isPublic" id="" className='mr-2 w-4 h-4' checked={data.isPublic || false} /> <span className="text-sm font-medium text-gray-900 dark:text-gray-300">Make Public <span className='text-red-800'>*</span></span> </div> </div> <button type="submit" className='p-2 px-8 rounded-lg text-white font-semibold text-lg bg-[#1072B9]' disabled={isLoading}> {isLoading ? <> <Loader /> <span className='ml-3'>Adding</span> </> : // isSuccess ? // <div className='flex gap-2'> // <BsPlusLg className='text-lg mt-1' /> // <span>Add</span> // </div> // : <>{questionId ? <div className='flex gap-2 -ml-2'> <BsCheck2 className='text-2xl mt-[2px]' /> <span>Done</span> </div> : <div className='flex gap-2'> <BsPlusLg className='text-lg mt-1' /> <span>Add</span> </div> }</> } </button> </form> </div> </div> {error.value && <ToastContainer />} </> ) }
from base64 import b64encode from dataclasses import dataclass from csvbase.value_objs import User @dataclass class ExtendedUser(User): password: str def basic_auth(self) -> str: """The HTTP Basic Auth header value for this user""" hex_api_key = self.hex_api_key() user_pass = f"{self.username}:{hex_api_key}".encode("utf-8") encoded = b64encode(user_pass).decode("utf-8") return f"Basic {encoded}"
# Push to Platinum ## Overview Welcome to the "Push to Platinum" repository! This project serves as a model for GitHub best practices, demonstrating how to enhance your repository and showcase coding maturity. Whether you're a seasoned developer or just starting, these examples will guide you toward creating a polished and collaborative codebase. ## Table of Contents - [Introduction](#introduction) - [Useful Links from the session](#useful-links-from-the-session) ## Introduction "Push to Platinum" provides practical examples and guidelines to help you implement GitHub best practices. Elevate your repository by incorporating these examples, making it a testament to coding maturity and collaborative excellence. ## Useful Links from the session Tier 1: - [Licensing a repository](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/licensing-a-repository) - [About readmes](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-readmes) - [Classifying your repository with topics (a.k.a. tagging)](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/classifying-your-repository-with-topics) - [Protected branches](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/managing-a-branch-protection-rule) Tier 2: - [Setting Guidelines for Repository Contributors](https://docs.github.com/en/communities/setting-up-your-project-for-healthy-contributions/setting-guidelines-for-repository-contributors) - [Codeowners (a.k.a Maintainers)](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners) - [Creating a default community health file](https://docs.github.com/en/communities/setting-up-your-project-for-healthy-contributions/creating-a-default-community-health-file) Tier 3: - [Manually creating a single issue template for your repository](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/manually-creating-a-single-issue-template-for-your-repository) - [Syntax for issue forms](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/syntax-for-issue-forms) - [Creating a pull request template for your repository](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/creating-a-pull-request-template-for-your-repository) - [Packages](https://github.com/features/packages) Tier 4: - [About wikis](https://docs.github.com/en/communities/documenting-your-project-with-wikis/about-wikis) - [About GitHub pages](https://docs.github.com/en/pages/getting-started-with-github-pages/about-github-pages) - [Managing releases in a repository](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository)
package com.apin.qunar.order.service.national.impl; import com.apin.qunar.common.utils.BeanUtil; import com.apin.qunar.order.dao.impl.NationalReturnOrderDaoImpl; import com.apin.qunar.order.dao.impl.NationalReturnPassengerDaoImpl; import com.apin.qunar.order.dao.model.NationalReturnOrder; import com.apin.qunar.order.dao.model.NationalReturnPassenger; import com.apin.qunar.order.domain.national.searchRefundOrderList.NationRefundOrderVO; import com.apin.qunar.order.service.national.SearchRefundOrderListService; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * @outhor ligang * @create 2018-07-30 16:36 */ @Service public class SearchRefundOrderListServiceImpl implements SearchRefundOrderListService { @Autowired private NationalReturnOrderDaoImpl nationalReturnOrderDao; @Autowired private NationalReturnPassengerDaoImpl nationalReturnPassengerDao; @Override public List<NationRefundOrderVO> queryPageList(String merchantNo, String account, String orderNo, String pessengerName, Integer offset, Integer limit) { List<NationalReturnOrder> nationalReturnOrders = null; List<NationalReturnPassenger> passengers = null; if (StringUtils.isNotBlank(pessengerName)) { passengers = nationalReturnPassengerDao.queryBy(merchantNo, orderNo, pessengerName); if (CollectionUtils.isNotEmpty(passengers)) { List<String> orderNos = passengers.stream().map(p -> p.getOrderNo()).collect(Collectors.toList()); nationalReturnOrders = nationalReturnOrderDao.queryPageListBy("", orderNos, offset, limit); } } else { nationalReturnOrders = nationalReturnOrderDao.queryPageListBy("", account, orderNo, offset, limit); List<String> orderNos = nationalReturnOrders.stream().map(p -> p.getOrderNo()).collect(Collectors.toList()); passengers = nationalReturnPassengerDao.queryByOrderNos(orderNos); } return buildNationalOrderDTO(nationalReturnOrders, passengers); } private List<NationRefundOrderVO> buildNationalOrderDTO(final List<NationalReturnOrder> orders, final List<NationalReturnPassenger> passengers) { List<NationRefundOrderVO> nationRefundOrderVOS = new ArrayList<>(); if (CollectionUtils.isEmpty(orders)) { return nationRefundOrderVOS; } NationRefundOrderVO nationRefundOrderVO = null; for (NationalReturnOrder order : orders) { nationRefundOrderVO = BeanUtil.copyProperties(order, NationRefundOrderVO.class); List<NationalReturnPassenger> filterPassenger = passengers.stream().filter(p -> p.getOrderNo().equals(order.getOrderNo())).collect(Collectors.toList()); int returnFee = order.getReturnFee(); nationRefundOrderVO.setReturnPrices(returnFee); nationRefundOrderVO.setPassengers(buildPassengers(filterPassenger)); nationRefundOrderVOS.add(nationRefundOrderVO); } return nationRefundOrderVOS; } private String buildPassengers(List<NationalReturnPassenger> passengers) { StringBuilder passengerBuilder = new StringBuilder(passengers.size() * 5); for (NationalReturnPassenger passenger : passengers) { passengerBuilder.append("/"); passengerBuilder.append(passenger.getName()); } return passengerBuilder.length() < 1 ? "" : passengerBuilder.substring(1).toString(); } @Override public Integer queryCount(final String merchantNo, final String account, final String orderNo, final String pessengerName) { List<NationalReturnPassenger> passengers = null; if (StringUtils.isNotBlank(pessengerName)) { passengers = nationalReturnPassengerDao.queryBy(merchantNo, orderNo, pessengerName); if (CollectionUtils.isNotEmpty(passengers)) { List<String> orderNos = passengers.stream().map(p -> p.getOrderNo()).collect(Collectors.toList()); return nationalReturnOrderDao.queryListCount(orderNos, account); } } else { return nationalReturnOrderDao.queryCount(account, orderNo); } return 0; } }
--- title: "Alcohol consumption by Portuguese students" output: html_notebook author: Shiva Kumar Pendem, Sricharan Cheeti, Kaushik Parvathaneni --- ```{r} library(dplyr) library(tidyverse) library(tidyr) library(corrplot) library(plotly) library(caTools) library(car) ``` ```{r} Mat = read.csv('studentMat.csv') ``` ### Preprocessing #### Converting Non numeric to Numeric ```{r } non_numeric_columns <- names(Mat)[sapply(Mat, function(col) !is.numeric(col))] cat("These are non-numeric columns:", non_numeric_columns, "\n\n") numeric_columns <- names(Mat)[sapply(Mat, is.numeric)] cat("These are numeric columns:", numeric_columns, "\n") ``` We have to convert Non numeric data to numeric data to find the correlation coeff ```{r} # Mat$sex <- ifelse(Mat$sex == 'M', 1, 0) ``` ```{r} # non_numeric_columns <- c('school', 'address', 'famsize', 'Pstatus', 'Mjob', 'Fjob', 'reason', 'guardian', 'schoolsup', 'famsup', 'paid', 'activities', 'nursery', 'higher', 'internet', 'romantic') # for(col in non_numeric_columns) { # if(length(unique(Mat[[col]])) == 2) { # # Label Encoding # levels <- unique(Mat[[col]]) # Mat[[col]] <- ifelse(Mat[[col]] == levels[1], 1, 0) # } else { # # One-Hot Encoding # Mat <- Mat %>% # mutate(!!col := as.factor(!!sym(col))) %>% # spread(!!col, !!col, fill = 0, convert = TRUE) # } # } non_numeric <- names(Mat)[sapply(Mat, function(col) !is.numeric(col))] for (col in non_numeric){ print(paste("The column ", col, "has ", length(unique(Mat[[col]])), ' unique values they are: ')) print((unique(Mat[[col]]))) cat('\n') } ``` ```{r Arranging Binary and non binary columns} binary_columns <- c() multi_unique_columns <- c() # Loop through each column and categorize based on the number of unique values for (col in non_numeric) { num_unique <- length(unique(Mat[[col]])) if (num_unique == 2) { binary_columns <- c(binary_columns, col) } else if (num_unique > 2) { multi_unique_columns <- c(multi_unique_columns, col) } } # for (col in binary_columns) { # unique_vals <- unique(Mat[[col]]) # Mat[[col]] <- ifelse(Mat[[col]] == unique_vals[1], 0, 1) # } print(paste("Binary columns:", paste(binary_columns, collapse = ", "))) cat('\n') print(paste("Multi unique value columns:", paste(multi_unique_columns, collapse = ", "))) ``` ```{r Turing binary columns numeric} for (col in binary_columns) { if ("yes" %in% Mat[[col]] && "no" %in% Mat[[col]]) { # If the column has 'yes' and 'no' values Mat[[col]] <- ifelse(Mat[[col]] == "yes", 1, 0) } else { # For other binary columns unique_vals <- unique(Mat[[col]]) Mat[[col]] <- ifelse(Mat[[col]] == unique_vals[1], 0, 1) print(paste(unique_vals[1],':0', unique_vals[2],':1')) } } ``` ```{r Turing multivalued columns numeric} # Perform one-hot encoding for each column in multi_unique_columns for (col in multi_unique_columns) { # Create a one-hot encoded matrix for the column formula_str <- paste("~ 0 +", col) one_hot <- model.matrix(as.formula(formula_str), data = Mat) # Convert matrix to data frame and set column names one_hot_df <- as.data.frame(one_hot) colnames(one_hot_df) <- gsub("^.\\.", col, colnames(one_hot_df)) # Bind the new one-hot encoded columns to the original data frame Mat <- cbind(Mat, one_hot_df) # Remove the original column Mat[[col]] <- NULL } # View the first few rows of the processed data to verify head(Mat) ``` ```{r} cor_matrix <- cor(Mat, use = "complete.obs") ``` ```{r} corrplot(cor_matrix, method = "circle") ``` ```{r} plot_ly( x = colnames(cor_matrix), y = rownames(cor_matrix), z = cor_matrix, type = "heatmap", colorscale = "Viridis" ) %>% layout(title_text = "Correlation Matrix Heatmap") ``` ```{r} G3_correlation <- cor_matrix[,'G3'] library(plotly) plot_ly(x = names(G3_correlation), y = G3_correlation, type = 'bar') %>% layout(title = "Correlation of G3 with Other Variables", yaxis = list(title = "Correlation Coefficient")) ``` ```{r} print(G3_correlation) ``` ```{r} # Sorting correlations in decreasing order to get top positive correlations top_positive <- sort(G3_correlation, decreasing = TRUE)[1:10] # Sorting correlations in increasing order to get top negative correlations top_negative <- sort(G3_correlation)[1:10] print("Top Positive Correlations:") print(top_positive) print("Top Negative Correlations:") print(top_negative) ``` ```{r} # Sort G3_correlation in increasing order sorted_names <- names(sort(G3_correlation)) # Convert variable names to a factor with levels specified by the sorted order factor_names <- factor(names(G3_correlation), levels = sorted_names) # Plot using plotly plot_ly(x = factor_names, y = G3_correlation, type = 'bar') %>% layout(title = "Correlation of G3 with Other Variables in Increasing Order", yaxis = list(title = "Correlation Coefficient")) ``` ```{r Alc_consumtion} Mat_alc <- Mat ``` ```{r} Mat_alc$Avg_alc <- (Mat_alc$Dalc + Mat_alc$Walc)/2 ``` ```{r} Mat_alc[,c("Avg_alc", "Dalc", "Walc")] ``` ```{r} Mat_alc <- Mat_alc %>% select(-Dalc, -Walc) ``` ```{r} Mat_alc ``` ```{r} Mat_alc <- Mat_alc %>% select(-G1, -G2,-G3) ``` ```{r} corr_mat = cor(Mat_alc) corrplot(corr_mat) ``` ```{r} Avg_alc_correlation <- corr_mat[,'Avg_alc'] plot_ly(x = names(Avg_alc_correlation), y = Avg_alc_correlation, type = 'bar') %>% layout(title = "Correlation of Avg_alc with Other Variables", yaxis = list(title = "Correlation Coefficient")) ``` ```{r} sorted_names <- names(sort(Avg_alc_correlation)) factor_names <- factor(names(Avg_alc_correlation), levels = sorted_names) plot_ly(x = factor_names, y = Avg_alc_correlation, type = 'bar') %>% layout(title = "Correlation of Avg_alc with Other Variables in Increasing Order", yaxis = list(title = "Correlation Coefficient")) ``` ```{r} Avg_alc_correlation ``` ```{r} Mat_alc ``` ```{r} # Assuming your data is in a variable named 'Mat_alc' # 2. Split the data into training and testing sets set.seed(123) # Setting seed for reproducibility split = sample.split(Mat_alc$Avg_alc, SplitRatio = 0.8) train_data = subset(Mat_alc, split == TRUE) test_data = subset(Mat_alc, split == FALSE) # 3. Train a linear regression model using the training set model <- lm(Avg_alc ~ ., data = train_data) # The dot means we are using all other columns as predictors # 4. Evaluate the model using the testing set predictions = predict(model, newdata = test_data) mse = mean((predictions - test_data$Avg_alc)^2) # Mean Squared Error print(mse) # Additionally, you can print a summary of the model to inspect coefficients and other statistics print(summary(model)) ``` ```{r} # Removing redudant variables for 1-hot encoding Mat_alc <- Mat_alc %>% select(-guardianother, -reasonreputation, -Fjobteacher, -Mjobteacher) ``` ```{r} set.seed(123) split = sample.split(Mat_alc$Avg_alc, SplitRatio = 0.8) train_data = subset(Mat_alc, split == TRUE) test_data = subset(Mat_alc, split == FALSE) model <- lm(Avg_alc ~ ., data = train_data) predictions = predict(model, newdata = test_data) mse = mean((predictions - test_data$Avg_alc)^2) print(mse) print(summary(model)) ``` ```{r} vif_model <- vif(model) print(vif_model) ``` ```{r} vif_model[vif_model >= 5] ``` Dropping Fjobother because the VIF value > 5 Generally, * 1 = not correlated. * Between 1 and 5 = moderately correlated. * Greater than 5 = highly correlated. ```{r} vif_model[vif_model > 3 & vif_model < 5] ``` ```{r} vif_model[vif_model <=1] ``` ```{r} Mat_alc <- Mat_alc %>% select(-Fjobother) ``` ```{r} set.seed(123) split = sample.split(Mat_alc$Avg_alc, SplitRatio = 0.8) train_data = subset(Mat_alc, split == TRUE) test_data = subset(Mat_alc, split == FALSE) model <- lm(Avg_alc ~ ., data = train_data) predictions = predict(model, newdata = test_data) mse = mean((predictions - test_data$Avg_alc)^2) print(mse) print(summary(model)) ``` Important Features based on the Significance codes sex, address, traveltime, paid, activities, nursery, famrel, goout, health, Fjobservices ```{r} model_summary <- summary(model) estimates <- model_summary$coefficients[, "Estimate"] ordered_estimates_desc <- estimates[order(-estimates)] print(ordered_estimates_desc) ``` ```{r} library(ggplot2) # Convert ordered estimates to a data frame df_estimates <- data.frame(Predictor = names(ordered_estimates_desc), Estimate = ordered_estimates_desc) # Plot using ggplot2 plot <- ggplot(df_estimates, aes(x = reorder(Predictor, Estimate), y = Estimate)) + geom_bar(stat = "identity", fill = "lightblue") + coord_flip() + labs(title = "Ordered Estimates from the Model", x = "Predictors", y = "Coefficient Value") + theme_minimal() plot ```
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <title>Personal Template</title> <meta content="" name="description"> <meta content="" name="keywords"> <!-- Favicons --> <link href="assets/img/favicon.png" rel="icon"> <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon"> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet"> <!-- Vendor CSS Files --> <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet"> <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet"> <link href="assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet"> <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet"> <link href="assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet"> <!-- icons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <!-- Template Main CSS File --> <link href="assets/css/style.css" rel="stylesheet"> * Template Name: Personal - v4.7.0 * Template URL: https://bootstrapmade.com/personal-free-resume-bootstrap-template/ * Author: BootstrapMade.com * License: https://bootstrapmade.com/license/ </head> <body> <!-- ======= Header ======= --> <header id="header"> <div class="container"> <h1><a href="index.html">Ankita Gutte</a></h1> <h2>I'm a passionate <span>Front-End Developer</span> from India</h2> <nav id="navbar" class="navbar"> <ul> <li><a class="nav-link active" href="#header">Home</a></li> <li><a class="nav-link" href="#about">About</a></li> <li><a class="nav-link" href="#resume">Resume</a></li> <li><a class="nav-link" href="#services">Services</a></li> <li><a class="nav-link" href="#portfolio">Portfolio</a></li> <li><a class="nav-link" href="#contact">Contact</a></li> </ul> <i class="bi bi-list mobile-nav-toggle"></i> </nav><!-- .navbar --> <div class="social-links"> <a href="https://github.com/gutteankita" target="_blank" class="github"><i class="bi bi-github"></i></a> <a href="https://www.linkedin.com/in/ankita-gutte-160795241/" target="_blank" class="linkedin"><i class="bi bi-linkedin"></i></a> </div> </div> </header><!-- End Header --> <!-- ======= About Section ======= --> <section id="about" class="about"> <!-- ======= About Me ======= --> <div class="about-me container"> <div class="section-title"> <h2>About</h2> <p>Learn more about me</p> </div> <div class="row"> <div class="col-lg-4" data-aos="fade-right"> <img src="assets/img/me.jpg" class="img-fluid" alt=""> </div> <div class="col-lg-8 pt-4 pt-lg-0 content" data-aos="fade-left"> <h3>Front-End Developer</h3> <p class="fst-italic"> I'm a Front-End Developer. </p> <div class="row"> <div class="col-lg-6"> <ul> <!-- <li><i class="bi bi-chevron-right"></i> <strong>Birthday:</strong> <span>20 July 2000</span></li> --> <li><i class="bi bi-chevron-right"></i> <strong>Website:</strong> <span>https://github.com/gutteankita</span> </li> <li><i class="bi bi-chevron-right"></i> <strong>Skype:</strong> <span>consult.ankita@outlook.com</span> </li> <li><i class="bi bi-chevron-right"></i> <strong>City:</strong> <span>Hyderabad, INDIA</span></li> </ul> </div> <div class="col-lg-6"> <ul> <!-- <li><i class="bi bi-chevron-right"></i> <strong>Age:</strong> <span>22</span></li> --> <li><i class="bi bi-chevron-right"></i> <strong>Degree:</strong> <span>Bachelor's Degree - (MSCS)</span></li> <li><i class="bi bi-chevron-right"></i> <strong>Email:</strong> <span>ankitagutte2007@gmail.com</span> </li> <li><i class="bi bi-chevron-right"></i> <strong>Freelance:</strong> <span>Available</span></li> </ul> </div> </div> <p> I have a serious passion for working on both front-end and back-end development processes. I design, develop, and maintain fully-fledged and functioning platforms with databases and servers. </p> </div> </div> </div><!-- End About Me --> <!-- ======= Counts ======= --> <div class="counts container"> <div class="row"> <div class="col-lg-3 col-md-6"> <div class="count-box"> <i class="bi bi-emoji-smile"></i> <span data-purecounter-start="0" data-purecounter-end="849" data-purecounter-duration="1" class="purecounter"></span> <p>Commits</p> </div> </div> <div class="col-lg-3 col-md-6 mt-5 mt-md-0"> <div class="count-box"> <i class="bi bi-journal-richtext"></i> <span data-purecounter-start="0" data-purecounter-end="3" data-purecounter-duration="1" class="purecounter"></span> <p>Projects</p> </div> </div> <div class="col-lg-3 col-md-6 mt-5 mt-lg-0"> <div class="count-box"> <i class="bi bi-headset"></i> <span data-purecounter-start="0" data-purecounter-end="560" data-purecounter-duration="1" class="purecounter"></span> <p>Hours Of Support</p> </div> </div> <div class="col-lg-3 col-md-6 mt-5 mt-lg-0"> <div class="count-box"> <i class="bi bi-award"></i> <span data-purecounter-start="0" data-purecounter-end="6" data-purecounter-duration="1" class="purecounter"></span> <p>Certificates</p> </div> </div> </div> </div><!-- End Counts --> <!-- ======= Skills ======= --> <div class="skills container"> <div class="section-title"> <h2>Skills</h2> </div> <div class="row skills-content"> <div class="col-lg-6"> <div class="progress"> <span class="skill">Python <i class="val">95%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="95" aria-valuemin="0" aria-valuemax="100"> </div> </div> </div> <div class="progress"> <span class="skill">Django <i class="val">70%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100"> </div> </div> </div> <!-- <div class="progress"> <span class="skill">Flask <i class="val">50%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"> </div> </div> </div> --> <div class="progress"> <span class="skill">Rest API <i class="val">50%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"> </div> </div> </div> <div class="progress"> <span class="skill">MySQl <i class="val">90%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100"> </div> </div> </div> <div class="progress"> <span class="skill">MongoDB <i class="val">90%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100"> </div> </div> </div> </div> <div class="col-lg-6"> <div class="progress"> <span class="skill">HTML <i class="val">95%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="95" aria-valuemin="0" aria-valuemax="100"> </div> </div> </div> <div class="progress"> <span class="skill">CSS <i class="val">95%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="95" aria-valuemin="0" aria-valuemax="100"> </div> </div> </div> <div class="progress"> <span class="skill">JavaScript <i class="val">80%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100"> </div> </div> </div> <div class="progress"> <span class="skill">React JS <i class="val">90%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100"> </div> </div> </div> <!-- <div class="progress"> <span class="skill">JQuery <i class="val">50%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"> </div> </div> </div> --> <div class="progress"> <span class="skill">SQLite <i class="val">90%</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100"> </div> </div> </div> </div> </div> </div><!-- End Skills --> <!-- ======= Interests ======= --> <!-- <div class="interests container"> <div class="section-title"> <h2>Interests</h2> </div> <div class="row"> <div class="col-lg-3 col-md-4"> <div class="icon-box"> <i class="ri-calendar-todo-line" style="color: #ffbb2c;"></i> <h3>CRM</h3> </div> </div> <div class="col-lg-3 col-md-4 mt-4 mt-md-0"> <div class="icon-box"> <i class="ri-bar-chart-box-line" style="color: #5578ff;"></i> <h3>ERP</h3> </div> </div> <div class="col-lg-3 col-md-4 mt-4 mt-md-0"> <div class="icon-box"> <i class="ri-bank-card-line" style="color: #e80368;"></i> <h3>Payment</h3> </div> </div> <div class="col-lg-3 col-md-4 mt-4 mt-lg-0"> <div class="icon-box"> <i class="ri-luggage-cart-line" style="color: #e361ff;"></i> <h3>Cart</h3> </div> </div> <div class="col-lg-3 col-md-4 mt-4"> <div class="icon-box"> <i class="ri-coupon-line" style="color: #47aeff;"></i> <h3>Coupons</h3> </div> </div> <div class="col-lg-3 col-md-4 mt-4"> <div class="icon-box"> <i class="ri-store-line" style="color: #ffa76e;"></i> <h3>Kanban </h3> </div> </div> <div class="col-lg-3 col-md-4 mt-4"> <div class="icon-box"> <i class="ri-file-shred-line" style="color: #11dbcf;"></i> <h3>HR</h3> </div> </div> <div class="col-lg-3 col-md-4 mt-4"> <div class="icon-box"> <i class="ri-chat-1-line" style="color: #4233ff;"></i> <h3>Chat</h3> </div> </div> <div class="col-lg-3 col-md-4 mt-4"> <div class="icon-box"> <i class="ri-profile-line" style="color: #b2904f;"></i> <h3>Portfolio</h3> </div> </div> <div class="col-lg-3 col-md-4 mt-4"> <div class="icon-box"> <i class="ri-base-station-line" style="color: #b20969;"></i> <h3>Social Media</h3> </div> </div> <div class="col-lg-3 col-md-4 mt-4"> <div class="icon-box"> <i class="ri-file-list-3-line" style="color: #ff5828;"></i> <h3>Workflow</h3> </div> </div> <div class="col-lg-3 col-md-4 mt-4"> <div class="icon-box"> <i class="ri-basketball-line" style="color: #29cc61;"></i> <h3>Sports</h3> </div> </div> </div> </div> --> <!-- End Interests --> </section><!-- End About Section --> <!-- ======= Resume Section ======= --> <section id="resume" class="resume"> <div class="container"> <div class="section-title"> <h2>Resume</h2> <p>Check My Resume</p> </div> <div class="row"> <div class="col-lg-6"> <h3 class="resume-title">Sumary</h3> <div class="resume-item pb-0"> <h4>Ankita Gutte</h4> <p><em>Seeking an innovative and responsible position wherein my technical prowess can be utilized appropriately, with exposure to new areas to enable me to make useful contributions for the benefit of the company.</em></p> <p> <ul> <li>Hyderabad, INDIA</li> <li>consult.ankita@outlook.com</li> </ul> </p> </div> <h3 class="resume-title">Education</h3> <div class="resume-item"> <h4>Bachelor of Science (MSCS) </h4> <h5>2018 - 2021</h5> <p><em>Nishitha Degree College, Nizamabad, Telangana</em></p> <p>Percentage/CGPA : 8.74</p> </div> <h3 class="resume-title">Certifications</h3> <div class="resume-item"> <h4>NXTWAVE</h4> <h5>2023 </h5> <p><em>Certificates: HTML, CSS, JavaScript, React JS, Node JS, Express JS, SQL</em></p> </div> <div class="resume-item"> <h4>Durga Software Solutions (HYDERABAD)</h4> <h5>2022 </h5> <p><em>Certificates: Python, Django and Rest API</em></p> </div> </div> <div class="col-lg-6"> <h3 class="resume-title">Professional Certificates</h3> <div class="resume-item"> <h4>Internship Certificate</h4> <h5>Python Developer (Oct 2022 - Apr 2023) </h5> <p><em>Rehlat, Hyderabad </em></p> <p> Assisted in the development and maintenance of Python-based applications, utilizing Django framework for web development tasks. Tasks included implementing new features, debugging issues, and ensuring the scalability and performance of Django-based web applications. Collaborated with team members to design and implement Django models, views, templates, and forms, following best practices for web development. Learned and applied Python programming and Django concepts under mentorship <!-- <ul> <li>Develop SQLite Database for User management and User profiles. </li> <li>Create an Admin Panel to manage registered users. </li> <li>Login and profile page development for users. </li> <li>Blog or article section interface for users and admin. </li> <li>Sequence diagram for analyizing stucture. </li> <li>User input field validations and edit or delete user data. </li> </ul> --> </p> </div> <div class="resume-item"> <h4>Present:</h4> <h5>Nxtwave Disruptive Technologie</h5> <p><em>Industry Ready Certification in Full-stack Development</em></p> <p> <!-- <ul> <li>Currently, working in Rehlat as a Python Developer.</li> <li>Good Knowledge of Dual Databases i.e., Relational and NonRelational. </li> </ul> --> At Nxtwave Disruptive Technologies, I've mastered a range of technologies including HTML, CSS, JavaScript, React, Node.js, and Express. Through practical experience, I've built several websites, gaining expertise in frontend and backend development. This platform is an excellent resource for skill acquisition and job readiness, offering a comprehensive curriculum from basics to advanced levels. </p> <h3 class="resume-title">Skills</h3> <div class="resume-item"> <h4>Technical Skills</h4> <h5>Programming Languages, Databases and OS </h5> <p><em>HTML, CSS, JavaScript, React JS, Python, Node JS, Express JS, Django, Rest API, MySQl, MongoDB, SQLite, Ubuntu, Windows</em></p> </div> </div> </div> </div> </section><!-- End Resume Section --> <!-- ======= Services Section ======= --> <section id="services" class="services"> <div class="container"> <div class="section-title"> <h2>Services</h2> <p>Full-stack Development</p> </div> <div class="row"> <div class="col-lg-4 col-md-6 d-flex align-items-stretch"> <div class="icon-box"> <div class="icon"><i class="fab fa-html5"></i></div> <h4> HTML </h4> <p> Markup language used to structure content on web pages, defining elements like headings, paragraphs, and images. </p> </div> </div> <div class="col-lg-4 col-md-6 d-flex align-items-stretch"> <div class="icon-box"> <div class="icon"><i class="fab fa-css3-alt"></i></div> <h4> CSS </h4> <p> Style sheet language that controls the appearance of HTML elements, including aspects like colors, fonts, margins, and positioning. </div> </div> <div class="col-lg-4 col-md-6 d-flex align-items-stretch"> <div class="icon-box"> <div class="icon"><i class="fab fa-js-square"></i></div> <h4> JavaScript </h4> <p> Dynamic scripting language for web development, used to add interactivity and functionality to web pages. </p> </div> </div> <div class="col-lg-4 col-md-6 d-flex align-items-stretch"> <div class="icon-box"> <div class="icon"><i class="fab fa-react"></i></div> <h4> React JS </h4> <p> React is JavaScript library for building user interfaces, developed by Facebook.</p> </div> </div> <div class="col-lg-4 col-md-6 d-flex align-items-stretch"> <div class="icon-box"> <div class="icon"><i class="fab fa-node"></i></div> <h4> Node JS </h4> <p> Server-side JavaScript runtime for building scalable web applications. </p> </div> </div> <div class="col-lg-4 col-md-6 d-flex align-items-stretch"> <div class="icon-box"> <div class="icon"><i class="fas fa-code"></i></div> <h4> Express JS </h4> <p> Minimalist web framework for Node.js, simplifying backend development.</p> </div> </div> <div class="col-lg-4 col-md-6 d-flex align-items-stretch"> <div class="icon-box"> <div class="icon"><i class="bx bxl-python"></i></div> <h4> Python </h4> <p> Python is a computer programming language often used to build websites and software, automate tasks, and conduct data analysis. </p> </div> </div> <div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4 mt-md-0"> <div class="icon-box"> <div class="icon"><i class="bx bxl-django"></i></div> <h4><a href="">Django</a></h4> <p> Django is a high-level Python web framework that enables rapid development of secure and maintainable websites. </p> </div> </div> <div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4 mt-md-0"> <div class="icon-box"> <div class="icon"><i class="bx bxs-user"></i></div> <h4><a href="">REST API</a></h4> <p> RESTful API is an interface that two computer systems use to exchange information securely over the internet. </p> </div> </div> <div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4"> <div class="icon-box"> <div class="icon"><i class="fas fa-database"></i></div> <h4><a href="">SQL</a></h4> <p> Language for managing relational databases, handling tasks like data querying and manipulation, essential for efficient data storage and retrieval in applications. </p> </div> </div> <div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4"> <div class="icon-box"> <div class="icon"><i class='bx ri-database-2-line'></i></div> <h4><a href="">MongoDB</a></h4> <p>MongoDB is an open source NoSQL database management program. NoSQL is used as an alternative to traditional relational databases.</p> </div> </div> <div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4"> <div class="icon-box"> <div class="icon"><i class="bx ri-database-2-line"></i></div> <h4><a href="">MySQl</a></h4> <p>A serverless compute service that enables you to run containers easily and quickly without managing any infrastructure</p> </div> </div> </div> </div> </section><!-- End Services Section --> <!-- ======= Portfolio Section ======= --> <section id="portfolio" class="portfolio"> <div class="container"> <div class="section-title"> <h2>Portfolio</h2> <p>My Works</p> </div> <div class="row"> <div class="col-lg-12 d-flex justify-content-center"> <ul id="portfolio-flters"> <li data-filter="*" class="filter-active">All</li> <li data-filter=".filter-app" data-bs-toggle="tooltip" data-bs-placement="top" title="Coming Soon">App</li> <li data-filter=".filter-card" data-bs-toggle="tooltip" data-bs-placement="top" title="Coming Soon">Card </li> <li data-filter=".filter-web">Web</li> </ul> </div> </div> <div class="row portfolio-container"> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-2.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Web 1</h4> <p>Web</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-2.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Web 3"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" data-gallery="portfolioDetailsGallery" data-glightbox="type: external" class="portfolio-details-lightbox" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-5.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Web 2</h4> <p>Web</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-5.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Web 2"><i class="bx bx-plus"></i></a> <a href="portfolio-details1.html" data-gallery="portfolioDetailsGallery" data-glightbox="type: external" class="portfolio-details-lightbox" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-9.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Web 3</h4> <p>Web</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-9.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Web 3"><i class="bx bx-plus"></i></a> <a href="portfolio-details2.html" data-gallery="portfolioDetailsGallery" data-glightbox="type: external" class="portfolio-details-lightbox" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> </div> </div> </section><!-- End Portfolio Section --> <!-- ======= Contact Section ======= --> <section id="contact" class="contact"> <div class="container"> <div class="section-title"> <h2>Contact</h2> <p>Contact Me</p> </div> <div class="row mt-2"> <div class="col-md-6 d-flex align-items-stretch"> <div class="info-box"> <i class="bx bx-map"></i> <h3>My Address</h3> <p>Hyderabad, Telangana 500032</p> </div> </div> <div class="col-md-6 mt-4 mt-md-0 d-flex align-items-stretch"> <div class="info-box"> <i class="bx bx-share-alt"></i> <h3>Social Profiles</h3> <div class="social-links"> <a href="https://github.com/gutteankita" class="github"><i class="bi bi-github"></i></a> <a href="https://www.linkedin.com/in/ankita-gutte-160795241/" class="linkedin"><i class="bi bi-linkedin"></i></a> </div> </div> </div> <div class="col-md-6 mt-4 d-flex align-items-stretch"> <div class="info-box"> <i class="bx bx-envelope"></i> <h3>Email Me</h3> <p>ankitagutte2007@gmail.com</p> </div> </div> <div class="col-md-6 mt-4 d-flex align-items-stretch"> <div class="info-box"> <i class="bx bx-phone-call"></i> <h3>Mobile No</h3> <p>7798779323</p> </div> </div> </div> <!-- Vendor JS Files --> <script src="assets/vendor/purecounter/purecounter.js"></script> <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <script src="assets/vendor/glightbox/js/glightbox.min.js"></script> <script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script> <script src="assets/vendor/swiper/swiper-bundle.min.js"></script> <script src="assets/vendor/waypoints/noframework.waypoints.js"></script> <script src="assets/vendor/php-email-form/validate.js"></script> <!-- Template Main JS File --> <script src="assets/js/main.js"></script> </div> </section> </body> </html>
import { fireEvent, screen } from '@testing-library/react'; import { BrowserRouter } from 'react-router-dom'; import { renderWithProviders } from '../../../helpers/test-utils'; import RulesContext from '../RulesContext'; import { useNavigate } from 'react-router-dom'; jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useNavigate: jest.fn(), })); describe('Rules context component testing', () => { test('should render component', () => { renderWithProviders( <BrowserRouter> <RulesContext /> </BrowserRouter> ); const rules = screen.queryByText('Rules'); expect(rules).not.toBeNull(); }); test('should call navigate after clicking btn', () => { const navigate = jest.fn(); // @ts-ignore useNavigate.mockReturnValue(navigate); renderWithProviders( <BrowserRouter> <RulesContext /> </BrowserRouter> ); const btn = screen.getByTestId('confirm-button'); fireEvent.click(btn); expect(navigate).toBeCalled(); }); });
import React, { startTransition, useEffect, useRef, useState, useTransition } from "react"; import NavBar from "../Acceuil/NavBar/NavBar"; import "./DiseaseSearch.css" import"https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.2/autocomplete-lhc.min.js"; import 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js'; import { Helmet } from "react-helmet"; import axios from "axios"; import DisplayData from "./DisplayData/DisplayData"; export default function DiseaseSearch() { const SearchDInput=useRef() const [dataJ,setdataJ]= useState([]) const [notFound,setNotFound] = useState(false) const [isPending,startTransition] = useTransition() async function HandleSearchDisease(e) { e.preventDefault() startTransition(()=> { const xhr=new XMLHttpRequest() xhr.open('GET','https://wsearch.nlm.nih.gov/ws/query?db=healthTopics&term='+SearchDInput.current.value,true); xhr.onload = ()=>{ var data = xhr.responseXML.getElementsByTagName("document") var summary = xhr.responseXML.getElementsByName("FullSummary") var title = xhr.responseXML.getElementsByName("title") var sousTitle = xhr.responseXML.getElementsByName("altTitle") var url = xhr.responseXML.getElementsByTagName("document") var orgName = xhr.responseXML.getElementsByName("organizationName") var i=0 var dataJson=[] for (let index = 0; index < data.length; index++) { // <DisplayData title={title[index]} sousTitle={sousTitle[index]} orgName={orgName[index]} url={url[index]} summary={summary[index]} /> var j={} j.title=title[index].childNodes[0].nodeValue j.summary=summary[index].childNodes[0].nodeValue j.sousTitle=sousTitle[index].childNodes[0].nodeValue j.url=url[index].getAttribute("url") j.orgName=orgName[index].childNodes[0].nodeValue dataJson.push(j) } setdataJ(dataJson) dataJson.length==0 ? setNotFound(true) : setNotFound(false) } xhr.send(); }) } return( <> <div className="DiseaseSearch-container"> <div className="DiseaseSearch-content"> <form onSubmit={HandleSearchDisease}> <div className="row DiseaseSearch-title text-center"> <div className="col-12"> <h1>Disease Search</h1> </div> </div> <div className="row DiseaseSearch-input"> <input type="text" id="condition" className="form-control text-center" placeholder="search for Diesease Information " ref={SearchDInput} required></input> <Helmet> <script> new Def.Autocompleter.Search('condition', 'https://clinicaltables.nlm.nih.gov/api/conditions/v3/search');</script> </Helmet> </div> <div className="row DiseaseSearch-btn"> <button type="button" className="btn btn-success" onClick={HandleSearchDisease}>Search</button> </div> <div className="getdata-container "> { isPending ? <div className="notfound-container"> <div className="row notfound-row"> <div className="offset-3 col-6 d-flex justify-content-center"> <div className="loading-picture "></div> </div> </div> </div> : dataJ!=[] ? dataJ.map(item =>{ return <div className="row data-cards "> <div className="col-12 d-flex justify-content-center"> <DisplayData title={item.title} sousTitle={item.sousTitle} orgName={item.orgName} url={item.url} summary={item.summary}/> </div> </div> }) : null } { notFound==true ? <div className="notfound-container"> <div className="row notfound-row"> <div className="offset-lg-3 col-lg-6 col-12 d-flex justify-content-center"> <div className="notfound-picture "></div> </div> </div> </div> : null } </div> </form> </div> </div> </> ) }
<?php namespace App\Models; use Laravel\Sanctum\HasApiTokens; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use App\Traits\HasPermissions; class User extends Authenticatable implements JWTSubject { use HasApiTokens, HasFactory, Notifiable,HasPermissions; protected $fillable = ['name', 'address', 'phone', 'image', 'gender', 'birthday', 'email', 'password', 'position_id', 'group_id' ]; protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array<int, string> */ // protected $fillable = [ // 'name', // 'email', // 'password', // ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', ]; public function getJWTIdentifier() { return $this->getKey(); } /** * Return a key value array, containing any custom claims to be added to the JWT. * * @return array */ public function getJWTCustomClaims() { return []; } public function group() { return $this->belongsTo(Group::class, 'group_id', 'id'); } public function products() { return $this->hasMany(Product::class, 'user_id', 'id'); } }
import styled from "styled-components"; import { Dispatch, SetStateAction, useState, useRef, useCallback } from "react"; import upload from "../../assets/upload.svg"; import { useCertificateUserApi } from "../../utils/api/user"; interface Props { setModalState: Dispatch<SetStateAction<boolean>>; } const CertifiedModal = ({ setModalState }: Props) => { const [inputState, setInputState] = useState<string>(); const [imageSrc, setImageSrc]: any = useState(null); const inputRef = useRef<HTMLInputElement | null>(null); const [btnState, setBtnState] = useState<boolean>(true); const closeModal = () => { setModalState(false); }; const onChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => { const { value } = e.target; setInputState(value); if (inputState === "") { setBtnState(true); } else { setBtnState(false); } }; const onUpload = (e: any) => { const file = e.target.files[0]; const reader = new FileReader(); reader.readAsDataURL(file); return new Promise<void>((resolve) => { reader.onload = () => { setImageSrc(reader.result || null); // 파일의 컨텐츠 resolve(); }; }); }; const onUploadImageButtonClick = useCallback(() => { if (!inputRef.current) { return; } inputRef.current.click(); }, []); const { mutate: certificate } = useCertificateUserApi(); const onClickCertificate = () => { certificate({ certificate: inputState! }); setModalState(false); }; return ( <ModalWrapper> <Wrapper> <input onChange={onChangeInput} value={inputState} type="text" name="certificate" placeholder="자격증 및 인증서를 작성해주세요." /> <UploadBtn onClick={onUploadImageButtonClick}> <input type="file" accept="image/*" ref={inputRef} onChange={onUpload} /> <img src={upload} alt="" /> <p>Upload File</p> </UploadBtn> <BtnWrapper> <CancellButton onClick={closeModal}>취소하기</CancellButton> <NextButton disabled={btnState} onClick={onClickCertificate}> 인증하기 </NextButton> </BtnWrapper> </Wrapper> </ModalWrapper> ); }; const ModalWrapper = styled.div` width: 100%; height: 100vh; position: fixed; top: 0; left: 0; background-color: rgba(33, 33, 33, 0.3); display: flex; justify-content: center; align-items: center; z-index: 101 !important; `; const Wrapper = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; width: 680px; height: 380px; padding: 50px 36px; background-color: ${({ theme }) => theme.colors.white}; border-radius: 16px; z-index: 99; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); > input { width: 100%; height: 50px; border-radius: 12px; margin-bottom: 20px; padding: 12px 25px; border: 1px solid ${({ theme }) => theme.colors.grayScale.Gray}; background-color: ${({ theme }) => theme.colors.grayScale.Light_Gray}; :focus { background-color: ${({ theme }) => theme.colors.white}; } } `; const BtnWrapper = styled.div` width: 100%; display: flex; justify-content: space-between; `; const UploadBtn = styled.div` cursor: pointer; display: flex; justify-content: space-between; align-items: center; width: 170px; height: 40px; padding: 8px 20px; background-color: ${({ theme }) => theme.colors.white}; border: 1px solid ${({ theme }) => theme.colors.greanScale.main}; border-radius: 10px; margin-bottom: 130px; margin-left: 430px; > input { display: none; } > p { font-weight: 590; font-size: 18px; color: ${({ theme }) => theme.colors.greanScale.main}; } `; const CancellButton = styled.button` cursor: pointer; width: 300px; height: 60px; border: 1px solid ${({ theme }) => theme.colors.grayScale.Light_Gray}; border-radius: 18px; background-color: ${({ theme }) => theme.colors.grayScale.Light_Gray}; font-size: 18px; font-weight: 400; color: ${({ theme }) => theme.colors.TextColor}; `; const NextButton = styled.button` cursor: pointer; width: 300px; height: 60px; border: 1px solid ${({ theme }) => theme.colors.greanScale.main}; border-radius: 18px; background-color: ${({ theme }) => theme.colors.greanScale.main}; font-size: 18px; font-weight: 400; color: ${({ theme }) => theme.colors.white}; :disabled { color: ${({ theme }) => theme.colors.greanScale.main}; background-color: ${({ theme }) => theme.colors.white}; } `; export default CertifiedModal;
import React from 'react'; import { useRouter } from 'next/router'; import styled from 'styled-components'; import { darken, lighten } from 'polished'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faSearch, faPlus } from '@fortawesome/free-solid-svg-icons'; import JobTicketsCard from 'components/pages/dashboard/JobTickets/JobTicketsCard'; export default function JobTickets() { const router = useRouter(); return ( <div> <TopContainer> <div className="title-container"> <h1>Job Tickets</h1> </div> <div className="button-container"> <div className="button"> <Button variant="white" onClick={() => router.push('/taxidermist/dashboard/jobs-board')} > <FontAwesomeIcon icon={faSearch} style={{ marginRight: '.5rem' }} /> Add From Jobs Board </Button> </div> <div className="button"> <Button onClick={() => alert('Coming soon')}> <FontAwesomeIcon icon={faPlus} style={{ marginRight: '.5rem' }} /> Create New Ticket </Button> </div> </div> </TopContainer> <HeaderContainer> <p> Current Job Tickets: <span className="ticket-number">3</span> </p> <p> Mount Bank Limit: <span className="ticket-number">25</span> </p> </HeaderContainer> <JobCardsContainer> {FAKE_JOBS.map((job, key) => ( <JobTicketsCard job={job} key={key} /> ))} </JobCardsContainer> </div> ); } const TopContainer = styled.div` display: flex; justify-content: space-between; margin-bottom: 2rem; .title-container { h1 { margin: 0.5rem; } } .button-container { display: flex; display: flex; align-items: center; .button { width: 220px; margin-left: 1rem; } } `; const HeaderContainer = styled.div` margin: 0 0 1.5rem 0.5rem; p { margin: 0 0 0.5rem; .ticket-number { color: ${({ theme }) => theme.colors.orange}; font-weight: 600; } } `; const Button = styled.button<{ variant?: 'white' }>` display: block; width: 100%; background: ${({ theme, variant }) => (variant === 'white' ? '#fff' : theme.colors.orange)}; color: ${({ theme, variant }) => (variant === 'white' ? theme.colors.dark : '#fff')}; border: 0.5px solid ${({ theme, variant }) => (variant === 'white' ? lighten(0.3, theme.colors.dark) : '#fff')}; padding: 0.75rem 1rem; border-radius: 6px; font-size: 1rem; cursor: pointer; box-shadow: ${(props) => props.theme.button.boxShadow}; transition: background 300ms ease-in-out, transform 150ms ease-in-out; &:hover { background: ${({ theme, variant }) => variant === 'white' ? darken(0.1, '#fff') : darken(0.05, theme.colors.orange)}; } ${({ theme }) => theme.global.setFocus(theme.colors.orange)} `; const JobCardsContainer = styled.div` display: grid; grid-template-columns: repeat(4, 1fr); gap: 1.5rem 1.5rem; @media (max-width: 1350px) { grid-template-columns: repeat(3, 1fr); } @media (max-width: 1100px) { grid-template-columns: repeat(2, 1fr); } @media (max-width: 800px) { grid-template-columns: repeat(1, 1fr); } `; const FAKE_JOBS = [ { title: 'Ryan Johnson', hunterName: 'Rotated Half Aggressive Moose Blah Blah', avatar: '/images/default-avatar.png', description: 'Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolor, natus molestias! Eius quia culpa tenetur explicabo doloribus hic harum quisquam dolorum, mollitia aut quod architecto sed corrupti?', }, { title: 'Megan Stevens', hunterName: 'Rotated Half Aggressive Goat', avatar: '/images/default-avatar.png', description: 'Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolor, natus molestias! Eius quia culpa tenetur explicabo doloribus hic harum quisquam dolorum, mollitia aut quod architecto sed corrupti? quia culpa tenetur explicabo doloribus hic harum quisquam dolorum, mollitia aut quod architecto sed corrupti.', }, { title: 'Richie Richards', hunterName: 'Rotated Full Stallion', avatar: '/images/default-avatar.png', description: 'Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolor, natus molestias! Eius quia culpa tenetur explicabo doloribus hic harum quisquam dolorum, mollitia aut quod architecto sed corrupti?', }, ];
/* test for gslice cross thread allocation/free * Copyright (C) 2006 Stefan Westerfeld * Copyright (C) 2007 Tim Janik * * This library 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 2 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include <glib.h> #include <stdlib.h> #include <unistd.h> #define N_THREADS 8 #define N_ALLOCS 50000 #define MAX_BLOCK_SIZE 64 struct ThreadData { int thread_id; GThread* gthread; GMutex* to_free_mutex; void* to_free [N_THREADS * N_ALLOCS]; int bytes_to_free [N_THREADS * N_ALLOCS]; int n_to_free; int n_freed; } tdata[N_THREADS]; void* thread_func (void *arg) { struct ThreadData *td = arg; int i; // g_print ("Thread %d starting\n", td->thread_id); for (i = 0; i < N_ALLOCS; i++) { if (rand() % (N_ALLOCS / 20) == 0) g_print ("%c", 'a' - 1 + td->thread_id); /* allocate block of random size and randomly fill */ int bytes = rand() % MAX_BLOCK_SIZE + 1; char *mem = g_slice_alloc (bytes); int f; for (f = 0; f < bytes; f++) mem[f] = rand(); /* associate block with random thread */ int t = rand() % N_THREADS; g_mutex_lock (tdata[t].to_free_mutex); tdata[t].to_free[tdata[t].n_to_free] = mem; tdata[t].bytes_to_free[tdata[t].n_to_free] = bytes; tdata[t].n_to_free++; g_mutex_unlock (tdata[t].to_free_mutex); /* shuffle thread execution order every once in a while */ if (rand() % 97 == 0) { if (rand() % 2) g_thread_yield(); /* concurrent shuffling for single core */ else g_usleep (1000); /* concurrent shuffling for multi core */ } /* free a block associated with this thread */ g_mutex_lock (td->to_free_mutex); if (td->n_to_free > 0) { td->n_to_free--; g_slice_free1 (td->bytes_to_free[td->n_to_free], td->to_free[td->n_to_free]); td->n_freed++; } g_mutex_unlock (td->to_free_mutex); } return NULL; } int main() { int t; g_thread_init (NULL); for (t = 0; t < N_THREADS; t++) { tdata[t].thread_id = t + 1; tdata[t].n_to_free = 0; tdata[t].n_freed = 0; tdata[t].to_free_mutex = g_mutex_new(); } g_print ("Starting %d threads for concurrent GSlice usage...\n", N_THREADS); for (t = 0; t < N_THREADS; t++) { tdata[t].gthread = g_thread_create (thread_func, &tdata[t], TRUE, NULL); g_assert (tdata[t].gthread != NULL); } for (t = 0; t < N_THREADS; t++) { g_thread_join (tdata[t].gthread); } g_print ("\n"); for (t = 0; t < N_THREADS; t++) { g_print ("Thread %d: %d blocks freed, %d blocks not freed\n", tdata[t].thread_id, tdata[t].n_freed, tdata[t].n_to_free); } return 0; }
#ifndef NEIGHBORLIST_H #define NEIGHBORLIST_H #include <vector> #include "atom.h" #include "atomicsystem.h" using namespace std; //! Class to generate and hold neighbor lists /*! This will divide the box into bins and for a given atom, loop over atoms in neighboring bins to generate its neighbor list. This speeds up the process because it is no longer necessary to loop over all atoms in the system. Also, for additional speed up, the neighbor list is kept in a linked list. */ class NeighborList { int natoms; int totalbins; int nxbins; int nybins; int nzbins; double xbinsize, ybinsize, zbinsize; double minxbox, minybox, minzbox; double xboxsize, yboxsize, zboxsize; int maxneighbors; AtomicSystem atomicsystem; double cutoffsq; int **neighboringbins; int *heads; int *binlist; int *atomsperbin; int** neighbors; int* neighborsperatom; bool initialize_binning(); void find_neighbors(int); bool is_bin_valid(double, double, double, int, int, int); void find_neighboring_bins(); public: //! Default Constructor NeighborList(); //! Creates a NeighborList object based on an AtomicSystem /*! \param asystem reference to the atomic system for which the neighbor lists have to be generated. \param cutoff maximum distance for which two atoms are considered neighbors \param nxb number of bins in the x direction \param nyb number of bins in the y direction \param nzb number of bins in the z direction */ NeighborList(AtomicSystem&,double,int,int,int,int); ~NeighborList(); //! Function that actually generates the neighbor list for each atom void build(); //! Returns a pointer to the list of atoms in given bin int* get_atoms_in_bin(int); //! Returns the number of atoms in given bins int get_atoms_per_bin(int); // bool are_bins_neighbors(int,int); //! Retursn the bin number in which the atom with given x, y, and z coordinates belong int get_bin_number(double, double, double); //! Returns the neighboring bins for a bin givne by its index int* get_neighboring_bins(int); //! Returns a pointer to the list of neighbors of an atom given by its index int* get_neighbors(int); //! Returns a pointer to the neighbor list of a given atom sorted by distance int* get_sorted_neighbors(int); //! Returns only atoms of a given type from the neighbor list of a given atom int* get_sorted_neighbors(int,string); //! Returns only atoms of specific types from the neighbor list of a given atom int* get_sorted_neighbors(int,vector<string>); //! Returns the number of neighbors for a given atom int get_n_neighbors(int); //! Returns the number of neighbors of a given type for a given atom int get_n_neighbors(int,string); //! Returns the number of neighbors of given types for a given atom int get_n_neighbors(int,vector<string>); }; #endif
import { Inject } from '@angular/core'; import { LOCAL_STORAGE , WINDOW} from '@ng-toolkit/universal'; import { Component, OnInit, AfterViewInit, AfterContentInit, ChangeDetectorRef, Input, Output, EventEmitter,Optional } from '@angular/core' import { ExploreMenuService } from '../explore-menu.service' import { Router } from '@angular/router' import { CollectionsEditModalComponent } from '../../collections/collections-edit-modal/collections-edit-modal.component' import { NgbModal } from '@ng-bootstrap/ng-bootstrap' import { DataService, AlertService } from '../../../_services' import { CollectionsDeleteComponent } from '../../collections/collections-delete/collections-delete.component' import { ShareModalComponent } from '../../shared/share-modal/share-modal.component' import { Title } from '@angular/platform-browser' import { ProfileService } from '../../profile/profile.service' import { environment } from './../../../../environments/environment' @Component({ selector: 'app-collection-tab', templateUrl: './collection-tab.component.html', styleUrls: ['./collection-tab.component.scss'] }) export class CollectionTabComponent implements OnInit, AfterViewInit { @Input('categoryType') categoryType: any userId: number collectionList: any = [] showCollectionLoader: boolean = false showPaginationLoader: boolean = true perPage: number = 10 currentPage: number = 1 modalReference: any = false authUserDetails: any cardGroup: any = [] randomSelectionCount: number = environment.randomSelectionCount; emptyStatus: boolean = false paginationCheck: boolean = false @Output() loaderClose: EventEmitter<any> = new EventEmitter() constructor(@Inject(WINDOW) private window: Window, @Optional() @Inject(LOCAL_STORAGE) private localStorage: any, private exploreMenuService: ExploreMenuService, private router: Router, private modalService: NgbModal, private _dataService: DataService, private alertService: AlertService, private cdr: ChangeDetectorRef, private titleService: Title, private profileService: ProfileService ) {} ngOnInit() { this.titleService.setTitle('Explore Collections | Shoot The Frame') if (this.localStorage.getItem('currentUser')) { this.authUserDetails = JSON.parse(this.localStorage.getItem('user')) this.userId = this.authUserDetails.id } this._dataService.alert.subscribe((val: any) => { if (val.type == 'success') { this.alertService.success(val.title, val.message) } else if (val.type == 'info') { this.alertService.info(val.title, val.message) } else if (val.type == 'stfawarderror') { this.alertService.warning(val.title, val.message) } else { this.alertService.error(val.title, val.message) } }) this.getCards() this.getCollectionExploreData() } ngAfterViewInit() { //Called after ngOnInit when the component's or directive's content has been initialized. //Add 'implements AfterContentInit' to the class. if (this.localStorage.getItem('deleteMessage')) { let val = JSON.parse(this.localStorage.getItem('deleteMessage')) this.alertService.success(val.title, val.message) this.cdr.detectChanges() this.localStorage.removeItem('deleteMessage') } } paginationItems() { if (this.paginationCheck == false) { this.showPaginationLoader = true this.currentPage++ this.getCollectionExploreData() } } getCollectionExploreData() { let data = { per_page: this.perPage, page: this.currentPage, type: this.categoryType, user_id: this.userId } this.exploreMenuService.getCollectionExploreData(data).subscribe( (response: any) => { //this.collectionList = this.collectionList.concat(response.collections) // this.showCollectionLoader = true this.showPaginationLoader = false let photos = response.collections if (photos.length == 0 && this.currentPage != 1) { this.emptyStatus = true } if (photos.length == 0) { this.paginationCheck = true } for (let i = 0; i < photos.length; ++i) { var remainder = this.collectionList.length % this.randomSelectionCount if (remainder == 0 && this.collectionList.length != 0) { var rand = this.cardGroup[ Math.floor(Math.random() * this.cardGroup.length) ]; if(rand) { let randomFile = { photo: rand, type: 'learn', height: '720', width: '720', page: data.page, card: '1' } this.collectionList.push(randomFile); } } if (photos[i].user_photo == '') { // user-default-header photos[i].user_photo = 'assets/images/temp/user-icon.svg'; } this.collectionList.push(photos[i]) } this.loaderClose.emit() }, error => {} ) } getDetails(id) { this.router.navigate(['/collection', id]) } editCollection(item) { this.modalService.dismissAll() this.modalReference = this.modalService.open( CollectionsEditModalComponent, { windowClass: 'modal-md' } ) this.modalReference.componentInstance.data = item this.modalReference.componentInstance.alert.subscribe(val => { if (val.type == 'success') { this.alertService.success(val.title, val.message) } else if (val.type == 'info') { this.alertService.info(val.title, val.message) } else if (val.type == 'stfawarderror') { this.alertService.warning(val.title, val.message) } else { this.alertService.error(val.title, val.message) } this.currentPage = 1 this.collectionList = [] this.getCollectionExploreData() }) //this.modalReference = this.modalService.open(content) this.modalReference.result.then( result => { ////console.log(result) }, reason => {} ) } deleteCollectionModal(item) { this.modalService.dismissAll() this.modalReference = this.modalService.open(CollectionsDeleteComponent, { windowClass: 'modal-md' }) this.modalReference.componentInstance.data = item this.modalReference.componentInstance.alert.subscribe(val => { if (val.type == 'success') { this.alertService.success(val.title, val.message) } else if (val.type == 'info') { this.alertService.info(val.title, val.message) } else if (val.type == 'stfawarderror') { this.alertService.warning(val.title, val.message) } else { this.alertService.error(val.title, val.message) } this.currentPage = 1 this.collectionList = [] this.getCollectionExploreData() }) this.modalReference.result.then(result => {}, reason => {}) } share(item) { const modalRef = this.modalService.open(ShareModalComponent) modalRef.componentInstance.item = item modalRef.componentInstance.type = 'collection' modalRef.result .then(result => {}) .catch(error => { // ////console.log(error); }) } getCards() { this.profileService.getCardsData().subscribe((response: any) => { //this.userPhotos = [] this.cardGroup = response.cards }) } showProfile(name: any) { this.router.navigate( [ '@' + name]); } }
<template> <div> <h1>Inloggen</h1> <div class="pin-code"> <div class="pin-point" :class="{ active: pin.length > 0 }" /> <div class="pin-point" :class="{ active: pin.length > 1 }" /> <div class="pin-point" :class="{ active: pin.length > 2 }" /> <div class="pin-point" :class="{ active: pin.length > 3 }" /> </div> <div class="pin-wrapper"> <div class="pin-row"> <button class="btn pin-btn" @click="press(1)">1</button> <button class="btn pin-btn" @click="press(2)">2</button> <button class="btn pin-btn" @click="press(3)">3</button> </div> <div class="pin-row"> <button class="btn pin-btn" @click="press(4)">4</button> <button class="btn pin-btn" @click="press(5)">5</button> <button class="btn pin-btn" @click="press(6)">6</button> </div> <div class="pin-row"> <button class="btn pin-btn" @click="press(7)">7</button> <button class="btn pin-btn" @click="press(8)">8</button> <button class="btn pin-btn" @click="press(9)">9</button> </div> <div class="pin-row"> <button class="btn action-btn" @click="press('BACK')"> <i class="fas fa-backspace" /> </button> <button class="btn pin-btn" @click="press(0)">0</button> <button class="btn action-btn" @click="press('GO')"> <i class="fas fa-arrow-right" /> </button> </div> </div> </div> </template> <script> import axios from "axios"; import Swal from "sweetalert2"; export default { name: "LoginPin", data() { return { pin: "", } }, methods: { press(value) { if (value === "BACK") { this.pin = this.pin.slice(0, -1); } else if (value === "GO") { if (this.pin.length === 4) { this.loginWithPin(); this.pin = ""; } } else if (this.pin.length < 4) { this.pin += value; if (this.pin.length === 4) { this.loginWithPin(); this.pin = ""; } } }, async loginWithPin() { try { const response = await axios.post("/api/auth/accessToken", { refreshToken: localStorage.getItem("refreshToken"), pin: this.pin, }); const {id, accessToken, refreshToken} = await response.data; localStorage.setItem("loggedInUserId", id); localStorage.setItem("accessToken", accessToken); localStorage.setItem("refreshToken", refreshToken); if (accessToken) { await Swal.fire({ toast: true, position: 'top', showConfirmButton: false, timer: 1000, timerProgressBar: true, didOpen: (toast) => { toast.addEventListener('mouseenter', Swal.stopTimer) toast.addEventListener('mouseleave', Swal.resumeTimer) }, icon: 'success', title: 'Succesvol ingelod!', text: 'Je wordt doorgestuurd naar de hoofdpagina...' }); this.$router.push("/"); } } catch (err) { await Swal.fire({ toast: true, position: 'top', showConfirmButton: false, timer: 3000, timerProgressBar: true, didOpen: (toast) => { toast.addEventListener('mouseenter', Swal.stopTimer) toast.addEventListener('mouseleave', Swal.resumeTimer) }, icon: 'error', title: 'Inloggen mislukt! Gebruikersnaam of wachtwoord is onjuist.' }); } } } }; </script> <style scoped> .pin-wrapper { display: flex; flex-direction: column; } .pin-row { display: flex; flex-direction: row; justify-content: center; align-items: center; } .btn { width: 5rem; aspect-ratio: 1/1; border-radius: 10%; margin: .5rem; font-size: 1.25rem; font-weight: bold; cursor: pointer; } .pin-btn:hover { background-color: var(--color-primary); color: #fff; } .pin-btn:active { transform: translate(.25rem, .25rem); box-shadow: none; } .pin-btn { border: .1rem solid var(--color-primary); box-shadow: .25rem .25rem 0 var(--color-primary-dark); background-color: #fff; color: #000; } .action-btn { border: none; box-shadow: none; } .action-btn i { color: var(--color-primary-dark); font-size: 2.5rem; } .action-btn:hover i { color: var(--color-primary-light); } .action-btn:active i { transform: translate(0, .25rem); } .pin-code { display: flex; flex-direction: row; justify-content: center; align-items: center; margin: 1rem 0; } .pin-point { width: 1rem; height: 1rem; border-radius: 50%; background-color: #000; margin: 0 .5rem; } .pin-point.active { background-color: var(--color-primary); } </style>
<!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>Marketplace</title> <link rel="stylesheet" href=" https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css"> </head> <body> <nav class="navbar navbar-expand-lg bg-dark" data-bs-theme="dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">Marketplace</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link " aria-current="page" href="{{ url_for('home_page') }}">Home</a> <a class="nav-link" href="{{ url_for('market_page') }}">Market</a> </div> <div class="navbar-nav ms-auto"> <a class="nav-link" href="#">Login</a> <a class="nav-link" href="{{ url_for('register_page') }}">Register</a> </div> </div> </div> </nav> {% with messages = get_flashed_messages(with_categories=True) %} {% if messages %} {% for category,message in messages %} <div class="alert alert-{{category}} alert-dismissible fade show" role="alert"> <button type="button" class="btn-close " data-bs-dismiss="alert" aria-label="Close"></button> {{message}} </div> {% endfor %} {% endif %} {% endwith %} {% block content %} {% endblock %} <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script> </body> </html>
from django.contrib.auth import get_user_model from config.base_api_test import BaseTest from rest_framework import status from django.urls import reverse from ..models import Product, Category, FigureField from ..serializers import CategoryInputSerializer class ModelItemTestCase(BaseTest): def test_list_category(self): """ Test list product """ res = self.client.get(reverse('product:category-list')) category = Category.objects.all().count() self.assertEqual(category, 1) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_create_category(self): """ Test just user can create category objects """ self.client.force_authenticate(user=self.user) response = self.client.post('/category/', data={ 'title': 'mobile2', 'slug': 'mobile2', 'status': True, 'position': 2, }) self.assertEqual(Category.objects.all().count(), 1) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_superuser_create_category(self): """ Test just superuser can create category objects """ self.client.force_authenticate(user=self.user) self.user.is_superuser = True response = self.client.post('/category/', data={ 'title': 'mobile2', 'slug': 'mobile2', 'status': True, 'position': 2, }) self.assertEqual(Category.objects.all().count(), 2) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_update_category(self): """ Test update category by superuser """ self.client.force_authenticate(user=self.user) self.user.is_superuser = True url = reverse('product:category-detail', args=[Category.objects.first().slug]) res = self.client.put(url, { 'title': 'my mobile', 'slug': 'mobile2', 'status': True, 'position': 2, }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(Category.objects.first().title, 'my mobile') def test_delete_category(self): """ Test delete category by superuser """ self.user.is_superuser = True self.client.force_authenticate(user=self.user) url = reverse('product:category-detail', args=[Category.objects.first().slug]) res = self.client.delete(url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(Category.objects.all().count(), 0) def test_list_product(self): """ Test list product """ res = self.client.get(reverse('product:product-list')) product = Product.objects.all().count() self.assertEqual(product, 1) self.assertEqual(res.status_code, status.HTTP_200_OK) def update_product(self): """ Test update product """ self.client.force_authenticate(user=self.user) url = reverse('product:product-detail', args=[Product.objects.first().slug]) res = self.client.put(url, data={ 'title': 'samsung sfsff', 'description': 'android app', 'price': 1.54, 'thumbnail': "/media/images/1_d3HHH29.jpg" }) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_create_products(self): """ Test create product by superuser """ self.client.force_authenticate(user=self.user) self.user.is_superuser = True url = reverse('product:product-list') res = self.client.post(url, data={ 'title': 'samsung jffff7', 'description': 'os:android', 'price': 0.18, 'category': [self.cat.pk], 'thumbnail': 'http://127.0.0.1:8000/media/images/1_d3HHH29.jpg' }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(Product.objects.all().count(), 2) def test_delete_product(self): """ Test for delete product by superuser """ self.client.force_authenticate(user=self.user) self.user.is_superuser = True res = self.client.delete('/product/samsung-j7/') self.assertEqual(res.status_code, status.HTTP_200_OK) def test_figure_list_request(self): """ Test figure list request by user """ response = self.client.get('/figure/') self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_figure_create(self): """ Test can not create figure by user """ self.client.force_authenticate(user=self.user) response = self.client.post(reverse('product:figure-list'), data={ 'type_product': 'android' }) self.assertEqual(FigureField.objects.all().count(), 0) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_superuser_figure_create(self): """ Test can not create figure by superuser """ self.client.force_authenticate(user=self.user) self.user.is_superuser = True response = self.client.post(reverse('product:figure-list'), data={ 'type_product': 'android' }) self.assertEqual(FigureField.objects.all().count(), 1) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_update_figure_superuser(self): """ Test update figure object by superuser """ self.client.force_authenticate(user=self.user) self.user.is_superuser = True FigureField.objects.create(type_product='android') response = self.client.put(reverse('product:figure-detail', args=[FigureField.objects.first().pk]), data={ 'type_product': 'backend' }) self.assertEqual(FigureField.objects.all().count(), 1) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(FigureField.objects.first().type_product, 'backend') def test_delete_figure_superuser(self): """ Test delete figure object by superuser """ self.client.force_authenticate(user=self.user) self.user.is_superuser = True figure = FigureField.objects.create(type_product='android') response = self.client.delete(reverse('product:figure-detail', args=[figure.pk])) self.assertEqual(FigureField.objects.all().count(), 0) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_output_category_list_serilizer(self): """ Test output serializer category """ data = { 'title': 'mobile2', 'slug': 'mobile2', 'status': True, 'position': 2, } serializer = CategoryInputSerializer(data=data) self.assertTrue(serializer.is_valid()) self.assertEqual(serializer.data['title'], data['title'])
package com.daniil.halushka.simplecard import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.daniil.halushka.simplecard.presentation.navigation.NavigationGraph import com.daniil.halushka.simplecard.presentation.navigation.ScreenRoutes import com.daniil.halushka.simplecard.presentation.screen.elements.bottomBar.CustomBottomBar import com.daniil.halushka.simplecard.ui.theme.SimpleCardTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { SimpleCardTheme { SimpleCardApp() } } } } @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun SimpleCardApp() { val navigationController = rememberNavController() val navigationBackStackEntry by navigationController.currentBackStackEntryAsState() val screenRouteNavigation = navigationBackStackEntry?.destination?.route Scaffold( bottomBar = { CustomBottomBar() } ) { NavigationGraph( navController = navigationController, startDestination = ScreenRoutes.HomeScreen.screenType ) } }
const express = require('express'); const app=express(); const port=8080; const path = require('path'); const { v4: uuidv4 } = require('uuid'); const methodOverride = require('method-override'); app.use(methodOverride("_method")); app.use(express.urlencoded({ extended: true })); app.use(express.static(path.join(__dirname, "public"))); app.set("view engine", "ejs"); app.set("views", path.join(__dirname, "views")); let data=[ { id: uuidv4(), username :"abhishek", tweet: "this is my first tweet" }, { id: uuidv4(), username :"abhi", tweet: "this is my second tweet" } ] app.get("/home",(req,res)=>{ res.render("index.ejs",{data}); }) app.get("/home/newtweet",(req,res)=>{ res.render("newtweet.ejs"); }) app.post("/home",(req,res)=>{ let {username,tweet}=req.body; let id=uuidv4(); data.push({id,username,tweet}); console.log(username); res.redirect("/home"); }) app.get("/home/:id",(req,res)=>{ let {id}=req.params; let post = data.find((p)=>id===p.id); res.render("profile.ejs",{post}); }) app.get("/home/:id/update",(req,res)=>{ let {id}=req.params; let post = data.find((p)=>id===p.id); res.render("update.ejs",{post}); }) app.patch("/home/:id",(req,res)=>{ let {id}=req.params; let newtweet=req.body.tweet; let post = data.find((p)=>id===p.id); post.tweet=newtweet; console.log(post); res.redirect("/home"); }) app.delete("/home/:id",(req,res)=>{ let {id}=req.params; data = data.filter((p)=>id!==p.id); res.redirect("/home"); }) app.listen(port,()=>{ console.log("Server Live"); })
<?php namespace App\Entity; use Symfony\Component\Validator\Constraints as Assert; use App\Repository\CommentRepository; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Context\ExecutionContextInterface; #[ORM\Entity(repositoryClass: CommentRepository::class)] class Comment { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\ManyToOne(inversedBy: 'commentaire')] #[ORM\JoinColumn(nullable: false)] private ?User $user = null; #[ Assert\Length(min: 10, minMessage: "Votre nom doit contenir au moins 10 caractères.") ] #[Assert\NotBlank(message: "Ce champ ne peut pas être vide")] #[ORM\Column(length: 255)] private ?string $contenu = null; #[Assert\GreaterThanOrEqual(0)] #[Assert\NotBlank(message: "Ce champ ne peut pas être vide")] #[ORM\Column(type: 'integer')] private ?int $nbLikes = 0; #[ORM\ManyToOne(inversedBy: 'comment')] private ?Post $post = null; public function getId(): ?int { return $this->id; } public function getUser(): ?User { return $this->user; } public function setUser(?User $user): static { $this->user = $user; return $this; } public function getContenu(): ?string { return $this->contenu; } public function setContenu(string $contenu): static { $this->contenu = $contenu; return $this; } public function getnbLikes(): ?int { return $this->nbLikes; } public function setnbLikes(int $nbLikes): static { $this->nbLikes = $nbLikes; return $this; } public function getPost(): ?Post { return $this->post; } public function setPost(?Post $post): static { $this->post = $post; return $this; } }
{% extends "base.html" %} {% block load %}{% load leaflet_tags %}{% endblock %} {% block head %} {% leaflet_js plugins="ALL" %} {% leaflet_css plugins="ALL" %} <!-- <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.css" /> <script src="http://cdn.leafletjs.com/leaflet-0.5/leaflet.js"></script> --> <style> body { padding: 0; margin: 0; } html, body, #map { height: 100%; } .info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .info h4 { margin: 0 0 5px; color: #777; } .menu { width: 400px; } .legend { line-height: 18px; color: #555; } .legend i { width: 18px; height: 18px; float: left; margin-right: 8px; opacity: 0.7; } #logo { position: absolute; bottom: -0.7%; left: 5%; z-index: 1000; } </style> <!-- jQuery UI 10 Basic --> <script src="../static/media/jquery-ui-1.10.3.custom/js/jquery-1.9.1.js" type="application/javascript"></script> <link rel="stylesheet" href="../static/media/jquery-ui-1.10.3.basic/css/redmond/jquery-ui-1.10.3.custom.css"> <script src="../static/media/jquery-ui-1.10.3.basic/js/jquery-ui-1.10.3.custom.js" type="application/javascript"></script> <!-- jQuery UI Pluguins --> <link rel="stylesheet" href="../static/media/jquery-ui-1.10.3.custom/plugins/themes/base/jquery.ui.selectmenu.css"> <script src="../static/media/jquery-ui-1.10.3.custom/plugins/ui/jquery.ui.selectmenu.js" type="application/javascript"></script> <script src="../static/media/jquery-ui-1.10.3.custom/plugins/jQuery.Spin.js" type="application/javascript"></script> {% endblock %} {% block title %}BCN OpenDAI Pilot{% endblock %} {% block body %} <div id="logo"><img src='../static/media/images/open-dai-logo-for-web-bottom.png' style="width:400px"/></div> {% leaflet_map "map" %} <script type="text/javascript"> function mapInit(map, bounds) { /* var minimal_style = 22677, normal_style = 997, midnight_style = 999; var base_key = 'BC9A493B41014CAABB98F0471D759707' kram_key = '32186e05680a4c8dacc22302bc6265c1'; var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/{key}/{styleId}/256/{z}/{x}/{y}.png', cloudmadeAttribution = 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>'; var minimal = L.tileLayer(cloudmadeUrl, {key: kram_key, styleId: minimal_style, attribution: cloudmadeAttribution}), normal = L.tileLayer(cloudmadeUrl, {key: kram_key, styleId: normal_style, attribution: cloudmadeAttribution}), midnight = L.tileLayer(cloudmadeUrl, {key: kram_key, styleId: midnight_style, attribution: cloudmadeAttribution}); */ // MapBox Tile Provider var mapboxeUrl = 'https://a.tiles.mapbox.com/v3/mplanaguma.ifj390dn/{z}/{x}/{y}.png', mpaboxAttribution = 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://www.mapbox.com/about/maps/">MapBox</a>'; var mapboxTiles = L.tileLayer(mapboxeUrl,{attribution:mpaboxAttribution}); // OSM Tile Provider var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', osmAttribution = 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'; var osmTiles = L.tileLayer(osmUrl,{attribution:osmAttribution}); map.setView([41.3850639, 2.1734035], 12); map.addLayer(mapboxTiles); // moving defalt zoom $('.leaflet-control-zoom').hide() var zoomControl = L.control.zoom({position:'bottomleft'}); zoomControl.addTo(map); function getColor(d) { return d >= 2 ? '#800026' : d >= 1 ? '#FC4E2A' : '#FFEDA0' ; } function style(feature) { return { fillColor: getColor(feature.properties.Pollution.alert), weight: 2, opacity: 1, color: 'white', dashArray: '3', fillOpacity: 0.7 }; } // controls var baseMaps = { "OSM": osmTiles, "MapBox": mapboxTiles }; var overlayMaps = { //"Punts": punts }; var controlLayer = L.control.layers(baseMaps, overlayMaps, {position:'bottomright'}); controlLayer.addTo(map); /* // Menu Overlay // ------------ var menu = L.control({position: 'topleft'}); menu.onAdd = function (map) { this._div = L.DomUtil.create('div', 'info menu'); this._div.innerHTML += "<div id='accordion'>" + "<h3>Pollution</h3><div id='menu-pollution'></div>" + "<h3>Traffic</h3><div id='menu-traffic'></div>" //+ "<h3>Alerts</h3><div id='menu-alert'></div>" + "</div>"; this.update(); //div.innerHTML += "<div style='background-color:orange;height:300px;width:100px;'>This div has height and width applied.</div>"; return this._div; }; // HACK to disable the mouse control to the map over the menu //Functions to ei'her disable (onmouseover) or enable (onmouseout) the map's dragging function controlEnter(e) { map.dragging.disable(); map.doubleClickZoom.disable(); } function controlLeave() { map.dragging.enable(); map.doubleClickZoom.enable(); } // Fuction to add content on the menu menu.update = function (props) { var div = $(this._div); var accordion = div.children(); accordion.accordion({heightStyle: "content"}); //Quick application of event handlers to overall control accordion.mouseover(controlEnter); accordion.mouseout(controlLeave); // Menus var menu_pollution = div.find('#menu-pollution'); }; menu.addTo(map); // ------------- */ var neighborhoods = []; var geoJsonLayer; // GeoJson Pollution $.ajax({ type: "GET", url: "pollution_async.geojson", success: function(bcnMap, textStatus, jqXHR){ var features = bcnMap.features; var polygons = []; //L.geoJson(bcnMap, {style: style}).addTo(map); var geoJsonLayer = new L.geoJson(bcnMap, { style: style, onEachFeature: function(feature, layer){ // layer.bindPopup('District: ' + feature.properties.Pollution.district + ' <br> ' + 'so2: ' + feature.properties.Pollution.so2+ ' <br> ' + 'no2: ' + feature.properties.Pollution.no2+ ' <br> ' + 'o3: ' + feature.properties.Pollution.o3+ ' <br> ' + 'co: ' + feature.properties.Pollution.co+ ' <br> ' + 'pm10: ' + feature.properties.Pollution.pm10+ ' \n '); }}); controlLayer.addOverlay(geoJsonLayer, "Pollution"); map.addLayer(geoJsonLayer); //geoJsonLayer.addTo(map); //controlLayer.addTo(map); /* // Pinta poligons a ma for(var i = 0; i < features.length; i++){ var polygonCoordinates = features[i].geometry.coordinates[0]; var polygon = []; for(var j = 0; j < polygonCoordinates.length; j++){ var coordinate = []; coordinate.push(polygonCoordinates[j][1]); coordinate.push(polygonCoordinates[j][0]); polygon.push(coordinate); } polygons.push(polygon); } for(var k = 0; k < polygons.length; k++){ var neighborhood = L.polygon(polygons[k], {weight: 1}).addTo(map); } */ }, error: function(jqXHR, textStatus, error){ console.log(error); } }); var legend = L.control({position: 'topright'}); legend.onAdd = function (map) { var div = L.DomUtil.create('div', 'info legend'), grades = [0, 1, 2], labels = ["Normal", "Poor", "Bad"]; // loop through our density intervals and generate a label with a colored square for each interval for (var i = 0; i < grades.length; i++) { div.innerHTML += '<i style="background:' + getColor(grades[i]) + '"></i> ' + labels[i] + '<br>' ; } return div; }; legend.addTo(map); // GeoJson Traffic function getColorTraffic(d) { return d >= 5 ? '#000000' : d >= 4 ? '#8B0000' : d >= 3 ? '#EE0000' : d >= 2 ? '#EE4000' : d >= 1 ? '#FFD700' : '#99CC32' ; } function styleTraffic(feature) { return { //fillColor: getColorTraffic(feature.properties.status), weight: 2, opacity: 1, color: getColorTraffic(feature.properties.status), //dashArray: '3', fillOpacity: 0.7 }; } $.ajax({ type: "GET", url: "traffic.geojson", success: function(bcnMap, textStatus, jqXHR){ var features = bcnMap.features; var polygons = []; //L.geoJson(bcnMap, {style: style}).addTo(map); var geoJsonLayer = new L.geoJson(bcnMap, { style: styleTraffic, onEachFeature: function(feature, layer){ // layer.bindPopup('Status: ' + feature.properties.status + ' \n ' + 'Forecat: ' + feature.properties.forecast); }}); controlLayer.addOverlay(geoJsonLayer, "Traffic"); map.addLayer(geoJsonLayer); }, error: function(jqXHR, textStatus, error){ console.log(error); } }); } // InitMap </script> {% endblock %}
/* * Pueda usar esta plantilla para la carga del reto a iMaster * Copie las clases de los paquetes Modelo, Vista, Controlador y Util * No incluya los import de los archivos .java solo las clases */ // Importaciones necesarias en iMaster import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.sql.PreparedStatement; // Util (No modificar) class JDBCUtilities { private static final String DATABASE_LOCATION = "ProyectosConstruccion.db"; public static Connection getConnection() throws SQLException { String url = "jdbc:sqlite:"+DATABASE_LOCATION; return DriverManager.getConnection(url); } } // Remplace en adelante por las clases de sus archivos .java // Vista class VistaRequerimientos {} public class VistaRequerimientosReto4 { public static final ControladorRequerimientosReto4 controlador = new ControladorRequerimientosReto4(); //// ****************REQUERIMIENTO 1 LIDERES POR SALARIO ****************** public static void requerimiento1(){ //lider por salario System.out.println("*** Lideres por Salario ***"); try{ ArrayList<LiderPorSalario> RankingLideresPorSalario = controlador.consultarLideresPorSalario(); for(LiderPorSalario liderporsalario : RankingLideresPorSalario){ System.out.printf("El Lider %s %s con Id %d tiene un salario de %d %n", liderporsalario.getNombre(), liderporsalario.getApellido(), liderporsalario.getIdLider(), liderporsalario.getSalario() ); } }catch(SQLException e){ System.err.println("Ha ocurrido un error!"+e.getMessage()); } } public static void requerimiento2(){ // Proyectos por tipo System.out.println("*** Proyectos por Tipo ***"); try{ ArrayList<ProyectosPorTipo> RankingProyectosPorTipo = controlador.consultarProyectosPorTipos(); for(ProyectosPorTipo proyectosportipo : RankingProyectosPorTipo){ System.out.printf("El proyecto con ID %d de la constructora: %s de la ciudad %s, tiene un estrato asignado igual a %d %n", proyectosportipo.getIdProyecto(), proyectosportipo.getConstructora(), proyectosportipo.getciudad(), proyectosportipo.getEstrato() ); } }catch(SQLException e){ System.err.println(e); } } public static void requerimiento3(){ // Lider por nombre System.out.println("*** Lideres por Nombre ***"); try{ ArrayList<LiderPorNombre> RankingLiderPorNombres = controlador.consultarLideresPorNombres(); for(LiderPorNombre liderespornombre : RankingLiderPorNombres){ System.out.printf("El Lider con ID %d se llama: %s %s %n", liderespornombre.getIdLider(), liderespornombre.getNombre(), liderespornombre.getApellido() ); } }catch(SQLException e){ System.err.println(e); } } } // Controlador class ControladorRequerimientos {} public class ControladorRequerimientosReto4 { //Su codigo public ControladorRequerimientosReto4(){ //Su codigo } public ArrayList<LiderPorSalario> consultarLideresPorSalario() throws SQLException { LiderPorSalarioDao respuesta = new LiderPorSalarioDao(); return respuesta.rankingLiderPorSalario(); } public ArrayList<ProyectosPorTipo> consultarProyectosPorTipos() throws SQLException { ProyectoPorTipoDao respuesta = new ProyectoPorTipoDao(); return respuesta.rankingProyectosPorTipo(); } public ArrayList<LiderPorNombre> consultarLideresPorNombres() throws SQLException { LiderPorNombreDao respuesta = new LiderPorNombreDao(); return respuesta.rankingLiderPorNombre(); } } // Modelo // VO class Requerimiento_1 {} public class LiderPorSalario { //Su codigo private String Nombre; private String Apellido; private int IdLider; private int Salario; public LiderPorSalario(){} public LiderPorSalario(String Nombre,String Apellido, int IdLider,int Salario){ this.Nombre = Nombre; this.Apellido = Apellido; this.IdLider = IdLider; this.Salario = Salario; } /// setters public void SetNombre(String Nombre){this.Nombre = Nombre;} public void setApellido(String Apellido){this.Apellido = Apellido;} public void setIdLider(int IdLider){this.IdLider = IdLider;} public void setSalario(int Salario){this.Salario = Salario;} /// Getters public String getNombre(){return this.Nombre;} public String getApellido(){return this.Apellido;} public int getIdLider(){return this.IdLider;} public int getSalario(){return this.Salario;} } //class Requerimiento_2 {} public class ProyectosPorTipo { private int idProyecto; private String constructora; private String ciudad; private int estrato; public ProyectosPorTipo(){} public ProyectosPorTipo(int idProyecto,String constructora,String ciudad,int estrato){ this.idProyecto=idProyecto; this.constructora=constructora; this.ciudad=ciudad; this.estrato=estrato; } /// setters public void SetIdProyecto(int idProyecto){this.idProyecto = idProyecto;} public void SetCostructora(String constructora){this.constructora = constructora;} public void SetCiudad(String ciudad){this.ciudad = ciudad;} public void SetEstrato(int estrato){this.estrato = estrato;} /// Getters public int getIdProyecto(){return this.idProyecto;} public String getConstructora(){return this.constructora;} public String getciudad(){return this.ciudad;} public int getEstrato(){return this.estrato;} } //class Requerimiento_3 {} public class LiderPorNombre { private int idLider; private String Nombre; private String Apellido; public LiderPorNombre(){} public LiderPorNombre(int idLider,String Nombre,String Apellido){ this.idLider=idLider; this.Nombre = Nombre; this.Apellido = Apellido; } public void setIdLider(int idLider){this.idLider=idLider;} public void setNombre(String Nombre){this.Nombre= Nombre;} public void setApellido(String Apellido){this.Apellido= Apellido;} public int getIdLider(){return this.idLider;} public String getNombre(){return this.Nombre;} public String getApellido(){return this.Apellido;} } // DAO //class Requerimiento_1Dao {} public class LiderPorSalarioDao { public ArrayList<LiderPorSalario> rankingLiderPorSalario() throws SQLException { ArrayList<LiderPorSalario> respuesta = new ArrayList<LiderPorSalario>(); Connection conexion = JDBCUtilities.getConnection(); try{ String Consulta = "SELECT Id_Lider, Nombre,Primer_Apellido, salario FROM Lider WHERE salario <= 500000 ORDER BY salario"; PreparedStatement statement = conexion.prepareStatement(Consulta); ResultSet resultSet = statement.executeQuery(); while(resultSet.next()){ LiderPorSalario liderPorSalario= new LiderPorSalario(); liderPorSalario.SetNombre(resultSet.getString("Nombre")); liderPorSalario.setApellido(resultSet.getString("Primer_apellido")); liderPorSalario.setIdLider(resultSet.getInt("Id_Lider")); liderPorSalario.setSalario(resultSet.getInt("Salario")); respuesta.add(liderPorSalario); } resultSet.close(); statement.close(); }catch(SQLException e){ System.err.println("error consultando los lideres por salario:" + e); }finally{ } return respuesta; // Su código } } //class Requerimiento_2Dao {} public ArrayList<ProyectosPorTipo> rankingProyectosPorTipo() throws SQLException { ArrayList<ProyectosPorTipo> respuesta = new ArrayList<ProyectosPorTipo>(); Connection conexion = JDBCUtilities.getConnection(); try{ String Consulta = "select p.ID_Proyecto, p.Constructora, p.Ciudad, t.Estrato as Estrato from Proyecto p join Tipo t on p.ID_Tipo = t.ID_Tipo where p.ciudad='Cartagena' ORDER BY Estrato"; PreparedStatement statement = conexion.prepareStatement(Consulta); ResultSet resultSet = statement.executeQuery(); while(resultSet.next()){ ProyectosPorTipo proyectosPorTipo= new ProyectosPorTipo(); proyectosPorTipo.SetIdProyecto(resultSet.getInt("ID_proyecto")); proyectosPorTipo.SetCostructora(resultSet.getString("Constructora")); proyectosPorTipo.SetCiudad(resultSet.getString("Ciudad")); proyectosPorTipo.SetEstrato(resultSet.getInt("estrato")); respuesta.add(proyectosPorTipo); } resultSet.close(); statement.close(); }catch(SQLException e){ System.err.println("error consultando los lideres por salario:" + e); }finally{ } return respuesta; // Su código } } //class Requerimiento_3Dao {} public class LiderPorNombreDao { public ArrayList<LiderPorNombre> rankingLiderPorNombre() throws SQLException { ArrayList<LiderPorNombre> respuesta = new ArrayList<LiderPorNombre>(); Connection conexion = JDBCUtilities.getConnection(); try{ String Consulta = "select ID_lider,Nombre,Primer_Apellido from Lider l where l.Primer_Apellido like('%z') order by Nombre ASC "; PreparedStatement statement = conexion.prepareStatement(Consulta); ResultSet resultSet = statement.executeQuery(); while(resultSet.next()){ LiderPorNombre liderPorNombre= new LiderPorNombre(); liderPorNombre.setIdLider(resultSet.getInt("ID_Lider")); liderPorNombre.setNombre(resultSet.getString("Nombre")); liderPorNombre.setApellido(resultSet.getString("Primer_Apellido")); respuesta.add(liderPorNombre); } resultSet.close(); statement.close(); }catch(SQLException e){ System.err.println("error consultando los lideres por salario:" + e); }finally{ } return respuesta; // Su código } }
import React from 'react'; import PropTypes from 'prop-types'; import { ListItem, Divider } from '@material-ui/core'; import ListItemText from './styles/UserTransactionsListItem.styled'; const UserTransactionsListItem = ({ transaction }) => ( <> <ListItem> <ListItemText primary={<strong>USER</strong>} secondary={transaction.user} /> <ListItemText right="true" primary={<strong>ETH AMOUNT</strong>} secondary={transaction.ethAmount} /> </ListItem> <Divider component="li" /> </> ); UserTransactionsListItem.propTypes = { transaction: PropTypes.shape({ ethAmount: PropTypes.number, user: PropTypes.string, }).isRequired, }; export default UserTransactionsListItem;
package domain import ( "github.com/stretchr/testify/require" "niseoku-go/pkg/domain" "testing" ) // 商品を作成できる func Test_CreateProduct(t *testing.T) { // Given productId := domain.GenerateProductId() productType := domain.ProductTypeGeneric productName, err := domain.NewProductName("iPhone") require.NoError(t, err) productPrice, err := domain.NewProductPrice(100000) require.NoError(t, err) // When product := domain.NewProduct(productId, productType, productName, productPrice) // Then require.NotNil(t, product) require.Equal(t, product.GetId(), productId) require.Equal(t, product.GetName(), productName) require.Equal(t, product.GetPrice(), productPrice) } // 商品を公開できる func Test_PublishAuction(t *testing.T) { // Given productId := domain.GenerateProductId() productType := domain.ProductTypeGeneric productName, err := domain.NewProductName("iPhone") require.NoError(t, err) productPrice, err := domain.NewProductPrice(100000) require.NoError(t, err) product := domain.NewProduct(productId, productType, productName, productPrice) // When product = product.Publish() // Then require.NotNil(t, product) require.Equal(t, product.GetStatus(), domain.ProductStatusPublic) }
<div class = "bootstrap-wrapper"> <div class = "container"> <div class = "row" style = "margin-top : 20px;"> <div class = "col-md-6 offset-md-3"> <mat-card> <form (ngSubmit) = "onSubmit()" #warehouseForm = "ngForm"> <div [innerHtml]="htmlContentHeader"></div> <mat-form-field class="full-width" appearance="fill" *ngIf="!isNew"> <mat-label>Warehouse</mat-label> <input matInput disabled value="{{warehouse.id}}"> </mat-form-field> <mat-form-field class="full-width" appearance = "outline"> <mat-label>Client </mat-label> <input type="text" [disabled]="isDetail" required [(ngModel)] = "warehouse.client" name = "client" matInput placeholder="Client's name"> <mat-error *ngIf="clientFormControl.hasError('required')"> Client is required </mat-error> </mat-form-field> <mat-form-field class="full-width" appearance="outline"> <mat-label>Type</mat-label> <mat-select [disabled]="isDetail" required [(ngModel)]="warehouse.warehouseFamily" name="type"> <mat-option *ngFor="let type of warehouseFamilies" [value]="type.value"> {{type.viewValue}} </mat-option> </mat-select> </mat-form-field> <mat-form-field appearance = "outline"> <mat-label>Size </mat-label> <input type="number" [disabled]="isDetail" min="0" required [(ngModel)] = "warehouse.size" name = "size" matInput> <mat-hint>Max numbers of racks</mat-hint> <mat-error *ngIf="sizeFormControl.hasError('required')"> Size is required </mat-error> </mat-form-field> <div class = "container text-center" *ngIf="!isDetail"> <button mat-raised-button color="primary" [disabled]= "!warehouseForm.form.valid">Save</button> <button mat-raised-button (click) = "goToLstWarehouses()" style = "margin-left: 20px;">Cancel</button> </div> <div class = "container text-center" *ngIf="isDetail"> <button mat-raised-button (click) = "goToLstWarehouses()" style = "margin-left: 20px;">Back</button> </div> </form> <br> <div *ngIf="isDetail || isUpdate"> <mat-divider></mat-divider> <br> <h1 class="text-center">Racks</h1> <table mat-table [dataSource]="racks"> <!-- id Column --> <ng-container matColumnDef="id"> <th mat-header-cell *matHeaderCellDef> Rack </th> <td mat-cell *matCellDef="let element"> {{element.id}} </td> </ng-container> <!-- Type Column --> <ng-container matColumnDef="type"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Type </th> <td mat-cell *matCellDef="let element"> {{element.rackType}} </td> </ng-container> <!-- Actions Column --> <ng-container matColumnDef="actions"> <th mat-header-cell *matHeaderCellDef> Actions </th> <td mat-cell *matCellDef="let element"> <div class="button-row" *ngIf="!isDetail"> <button (click) = "deleteRack(element.id)" mat-raised-button color="warn" matTooltip="Delete">Delete</button> </div> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> <br> <div class = "container text-center" *ngIf="!isDetail"> <button mat-mini-fab color="primary" (click)="openDialog()" matTooltip="Add rack to warehouse"> <mat-icon>add</mat-icon> </button> </div> </div> </mat-card> </div> </div> </div> </div>
import React from 'react' import { ModuleProvider, ModuleProviderValue } from './provider' import { Context } from './context' import { ModuleContextOptions, ModuleContext } from './module-context' /** * ModuleContext for manager dependencies */ export type ModuleCtor<T = any> = new (...args: any[]) => T export type Injectable<T = any> = ModuleCtor<T> | ModuleProvider<T> export type MutableContainerState<T extends Container> = Omit<T, 'state'> & { state: T['state'] } /** * Container and Module */ export class Container<S = {}> { static createContext<T extends Container>() { return React.createContext<T | null>(null) } static from<T extends ModuleCtor>(Ctor: T) { return class InjectableClass extends Ctor { constructor(...args: any[]) { super(...args) /** * add instance to current-context with Constructor as key */ Context.from(this).addModule(this.constructor as ModuleCtor, this) } /** * get dep by Dep key * @param Dep */ use<T>(Dep: ModuleCtor<T>): T use<T>(Dep: ModuleProvider<T>): T use<T>(Dep: Injectable<T>): T { return Context.from(this).use(Dep as any) } /** * inject provider-value * @param providerValue */ inject<T>(providerValue: ModuleProviderValue<T>): T { return Context.from(this).inject(providerValue) } /** * create a new context for Dep * @param Ctor * @param options options for reusing deps or others */ new<T>(Ctor: ModuleCtor<T>, options?: ModuleContextOptions): T { return Context.from(this).new(Ctor, options) } } } declare state: Readonly<S> private declare _listeners: (() => void)[] constructor() { this._listeners = [] /** * add instance to current-context with Constructor as key */ Context.from(this).addModule(this.constructor as ModuleCtor, this) } /** * mutate module state * @param state module state */ setState<K extends keyof S>(state: ((prevState: Readonly<S>) => Pick<S, K> | S) | (Pick<S, K> | S)) { const self: MutableContainerState<typeof this> = this if (isFunction(state)) { Object.assign(self.state, state(self.state)) } else { Object.assign(self.state, state) } const listeners = this._listeners for (let i = 0; i < listeners.length; i++) { const listener = listeners[i] listener() } } /** * Adds a change listener * @param listener listener A callback to be invoked on every dispatch. * @returns A function to remove this change listener. */ subscribe(listener: () => void) { if (typeof listener !== 'function') { throw new Error(`Expected the listener to be a function. Instead, received: '${typeof listener}'`) } const nextListeners = this._listeners nextListeners.push(listener) return function unsubscribe() { const index = nextListeners.indexOf(listener) nextListeners.splice(index, 1) } } /** * get dep by Dep key * @param Dep */ use<T>(Dep: ModuleCtor<T>): T use<T>(Dep: ModuleProvider<T>): T use<T>(Dep: Injectable<T>): T { return Context.from(this).use(Dep as any) } /** * inject provider-value * @param providerValue */ inject<T>(providerValue: ModuleProviderValue<T>): T { return Context.from(this).inject(providerValue) } /** * create a new context for Dep * @param Ctor * @param options options for reusing deps or others */ new<T>(Ctor: ModuleCtor<T>, options?: ModuleContextOptions): T { return Context.from(this).new(Ctor, options) } } export class Module<S = {}> extends Container<S> {} export const initialize = <T>(Dep: ModuleCtor<T>, options?: ModuleContextOptions, ctx = new ModuleContext()) => { return ctx.new(Dep, options) } function isFunction(fn: any): fn is Function { return typeof fn === 'function' }
package christmas.domain.orderdetails; import christmas.domain.Event; import christmas.domain.Order; import christmas.domain.orderdetails.benefit.DDayBenefit; import christmas.domain.orderdetails.benefit.GiftBenefit; import christmas.domain.orderdetails.benefit.SpecialBenefit; import christmas.domain.orderdetails.benefit.WeekDayBenefit; import christmas.domain.orderdetails.benefit.WeekEndBenefit; import christmas.utility.EventConstant; import christmas.utility.OrderConstant; import java.util.ArrayList; import java.util.List; public class Benefit { private final List<String> appliedBenefits = new ArrayList<>(); private final DDayBenefit dDayBenefit = new DDayBenefit(); private final WeekDayBenefit weekDayBenefit = new WeekDayBenefit(); private final WeekEndBenefit weekEndBenefit = new WeekEndBenefit(); private final SpecialBenefit specialBenefit = new SpecialBenefit(); private final GiftBenefit giftBenefit = new GiftBenefit(); public void applyBenefit(List<Order> orders, int totalPrice, Event event) { if (totalPrice >= EventConstant.DISCOUNT_EVENT_MINIMUM_TOTAL_PRICE) { applyDDayBenefit(event); applyWeekDayBenefit(orders, event); applyWeekEndBenefit(orders, event); applySpecialBenefit(event); applyGiftBenefit(totalPrice, event); } } public int totalDiscountAmount() { return dDayBenefit.getDiscountAmount() + weekDayBenefit.getDiscountAmount() + weekEndBenefit.getDiscountAmount() + specialBenefit.getDiscountAmount() + giftBenefit.getDiscountAmount(); } private void applyDDayBenefit(Event event) { if (event.isDDayEvent()) { dDayBenefit.applyDDayBenefit(event.getReservationDate()); this.appliedBenefits.add(dDayBenefit.toString()); } } private void applyWeekDayBenefit(List<Order> orders, Event event) { if (event.isWeekDayEvent()) { weekDayBenefit.applyWeekDayBenefit(orders); if (weekDayBenefit.getDiscountAmount() > 0) { this.appliedBenefits.add(weekDayBenefit.toString()); } } } private void applyWeekEndBenefit(List<Order> orders, Event event) { if (event.isWeekEndEvent()) { weekEndBenefit.applyWeekEndBenefit(orders); if (weekEndBenefit.getDiscountAmount() > 0) { this.appliedBenefits.add(weekEndBenefit.toString()); } } } private void applySpecialBenefit(Event event) { if (event.isSpecialEvent()) { specialBenefit.applySpecialBenefit(); if (specialBenefit.getDiscountAmount() > 0) { this.appliedBenefits.add(specialBenefit.toString()); } } } private void applyGiftBenefit(int totalPrice, Event event) { if (event.isGiftEvent(totalPrice)) { giftBenefit.applyGiftBenefit(); if (giftBenefit.getDiscountAmount() > 0) { this.appliedBenefits.add(giftBenefit.toString()); } } } @Override public String toString() { if (appliedBenefits.isEmpty()) { return OrderConstant.NONE; } StringBuilder stringBuilder = new StringBuilder(); for (String benefit : appliedBenefits) { stringBuilder.append(benefit); } return stringBuilder.toString(); } }
import { BsChevronDown, BsChevronRight } from "react-icons/bs"; import useComponentVisible from "../../hooks/useComponentVisible"; import { useState } from "react"; type SearcDropdownProps = { handleSearchCategoryChange: (category: string) => void; } const SearchDropdown: React.FC<SearcDropdownProps> = ({handleSearchCategoryChange}) => { const [dropdownCategory, setDropdownCategory] = useState("All"); const dropdownVisible = useComponentVisible(false); const handleDropdown = () => { (dropdownVisible.isComponentVisible) ? dropdownVisible.setComponentVisible(false) : dropdownVisible.setComponentVisible(true); } const dropdownVisibilityState = (dropdownVisible.isComponentVisible) ? "visible" : "hidden"; return ( <div ref={dropdownVisible.ref} className="relative flex justify-center items-center select-none"> <div onClick={handleDropdown} className={`${dropdownVisible.isComponentVisible ? "bg-gray-200 dark:bg-gray-900 outline outline-1 outline-gray-400" : ""} gap-2 px-3 py-1 flex items-center hover:outline hover:outline-1 hover:outline-gray-400 rounded-lg dark:text-white cursor-pointer`}> <h1>{dropdownCategory}</h1> {(dropdownVisible.isComponentVisible) ? <BsChevronRight /> : <BsChevronDown />} </div> {/* Dropdown Menu */} <div className={`${dropdownVisibilityState} absolute top-[112%] w-full z-50 rounded-lg border border-gray-400 dark:border-gray-600`}> <div className="flex flex-col gap-1 bg-gray-200 dark:bg-gray-900 rounded-lg text-black dark:text-white"> <div onClick={() => {handleSearchCategoryChange("All"); setDropdownCategory("All");}} className={`${dropdownCategory === "All" ? "hidden" : "visible"} cursor-pointer px-2 py-[2px] text-sm hover:bg-gray-300 dark:hover:bg-gray-600 rounded-md transition-colors duration-100 ease-in`}> All </div> <div onClick={() => {handleSearchCategoryChange("Content"); setDropdownCategory("Content");}} className={`${dropdownCategory === "Content" ? "hidden" : "visible"} cursor-pointer px-2 py-[2px] text-sm hover:bg-gray-300 dark:hover:bg-gray-600 rounded-md transition-colors duration-100 ease-in`}> Content </div> <div onClick={() => {handleSearchCategoryChange("Day"); setDropdownCategory("Day");}} className={`${dropdownCategory === "Day" ? "hidden" : "visible"} cursor-pointer px-2 py-[2px] text-sm hover:bg-gray-300 dark:hover:bg-gray-600 rounded-md transition-colors duration-100 ease-in`}> Day </div> <div onClick={() => {handleSearchCategoryChange("Month"); setDropdownCategory("Month");}} className={`${dropdownCategory === "Month" ? "hidden" : "visible"} cursor-pointer px-2 py-[2px] text-sm hover:bg-gray-300 dark:hover:bg-gray-600 rounded-md transition-colors duration-100 ease-in`}> Month </div> <div onClick={() => {handleSearchCategoryChange("Date"); setDropdownCategory("Date");}} className={`${dropdownCategory === "Date" ? "hidden" : "visible"} cursor-pointer px-2 py-[2px] text-sm hover:bg-gray-300 dark:hover:bg-gray-600 rounded-md transition-colors duration-100 ease-in`}> Date </div> <div onClick={() => {handleSearchCategoryChange("Year"); setDropdownCategory("Year");}} className={`${dropdownCategory === "Year" ? "hidden" : "visible"} cursor-pointer px-2 py-[2px] text-sm hover:bg-gray-300 dark:hover:bg-gray-600 rounded-md transition-colors duration-100 ease-in`}> Year </div> <div onClick={() => {handleSearchCategoryChange("Score"); setDropdownCategory("Score");}} className={`${dropdownCategory === "Score" ? "hidden" : "visible"} cursor-pointer px-2 py-[2px] text-sm hover:bg-gray-300 dark:hover:bg-gray-600 rounded-md transition-colors duration-100 ease-in`}> Score </div> <div onClick={() => {handleSearchCategoryChange("Location"); setDropdownCategory("Location");}} className={`${dropdownCategory === "Location" ? "hidden" : "visible"} cursor-pointer px-2 py-[2px] text-sm hover:bg-gray-300 dark:hover:bg-gray-600 rounded-md transition-colors duration-100 ease-in`}> Location </div> </div> </div> </div> ); } export default SearchDropdown; {/* <li><strong>Content</strong> - ex: "content:happy"</li> <li><strong>Day</strong> - ex: "day:monday"</li> <li><strong>Month</strong> - ex: "month:march"</li> <li><strong>Date</strong> - ex: "date:15"</li> <li><strong>Year</strong> - ex: "year:2020"</li> <li><strong>Emoji Score</strong> - ex: "score:-2"</li> */}
<!doctype html> <html lang="pt-br"> <head> <title>Bootstrap - Margin e Wrap</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <style type="text/css"> .caixa { background: #f5f5f5; height: 200px; } .item { border: 1px solid black; padding: 5px; } </style> </head> <body> <div class="container"> <h2>Margin right/left auto (mr-auto, ml-auto)</h2> <div class="caixa d-flex "> <div class="item ml-auto mr-auto">Flex item 1</div> <div class="item ml-auto mr-auto">Flex item 2</div> <div class="item ml-auto mr-auto">Flex item 3</div> </div> <br><br> <h2>Margin bottom/top auto (mt-auto, mb-auto)</h2> <div class="caixa d-flex flex-column"> <div class="item mb-auto mt-auto">Flex item 1</div> <div class="item">Flex item 2</div> <div class="item">Flex item 3</div> </div> <br><br> <h2>Wrap (flex-wrap, flex-nowrap)</h2> <div class="caixa d-flex flex-nowrap"> <div class="item">Flex item 1</div> <div class="item">Flex item 2</div> <div class="item">Flex item 3</div> <div class="item">Flex item 4</div> <div class="item">Flex item 5</div> <div class="item">Flex item 6</div> <div class="item">Flex item 7</div> <div class="item">Flex item 8</div> <div class="item">Flex item 9</div> <div class="item">Flex item 10</div> <div class="item">Flex item 11</div> <div class="item">Flex item 12</div> <div class="item">Flex item 13</div> <div class="item">Flex item 14</div> <div class="item">Flex item 15</div> </div> <br><br> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script> </body> </html>
import { AuthenticationService } from './../../index/service/authentication.service'; import { SharedService } from '../../shared/service/shared.service'; import { PlaceStatus } from '../../shared/common'; import { Router } from '@angular/router'; import { Observable } from 'rxjs'; import { Component, OnInit } from '@angular/core'; import { UserService } from '../service/user.service'; import { ManagePostForm } from 'src/app/shared/model/place.model'; @Component({ selector: 'app-seller-manage', templateUrl: './seller-manage.component.html', }) export class SellerManageComponent implements OnInit { placeID: number; userID: number; posts: Observable<ManagePostForm>; statusSelects = [ { id: -1, name: 'Tất cả' }, // Cancel, Active, Pending, Checking { id: PlaceStatus.ACTIVE, name: 'Đã duyệt' }, { id: PlaceStatus.PENDING, name: 'Đang chờ duyệt' }, { id: PlaceStatus.CHECKING, name: 'Đang kiểm tra' }, { id: PlaceStatus.CANCEL, name: 'Đã hủy' } ]; statusSelected: any; constructor( private userService: UserService, private router: Router, public sharedService: SharedService, public loginService: AuthenticationService) { this.statusSelected = this.statusSelects[0].id; } ngOnInit() { this.userID = this.loginService.currentUserValue.userID; this.userService.getAllPost(this.userID).subscribe( data => this.posts = data ); } isStatusShow(id) { if (this.statusSelected === -1) { // Cancel, Active, Pending, Checking return id === PlaceStatus.ACTIVE || id === PlaceStatus.PENDING || id === PlaceStatus.CHECKING || id === PlaceStatus.CANCEL; } else { return id === this.statusSelected; } } isViewShow(id) { return id === PlaceStatus.ACTIVE; } isCancelShow(id) { return id !== PlaceStatus.CANCEL; } isEditShow(id) { return id === PlaceStatus.PENDING; } edit() { this.router.navigate(['user/seller/post-edit', { id: this.placeID }], { skipLocationChange: true }); } cancel() { this.userService.updateStatusPlace(this.placeID, PlaceStatus.CANCEL).subscribe( data => { if (data) { this.userService.getAllPost(this.userID).subscribe( res => this.posts = res); } } ); } }
defmodule Rabble.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application @impl true def start(_type, _args) do children = [ # Start the Ecto repository Rabble.Repo, # Start the Telemetry supervisor RabbleWeb.Telemetry, # Start the PubSub system {Phoenix.PubSub, name: Rabble.PubSub}, # Start the Endpoint (http/https) RabbleWeb.Endpoint, # Online Presence RabbleWeb.Presence, # Clean pow store {Pow.Postgres.Store.AutoDeleteExpired, [interval: :timer.hours(24)]} # Start a worker by calling: Rabble.Worker.start_link(arg) # {Rabble.Worker, arg} ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Rabble.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. @impl true def config_change(changed, _new, removed) do RabbleWeb.Endpoint.config_change(changed, removed) :ok end end
--- layout: about title: home permalink: / subtitle: <i>An NGF-funded project with a 2.1 million Euro budget applying technical methods to the law with the aim of making the EU's ambitious AI regulation – particularly the GDPR and AI Act – work in practice.</i> profile: align: right image: logo.png image_circular: false # crops the image to make it circular # more_info: > # <p>Prompt: Visualize a logo that portrays a pathway, symbolizing the journey from AI innovation to regulatory compliance. This path should start from a stylized AI icon, winding its way through a series of legal symbols (like a document with a seal, a gavel) and leading to a harmonious coexistence symbol represented by a perfectly balanced scale embedded within a digital landscape. Use a color scheme that conveys clarity and optimism, such as light blues and greens.</p> news: true # includes a list of news items latest_posts: false # includes a list of the newest posts selected_papers: false # includes a list of papers marked as "selected={true}" social: true # includes social icons at the bottom of the page profiles: # if you want to include more than one profile, just replicate the following block # and create one content file for each profile inside _pages/ - align: center image: konrad.jpg image_circular: true # crops the image to make it circular more_info: > Konrad Kollnig<br> Project Lead, Assistant Professor - align: center image: gijs.jpg image_circular: true # crops the image to make it circular more_info: > Gijs van Dijck<br> Professor of Private Law - align: center image: qian.jpg image_circular: true # crops the image to make it circular more_info: > Qian Li<br> Postdoctoral Researcher - align: center image: kamil.jpg image_circular: true # crops the image to make it circular more_info: > Kamil Szostak<br> PhD Student - align: center image: you.png image_circular: true # crops the image to make it circular more_info: > You?<br> PhD Student - align: center image: you.png image_circular: true # crops the image to make it circular more_info: > You?<br> PhD Student - align: center image: you.png image_circular: true # crops the image to make it circular more_info: > You?<br> PhD Student - align: center image: you.png image_circular: true # crops the image to make it circular more_info: > You?<br> PhD Student --- **You can follow the project updates by subscribing to our Substack: <https://regtech4ai.substack.com/>** The General Data Protection Regulation (GDPR) is a conerstone of the regulation of AI in the EU. It seeks to facilitate the flow of data across the EU while protecting citizens’ fundamental rights – including data protection and privacy. Even though the GDPR is now more than 7 years old, there remain significant gaps between the law and practice. For example, past research by the project lead showed that less than 10% of mobile apps fulfil the minimum legal requirements regarding *consent* – one of the core principles of GDPR. As the EU is introducing the *AI Act* (i.e. its first law aimed directly at AI), it is likely that again – like with GDPR – enforcement will be lagging and that businesses will be overwhelmed by the legal obligations. In response, **RegTech4AI** will research *regulatory technologies* (RegTech) to assist enforcement agencies and businesses with AI regulation, and thereby bolster trust in AI systems among citizens. The aim of this project is *not* to develop new AI frameworks or laws (as this has been studied much before). Instead, **we focus on the challenge of** **implementation****: making AI-relevant laws like GDPR and the AI Act work in practice**. This topic has received very limited attention as it requires a deep understanding of both CS and law – which is rare. To be prepared to respond to new AI challenges in the years ahead, we will also actively build bridges across CS and law, including by organising a set of workshops and conferences on the topic. **RegTech4AI** will be carried out as part of the <a href="https://www.maastrichtuniversity.nl/about-um/faculties/law/research/law-and-tech-lab" target="_blank">Law&Tech Lab</a> at Maastricht University, located in the Netherlands and close to Brussels. Over the last 5 years, the Lab grew continuously and now hosts 16 faculty members, with experts in AI law, NLP, and legal data science. ## team The project team consists of a range of experienced researchers in the domain of applying technical methods to the law (particular in machine learning and data science), one postdoc with interdisciplinary research expertise, and up to five PhD students. {% if page.profiles %} <div class="container"> <div class="row"> {% for profile in page.profiles %} <div class="col-md-3 mb-4"> {% if profile.image %} <div class="profile-image text-center"> {% assign profile_image_path = profile.image | prepend: 'assets/img/' %} {% if profile.image_circular %} {% assign profile_image_class = 'img-fluid z-depth-1 rounded-circle' %} {% else %} {% assign profile_image_class = 'img-fluid z-depth-1 rounded' %} {% endif %} <img src="{{ profile_image_path }}" class="{{ profile_image_class }}" alt="Profile image"> </div> {% endif %} {% if profile.more_info %} <div class="profile-subtitle text-center mt-2">{{ profile.more_info }}</div> {% endif %} </div> {% endfor %} </div> </div> {% endif %} <!-- News --> {% if page.news and site.announcements.enabled %} <h2> <a href="{{ '/news/' | relative_url }}" style="color: inherit">news</a> </h2> {% include news.liquid limit=true %} {% endif %}
var Modal = require('../../../src/symphony/extensions/modal'); var ModalView = require('../../../src/symphony/views/modal'); var sandbox = require('../../mocks/sandboxMock'); var core = { sandbox: sandbox, start: $.noop }; describe("The modal core extension", function() { beforeEach(function() { m = new Modal(core, sandbox); }); it("should throw an error if instantiated without a core instance", function() { expect(function() { new Modal(); }).toThrow(); }); describe("when instantiated", function() { var m; it("should subscribe to modal:show", function() { expect(sandbox.subscribe).toHaveBeenCalledWith('modal:show', jasmine.any(Function)); }); it("should subscribe to modal:hide", function() { expect(sandbox.subscribe).toHaveBeenCalledWith('modal:hide', jasmine.any(Function)); }); }); describe("the show function", function() { beforeEach(function() { spyOn(core, 'start'); spyOn(ModalView.createView.prototype, 'render').and.returnValue({ el: {} }); spyOn(ModalView.createView.prototype, 'postRender'); }); it("should render the passed-in modal view", function() { m.show({ contentView: {} }); expect(ModalView.createView.prototype.render).toHaveBeenCalled(); expect(ModalView.createView.prototype.postRender).toHaveBeenCalled(); }); it("should start the passed-in module string", function() { m.show({ contentView: 'test' }); expect(core.start).toHaveBeenCalledWith('test', jasmine.any(Object)); }); }); describe("the close function", function() { var spy; beforeEach(function() { spy = jasmine.createSpyObj('modalView', ['removeContent', 'destroy']); m.modalView = spy; m.close(); }); it("should remove the modal view's content", function() { expect(spy.removeContent).toHaveBeenCalled(); }); it("should destroy the modal view", function() { expect(spy.destroy).toHaveBeenCalled(); }); it("should null modalView", function() { expect(m.modalView).toBeNull(); }); }); });
# Summary {.unnumbered} ## Some words before going **"Have you used Cryptography?"** I have asked this question to several of my friends and some of them would say, no. But look around, the website you love has a way to secretly communicate with you everyday, through some web protocols with cryptography. You may reveal everything to the hacker with only one tap of your credit card when you do some shopping without the magic of Cryptography. Some latest trend, Blockchain: Cryptocurrency, NFTs, Distributed stuffs, etc.; have its cores are cryptographic protocols to preserve the integrity. Even somethings does not seems to need Cryptography, like AI, recently have some usage of it to preserve the privacy in training dataset. Therefore, I would really appreciate that you choose me and my document as a first playground for your crypto knowledge!!! ## Brief summary A brief summary of the books: + **"Symmetric Cryptography"**: As its name, we will have a walkthrough some fields of Symmetric Cryptography from the very historical (and completely) broken to the newest that are used in your daily Internet surfing. + **"Asymmetric Cryptography"**: This part will look into the constructions of many famous cryptography scheme that is also the deliverer for your symmetric cryptography and validation. !!! Warning: Many Maths! + **"Hash functions"**: Integrity will mostly mention in this field, and some examples of how to playing with some hacks to break the integrity! + **"Appendices"**: Some other tools/guides for you to playing with the material of the book and also further games. ## Philosophy The aim of this book is **guilding** you to start with crypto, rather than a cheatsheet for you to copy the snipset into any cryptography challenges in CTFs. Therefore, the basics of SageMath/Python will be mentioned in the book, but not the all attacks' implementations. I know that there are many available samples on GitHub; however, gaining experiences by playing around with debugging, 'math'-ing, and programming is better, rights? However, do not afraid about the hard problems. At any point of this book, you will find some exercises (that I find it should work for gaining your skills) to practice with. Also, do not afraid to contact me via social medias! ::: {.callout-tip} Let's write something (as clear as you can) about what you want to learn or love about Cryptography and what do you expect this book has. 100% I can give you all the stuff you need, but I am sure you will find them out if you **REALLY** want to finish (and extend) your checklist! ::: That's enough for the text! Let's gooooo!!!!.
import numpy as np import torch from torch.utils.data import Dataset from skimage.io import imread import random import torchvision import os import pickle import pandas as pd import cv2 from scipy.ndimage import gaussian_filter # This class processes multiple IMC file types and returns pre-processed tiles of the image for a given path class ImageDataset(Dataset): def __init__(self, imgs_path, n_tiles, delta, tilesize, resize_=None, strength='Weak', swav_=False, norm=True, n_neighbors=1, uniform_tiling=False): self.imgs_path = imgs_path # path for files directory. Must contain ONLY image files if self.imgs_path[-3:] == 'npz': # for handling numpy (lung) self.np_images, self.img_ids = self.process_np(self.imgs_path) # process numpy else: self.img_ids = [a for a in os.listdir(imgs_path)] if self.imgs_path[-14:] == 'DLBCL_hyperion': # For handling DLBCL images with open('/content/drive/MyDrive/DLBCL_Associated_data/keep_markers.pkl', 'rb') as f: self.keep_markers = pickle.load(f) self.n_tiles = n_tiles # number of tiles per image self.delta = delta # neighbor sample distance factor self.tilesize = tilesize # h x w self.strength = strength # augmentation strength self.swav_ = swav_ # if swav model self.norm = norm # if normalizing according to Pixie paper self.n_neighbors = n_neighbors # num neighbors (for latent smoothing) self.resize_ = resize_ # to resize tiles (pretrained resnet) self.uniform_tiling = uniform_tiling # for testing. Evenly spaced tiles from image # this function handles lung Numpy file format def process_np(self, path_): data = np.load(path_, allow_pickle=True) # load pickled file np_images = data['X'] # data is dictionary-like object. X is images img_ids = [a for a in range(len(np_images))] # IDs are numerical, not names for i in range(len(np_images)): # iterate thru images t = np_images[i] / np.max(np_images[i], axis=(1, 2)).reshape(len(np_images[i]), 1, 1) # channel norm np_images[i] = t return np_images, img_ids # This function handles text csv format for DLBCL dataset def process_txt(self, path_, keep_): df = pd.read_csv(os.path.join(path_), sep='\t', usecols=['X', 'Y'] + keep_) # read file, keep relevant channels df = df.apply(pd.to_numeric, errors='coerce') # convert from str to float arr2d = pd.pivot_table(df, index='X', columns='Y', values=keep_).reindex(keep_, axis=1, level=0).values # convert from 2d to 3d by pixel value arr3d = np.reshape(arr2d, (arr2d.shape[0], arr2d.shape[1] // len(keep_), len(keep_)), order='F').transpose(2, 0, 1) # reshape into proper 3d shape if np.isnan(arr3d).any(): arr3d[np.isnan(arr3d)] = 0 return arr3d def __len__(self): return len(self.img_ids) # This function tiles the image evenly for testing def tile_image_uniform(self, np_img, otsu, tilesize, rm_blank=False, thresh=.05): if len(np_img.shape) == 3: # if [C, W, H] np_img = np.expand_dims(np_img, 0) # [1, C, W, H] num_rows = np_img.shape[3] // tilesize # num evenly spaced rows num_cols = np_img.shape[2] // tilesize # num evenly spaced columns y_remainder = (np_img.shape[3] % tilesize) // 2 # space left on each side x_remainder = (np_img.shape[2] % tilesize) // 2 tmplst = [] corners = [] nulls = [] i = 0 # Iterate thru rows and columns, filling with tiles for row in range(num_rows): for col in range(num_cols): tile = np_img[:, :, x_remainder + col * tilesize:x_remainder + (col + 1) * tilesize, y_remainder + row * tilesize:y_remainder + (row + 1) * tilesize] if otsu is not None: # Otsu determines if tile is empty or has cells otsu_tile = otsu[x_remainder + col * tilesize:x_remainder + (col + 1) * tilesize, y_remainder + row * tilesize:y_remainder + (row + 1) * tilesize] if rm_blank: # removes empty tiles, improves clustering downstream if otsu_tile.mean() < thresh: # empty tiles tile[:, :, :, :] = 0 nulls.append([1]) # labels this tile to be removed downstream else: nulls.append([0]) # labels this tile to not be removed from analysis tmplst.append(tile) corners.append([[col * tilesize + x_remainder, row * tilesize + y_remainder]]) else: tmplst.append(tile) corners.append([[col * tilesize + x_remainder, row * tilesize + y_remainder]]) nulls.append([0]) return torch.tensor(np.concatenate(tmplst)), np.concatenate(corners), np.concatenate(nulls) # This function rnadomly selects n tiles and corresponding neighbors from image def tile_image(self, np_img, tilesize, n, delta, n_neighbors=1, otsu_=None): if len(np_img.shape) == 3: np_img = np.expand_dims(np_img, 0) if otsu_ is not None: # *currently only optimized for liver dataset. need to make channel a variable dna1 = cv2.normalize(np_img[0, 39, :, :], None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F).astype(np.uint8) dna2 = cv2.normalize(np_img[0, 40, :, :], None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F).astype(np.uint8) otsu = (cv2.threshold(dna1, 0, 1, cv2.THRESH_OTSU)[1] + cv2.threshold(dna2, 0, 1, cv2.THRESH_OTSU)[1]) / 2 cornerlst = [] neighbors_lst = [] counter = 0 anchors_ = np.empty([n, np_img.shape[1], tilesize, tilesize]) neighbors_ = np.empty([n, np_img.shape[1], tilesize, tilesize]) # Iterate thru num neighbors, only counting tiles that are non-empty while counter < n: xl = random.sample(range(0, (np_img.shape[2] - tilesize - 1)), 1)[0] yl = random.sample(range(0, (np_img.shape[3] - tilesize - 1)), 1)[0] anchor = np_img[:, :, xl:xl + tilesize, yl:yl + tilesize] if otsu_ is not None: otsu_tile = otsu[xl:xl + tilesize, yl:yl + tilesize] if otsu_tile.mean() > 0.05: anchors_[counter] = anchor cornerlst.append([[xl, yl]]) counter += 1 else: pass else: anchors_[counter] = anchor # append anchor cornerlst.append([[xl, yl]]) # top left corner for future analysis counter += 1 # Iterate thru number of neighbors per tile for i in range(n_neighbors): neighbors_tmp = np.empty([n, np_img.shape[1], tilesize, tilesize]) for e, corner in enumerate(cornerlst): otsu_count = 0 while otsu_count == 0: # keeps track of empty tiles xl, yl = corner[0] # top left corner for anchor xdelta = int(np.rint(random.gauss(0, delta))) + xl # neighbor corner ydelta = int(np.rint(random.gauss(0, delta))) + yl # neighbor corner if xdelta < 0: # make sure there is no 'overhang' xdelta = 0 # push to edege elif xdelta + tilesize > np_img.shape[2]: # make sure there is no 'overhang' xdelta = np_img.shape[2] - tilesize - 1 if ydelta < 0: # make sure there is no 'overhang' ydelta = 0 elif ydelta + tilesize > np_img.shape[3]: # make sure there is no 'overhang' ydelta = np_img.shape[3] - tilesize - 1 neighbor = np_img[:, :, xdelta:xdelta + tilesize, ydelta:ydelta + tilesize] if otsu_: otsu_neighbor = otsu[xdelta:xdelta + tilesize, ydelta:ydelta + tilesize] if otsu_neighbor.mean() > .05: # only take non empty otsu otsu_count += 1 else: otsu_count += 1 neighbors_tmp[e] = neighbor neighbors_lst.append(neighbors_tmp) corners = np.concatenate(cornerlst) return anchors_, neighbors_lst, corners # This function gets number of markers, which changes between datasets def get_num_markers(self, dataset): a, _, _ = dataset[0] return a.shape[1] # This function normalizes image, with or without pixel-norm def normalize_image(self, x, norm_scale=True): # first clip each channel independently for c in range(len(x)): x[c] = np.clip(np.array(x[c]), None, np.quantile(x[c], .99)) x = gaussian_filter(x, (0, 1.5, 1.5)) # gaussian filter all images if norm_scale: # pixel norm nan = np.where(x == 0, np.nan, x) # create mask that doesn't acount for 0 values if bool(np.isnan(nan).all()): # for slice that is all 0 pass else: quant = np.nanquantile(nan, .999, axis=(1, 2)) # along channel axis x = torch.from_numpy(x / quant.reshape(-1, 1, 1)) # divide out by 99.9% non-zero value for channel totals = torch.sum(x, dim=0).unsqueeze(0) + 1e-5 # reshape scale factor totals = torch.repeat_interleave(totals, x.shape[0], dim=0) # sum of relative per channel intensity x = x / totals # create pixel-level scaling return x / x.max() # 0-1 norm def __getitem__(self, idx): #handles numpy images if self.imgs_path[-3:] == 'npz': x = self.np_images[idx] x = np.clip(np.array(x), None, np.quantile(x, .99)) else: img_id = self.img_ids[idx] if img_id[-3:] == 'iff': x = imread(os.path.join(self.imgs_path, img_id)) # tiff files if np.isnan(x).any(): x[np.isnan(x)] = 0 elif img_id[-3:] == 'txt': # specifically for DLBCL x = self.process_txt(os.path.join(self.imgs_path, img_id), self.keep_markers) x = self.normalize_image(x, self.norm) # all images processed if self.uniform_tiling: # for testing output, corners, nulls = self.tile_image_uniform(x, None, self.tilesize, rm_blank=False, thresh=0) return output, corners, img_id.strip('.tiff'), nulls # evenly spaced tiles and location else: # for training anchors, neighbors, corners = self.tile_image(x, self.tilesize, self.n_tiles, self.delta, self.n_neighbors) anchors, neighbors = torch.tensor(np.array(anchors)).float(), torch.tensor(np.array(neighbors)).float() if self.resize_ != None: #resize function (resnet) resize = torchvision.transforms.Resize((self.resize_, self.resize_), antialias=True) neighbors = resize( neighbors.reshape(self.n_neighbors * self.n_tiles, anchors.shape[1], anchors.shape[2], anchors.shape[3])) anchors = resize(anchors) return anchors, neighbors.reshape(self.n_neighbors, self.n_tiles, anchors.shape[1], anchors.shape[2], anchors.shape[3]), corners
"use client"; import React from "react"; import Link from "next/link"; import Image from "next/image"; import { TypeAnimation } from "react-type-animation"; import { motion } from "framer-motion"; const SectionOne: React.FC = () => { return ( <section className="lg: py-16"> <div className="grid grid-cols-1 sm:grid-cols-12"> <motion.div initial={{ opacity: 0, scale: 0.5 }} animate={{ opacity: 1, scale: 1 }} transition={{ duration: 0.5 }} className="col-span-8 place-self-center text-center sm:text-left justify-self-start" > <h1 className="text-white mb-4 text-4xl sm:text-5xl lg:text-7xl lg:leading-normal font-extrabold"> <span className="text-transparent bg-clip-text bg-text-gradient"> Hello, I&apos;m{" "} </span> <br></br> <TypeAnimation sequence={[ "Ramiro Avila", 1000, "Frontend Developer", 1000, "Web Developer", 1000, "Computer vision enthusiast", 1000, ]} wrapper="span" speed={50} repeat={Infinity} /> </h1> <p className="text-[#ADB7BE] text-base sm:text-lg mb-6 lg:text-xl"> Systems Engineering student passionate about Computer Vision, Deep Learning and creating web applications. </p> <div> <Link href="/" className="px-1 inline-block py-1 w-full sm:w-fit rounded-full bg-gradient-to-br from-primary-500 to-secondary-500 bg-yellow-800 text-white mx-3" > <span className="block bg-[#121212] hover:text-red-300 rounded-full px-5 py-2"> Hire Me </span> </Link> <Link href="/" className="px-1 inline-block py-1 w-full sm:w-fit rounded-full bg-gradient-to-br from-primary-500 to-secondary-500 bg-yellow-800 text-white mt-3 mx-3" > <span className="block bg-[#121212] hover:text-red-300 rounded-full px-5 py-2"> Download CV </span> </Link> </div> </motion.div> <motion.div initial={{ opacity: 0, scale: 0.5 }} animate={{ opacity: 1, scale: 1 }} transition={{ duration: 0.5 }} className="col-span-4 place-self-center" > <div className="mt-4 rounded-full bg-[#181818] w-[350px] h-[400px] relative "> <Image src="/person.webp" alt="person image" className="absolute transform -translate-x-1/2 -translate-y-1/2 top-1/2 left-1/2" width={300} height={300} priority={true} /> </div> </motion.div> </div> </section> ); }; export default SectionOne;
import { Spinner } from '@chakra-ui/spinner'; import { SendHorizonal } from 'lucide-react'; import toast from 'react-hot-toast'; import { useState } from 'react'; import { tokenDecoder } from '../../../utils/tokenDecoder'; import axios from '../../../services/axios'; import { AnswersProtocol } from '../../../interfaces/answers-protocol'; export type UpdateAnswerProps = { answer: AnswersProtocol; index: number; comment_id: number; activeIndexUpdating: number | null; setActiveIndexUpdating: React.Dispatch<React.SetStateAction<number | null>>; }; export default function UpdateAnswer({ answer, index, comment_id, activeIndexUpdating, setActiveIndexUpdating, }: UpdateAnswerProps) { const [content, setContent] = useState(''); const [isLoading, setIsLoading] = useState(false); const token = localStorage.getItem('token'); const user_id = tokenDecoder(token)?.id; const updateAnswer = async (id: number) => { setIsLoading(true); if (!content || content.length === 0) { setIsLoading(false); return toast.error('Você não pode enviar um comentario vazio.'); } await axios .put(`answer/update/${id}`, { content, user_id, comment_id }) .then((response) => { console.log(response); setIsLoading(false); setActiveIndexUpdating(null); toast.success('Comentário atualizado.'); }) .catch((error) => { console.log(error); setIsLoading(false); toast.error('Erro ao tentar atualizar comentário.'); }); }; return ( <> <div className="flex flex-col justify-center gap-5"> {activeIndexUpdating === index ? ( <div className="flex gap-8 mt-8 mb-8 items-center"> <input onChange={(e) => setContent(e.target.value)} placeholder="Digite algo..." className="rounded-md pl-10 p-2 w-10/12 outline-none flex items-center gap-20 border border-black" /> <button onClick={() => updateAnswer(answer.id)} className="flex items-center justify-center bg-blue-400 text-white p-3 rounded-full hover:opacity-85" > {isLoading ? ( <Spinner boxSize="25px" color="white" /> ) : ( <SendHorizonal /> )} </button> </div> ) : ( <div className="mt-6 mb-6">{answer.content}</div> )} </div> </> ); }
package entity import ( "github.com/TEDxITS/website-backend-2024/constants" "github.com/google/uuid" "gorm.io/gorm" ) type ( PE2RSVP struct { ID uuid.UUID `json:"id" form:"id" gorm:"type:uuid;primary_key;default:uuid_generate_v4()"` Name string `json:"name" form:"name"` Email string `json:"email" form:"email"` Institute string `json:"institute" form:"institute"` Department string `json:"department" form:"department"` StudentID string `json:"student_id" form:"student_id"` Batch string `json:"batch" form:"batch"` WillingToCome *bool `json:"willing_to_come" form:"willing_to_come"` WillingToBeContacted *bool `json:"willing_to_be_contacted" form:"willing_to_be_contacted"` Essay string `json:"essay" form:"essay" gorm:"comment:How do you see Indonesia in the next 10 years due to the influence of its politics?"` } ) func (e *PE2RSVP) AfterCreate(tx *gorm.DB) error { if !*e.WillingToCome { return nil } var event Event if err := tx.Model(&Event{}).Where(Event{ Name: constants.PE2Name, }).Take(&event).Error; err != nil { return err } event.Registers += 1 if err := tx.Model(&Event{}).Where(Event{ Name: constants.PE2Name, }).Updates(event).Error; err != nil { return err } return nil }
import React, { useState } from "react"; import { Link } from "react-router-dom"; import { useCartContext } from "../../context/cartContext"; import { higherThanStock } from "../../helpers"; import "./ItemCount.css"; function ItemCount({ id, stock, initial, nombre, img, precio }) { const { agregarItem } = useCartContext(); const [qty, setQty] = useState(initial); const addOne = () => { if (!higherThanStock(qty, stock)) setQty(qty + 1); }; const removeOne = () => { if (higherThanStock(qty, 1)) setQty(qty - 1); }; const onAdd = (qty) => { agregarItem({ item: nombre, cantidad: qty, img: img, price: precio, stock: stock, id: id, }); apagarBoton(); }; const [botonActivo, setBotonActivo] = useState(false); function apagarBoton() { setBotonActivo(true); } return ( <div> {!botonActivo ? ( <div> <div id="ItemCount"> <button className="btn btn-danger btn-remove" onClick={() => removeOne()} > - </button> <p className="text-dark">{qty}</p> <button className="btn btn-primary btn-add text-center" onClick={() => { addOne(); }} > + </button> </div> <div> <button disabled={qty===0} className="btn btn-primary btnAddCart" onClick={() => onAdd(qty)} > Añadir al carrito </button> </div> </div> ) : ( <div className="text-center"> <Link to="/" className="btn btn-primary m-3"> Seguir comprando </Link> <Link to="/cart" className="btn btn-success m-3"> Terminar mi Compra </Link> </div> )} </div> ); } export default ItemCount;
import { Paysheet, type PaysheetType } from '@/data/paySchema' import { useAddPay } from '@/hooks/usePay' import { ArrowForwardIcon } from '@chakra-ui/icons' import { Box, Button, Flex, FormControl, FormErrorMessage, FormHelperText, FormLabel, Icon, Input, Spacer, useColorModeValue, useConst, } from '@chakra-ui/react' // import { DevTool } from '@hookform/devtools' import { zodResolver } from '@hookform/resolvers/zod' import { format } from 'date-fns' import { motion as m } from 'framer-motion' import { useEffect } from 'react' import { useForm, type SubmitHandler } from 'react-hook-form' import { GiCancel } from 'react-icons/gi' import { TiLightbulb } from 'react-icons/ti' import { Form, useLocation } from 'react-router-dom' const DailyForm: () => JSX.Element = () => { const location = useLocation() const day = location?.state as PaysheetType const bg = useColorModeValue('white', ' gray.800') // const placeholderColor = useColorModeValue('gray.400', 'gray.500') const date = useConst(new Date().toISOString().slice(0, 10)) const { addPay, payError } = useAddPay() const { register, handleSubmit, watch, formState: { errors, isSubmitting }, reset, getValues, setValue, } = useForm<PaysheetType>({ resolver: zodResolver(Paysheet), }) const onSubmit: SubmitHandler<PaysheetType> = (data) => { try { addPay({ ...data }).catch((error) => { console.error(error) console.error(payError) }) reset() } catch (error: unknown) { if (error instanceof Error) { console.error(error.message) console.error(error) console.error(payError) } } } const totalMilesFunc: () => void = () => { const startingMiles = Number(getValues('startingMiles')) const endingMiles = Number(getValues('endingMiles')) const totalMiles = endingMiles - startingMiles > 0 ? endingMiles - startingMiles : 0 setValue('totalMiles', totalMiles) } useEffect(() => { totalMilesFunc() }, [watch('startingMiles'), watch('endingMiles')]) const canSubmit = Object.keys(errors).length === 0 && !isSubmitting return ( <m.div initial={{ opacity: 0, y: 80, scale: 0.8 }} animate={{ opacity: 1, y: 0, scale: [0.9, 1.2, 1] }} transition={{ type: 'spring', stiffness: 90, damping: 15, }} exit={{ opacity: 0 }} > <Box border="2px" borderColor="cyan.600" boxShadow="dark-lg" p="4" rounded="md" mt={10} mb={10} w="60vw" maxW="500px" minW="350px" bg={bg} > <Box p="4"> <Form onSubmit={handleSubmit(onSubmit)}> <FormControl isInvalid={errors.date != null} isRequired variant="floating" > <Input {...register('date')} id="date" type="date" placeholder="date" mb="3" mt="3" defaultValue={ day?.date > 0 ? format(day?.date, 'yyyy-MM-dd') : date } /> <FormLabel htmlFor="date">Date</FormLabel> <FormErrorMessage>{errors.date?.message}</FormErrorMessage> </FormControl> <Box my="3"> <FormControl isInvalid={errors.startingMiles != null} isRequired variant="floating" > <Input {...register('startingMiles')} id="startingMiles" type="number" placeholder="Starting Miles" mb="3" defaultValue={ day?.startingMiles >= 0 ? day?.startingMiles : undefined } /> <FormLabel htmlFor="startingMiles">Starting Miles:</FormLabel> <FormErrorMessage> {errors.startingMiles?.message} </FormErrorMessage> </FormControl> </Box> <Box my="3"> <FormControl isInvalid={errors.endingMiles != null} isRequired variant="floating" > <Input {...register('endingMiles')} id="endingMiles" type="number" placeholder="Ending Miles" mb="3" defaultValue={ day?.endingMiles >= 0 ? Number(day?.endingMiles) : undefined } /> <FormLabel htmlFor="endingMiles">Ending Miles:</FormLabel> <FormErrorMessage> {errors.endingMiles?.message} </FormErrorMessage> </FormControl> </Box> <Box my="3"> <FormControl isInvalid={errors.totalMiles != null} isRequired variant="floating" > <Input {...register('totalMiles', { valueAsNumber: true, required: false, })} id="totalMiles" type="number" placeholder="Total Miles" disabled // mb="3" defaultValue={ day?.totalMiles >= 0 ? Number(day?.totalMiles) : undefined } /> <FormLabel htmlFor="totalMiles">Total Miles:</FormLabel> <FormErrorMessage> {errors.totalMiles?.message} </FormErrorMessage> <FormHelperText ml="10"> <Icon as={TiLightbulb} w={3} h={3} /> Total miles are automatically calculated </FormHelperText> </FormControl> </Box> <Box my="3"> <FormControl isInvalid={errors.payMiles != null} isRequired variant="floating" > <Input {...register('payMiles')} id="payMiles" type="number" placeholder="Pay Miles" mb="3" defaultValue={ day?.payMiles >= 0 ? Number(day?.payMiles) : undefined } /> <FormLabel htmlFor="payMiles">Pay Miles:</FormLabel> <FormErrorMessage>{errors.payMiles?.message}</FormErrorMessage> </FormControl> </Box> <Box my="3"> <FormControl isInvalid={errors.backhaul != null} variant="floating" > <Input {...register('backhaul')} id="backhaul" placeholder="BackHaul" mb="3" type={'number'} step=".01" defaultValue={ day?.backhaul >= 0 ? Number(day?.backhaul) : undefined } /> <FormLabel htmlFor="backhaul" optionalIndicator> Backhaul: </FormLabel> <FormErrorMessage>{errors.backhaul?.message}</FormErrorMessage> </FormControl> </Box> <Box my="3"> <FormControl isInvalid={errors.delayHours != null} variant="floating" > <Input {...register('delayHours')} id="delayHours" placeholder="Delay Hours" // mb="3" type={'number'} step=".01" defaultValue={ day?.delayHours >= 0 ? Number(day?.delayHours) : undefined } /> <FormLabel htmlFor="delayHours" optionalIndicator> Delay Hours: </FormLabel> <FormErrorMessage> {errors.delayHours?.message} </FormErrorMessage> <FormHelperText ml="10"> <Icon as={TiLightbulb} w={3} h={3} /> Delay is decimal 45min = .75 </FormHelperText> </FormControl> </Box> <Flex> <Button mt={4} px={5} colorScheme="cyan" isLoading={isSubmitting} type="submit" disabled={!canSubmit} loadingText={ day?.totalMiles !== null ? 'Updating' : 'Submitting' } variant="outline" _hover={{ bg: 'cyan.600', color: 'white', scale: 1.1, }} rightIcon={<ArrowForwardIcon />} > Submit </Button> <Spacer /> <Button mt={4} colorScheme="red" onClick={() => { reset() }} disabled={isSubmitting} variant="outline" _hover={{ bg: 'red.400', color: 'white', scale: 1.1, }} rightIcon={<GiCancel />} > Reset </Button> </Flex> </Form> </Box> {/* {import.meta.env.DEV && <DevTool control={control} />} */} </Box> </m.div> ) } export default DailyForm // export interface PaysheetInputs { // date: string // startingMiles: string // endingMiles: string // totalMiles: number // payMiles: string // backhaul: string // delayHours: string // }
import config from './config'; import apiRouter from './api'; import express from 'express'; import sassMiddleware from 'node-sass-middleware'; import path from 'path'; const server = express(); server.use(sassMiddleware({ src: path.join(__dirname, 'sass'), dest: path.join(__dirname, 'public'), outputStyle: 'compressed', debug: true })); server.set('view engine', 'ejs'); import serverRender from './serverRender'; server.get('/', (req, res) => { serverRender() .then(({ initialData, initialMarkup }) => { res.render('index', { content: initialMarkup, initialData }); }) .catch(console.error); }); server.use('/api', apiRouter); server.use(express.static('public')); server.listen(config.port, config.host, () => { console.info('Express listening on port ', config.port); });
<!-- * @Description: * @Author: lys1626/刘芹芹 * @Date: 2019-12-06 15:01:28 * @LastEditors : lys1626/刘芹芹 * @LastEditTime : 2019-12-25 16:10:40 --> <template> <div class="hard-ware-con" style="width:100%"> <div class="circle-container"> <i-circle :size="size" :percent="percent*100" trail-color="#023d7f" :trail-width="8.5" :stroke-color="color" :stroke-width="8.5"> <span class="demo-Circle-inner">{{showPercent}} <span class="demo-Circle-inner-icon">%</span> </span> </i-circle> </div> <!-- 硬件信息 --> <div class="hard-ware-info"> <div style="display: table-cell;vertical-align: middle;"> <span class="info-name" :style="{color: textColor}">{{hardName}}</span> <span class="clip-text" :style="hardSty" :title="settitle(alreadyHave,allHave,unit)"> <span class="already-have" :style="{color: textColor}">{{alreadyHave}}</span> <span class="all-have">/{{allHave}}</span> <span class="unit">{{unit}}</span> </span> </div> </div> </div> </template> <script> import colorChange from '@/assets/js/color-change.js'; export default { name: 'CircleProcess', mixins: [colorChange], props: { // 进度圆百分比 percent: { type: Number, default: 50 }, // 圆的大小 size: { type: Number, default: 105 }, // 进度颜色 color: { type: [String, Array], default: '#3be5fe' }, // 信息名 hardName: { type: [String], default: 'CPU' }, // 已经使用 alreadyHave: { type: [Number], default: 0 }, // 总量 allHave: { type: [Number], default: 0 }, // 单位 unit: { type: String, default: '核' }, // 文本颜色 textColor: { type: String, default: '#05c9fb' } }, data() { return { textSty: { fontWeight: '700', fontSize: '2.5em' } }; }, computed: { /** * @function: showPercent * @description: 进度条百分比 * @param {type} * @returns: {String} percent */ showPercent() { return (this.percent * 100).toFixed(0); }, /** * @function: hardSty * @description: 信息区域大小 * @param {type} * @returns: {Object} */ hardSty() { return { width: `170px` }; }, /** * @function: settitle * @description: 设置提示信息 * @param {String} val1 已用 * @param {String} val2 全部量 * @param {String} val3 % * @returns: {void} */ settitle(val1, val2, val3) { return (val1, val2, val3) => { return val1 + '/' + val2 + val3; }; } } }; </script> <style lang="less" scoped> @font-face { font-family: 'DS-Digital'; /*字体名称*/ src: /* IE6-IE8 */ url('../assets/font/DS-Digital.ttf') format('truetype'); /* chrome, firefox, opera, Safari, Android, iOS 4.2+*/ } @font-face { font-family: 'Fette-Engschrift'; /*字体名称*/ src: /* IE6-IE8 */ url('../assets/font/Fette-Engschrift.ttf') format('truetype'); /* chrome, firefox, opera, Safari, Android, iOS 4.2+*/ } .demo-Circle-inner { color: #fff; font-size: 3rem; font-family: Fette-Engschrift; } .demo-Circle-inner-icon { font-size: 1.875rem; } .hard-ware-con { width: 200px; position: relative; .circle-container { position: relative; display: inline-block; } .hard-ware-info { height: 100%; position: absolute; top: 0; // right: 0; left: 100px; display: table; color: #fff; font-size: 1em; padding-left: 25px; .info-name { font-family: 'MicrosoftYaHei'; font-size: 1.25rem; display: block; padding-bottom: 13px; } .clip-text { display: inline-block; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; } .already-have { font-family: Fette-Engschrift; font-size: 2.5rem; } .all-have { font-family: Fette-Engschrift; font-size: 2.5rem; color: #fff; } .unit { font-family: 'MicrosoftYaHei'; font-size: 1.125rem; color: #efeeee; } } } </style>
<?php use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); })->name('home'); Auth::routes(); // Route::get('/home', 'Admin\HomeController@index')->name('home'); Route::middleware('auth') ->namespace('Admin') ->name('admin.') ->prefix('admin') ->group(function () { Route::get('/', 'PageController@dashboard')->name('dashboard'); Route::resource('posts', 'PostController'); Route::get('/categories/slug', 'CategoryController@slug')->name('categories.slug'); Route::resource('categories', 'CategoryController'); Route::resource('tags', 'TagController'); });
/* ! tailwindcss v3.3.1 | MIT License | https://tailwindcss.com *//* 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) 2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116) */ *, ::before, ::after { box-sizing: border-box; /* 1 */ border-width: 0; /* 2 */ border-style: solid; /* 2 */ border-color: #e5e7eb; /* 2 */ } ::before, ::after { --tw-content: ''; } /* 1. Use a consistent sensible line-height in all browsers. 2. Prevent adjustments of font size after orientation changes in iOS. 3. Use a more readable tab size. 4. Use the user's configured `sans` font-family by default. 5. Use the user's configured `sans` font-feature-settings by default. 6. Use the user's configured `sans` font-variation-settings by default. */ html { line-height: 1.5; /* 1 */ -webkit-text-size-adjust: 100%; /* 2 */ -moz-tab-size: 4; /* 3 */ -o-tab-size: 4; tab-size: 4; /* 3 */ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; /* 4 */ font-feature-settings: normal; /* 5 */ font-variation-settings: normal; /* 6 */ } /* 1. Remove the margin in all browsers. 2. Inherit line-height from `html` so users can set them as a class directly on the `html` element. */ body { margin: 0; /* 1 */ line-height: inherit; /* 2 */ } /* 1. Add the correct height in Firefox. 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) 3. Ensure horizontal rules are visible by default. */ hr { height: 0; /* 1 */ color: inherit; /* 2 */ border-top-width: 1px; /* 3 */ } /* Add the correct text decoration in Chrome, Edge, and Safari. */ abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } /* Remove the default font size and weight for headings. */ h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } /* Reset links to optimize for opt-in styling instead of opt-out. */ a { color: inherit; text-decoration: inherit; } /* Add the correct font weight in Edge and Safari. */ b, strong { font-weight: bolder; } /* 1. Use the user's configured `mono` font family by default. 2. Correct the odd `em` font sizing in all browsers. */ code, kbd, samp, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; /* 1 */ font-size: 1em; /* 2 */ } /* Add the correct font size in all browsers. */ small { font-size: 80%; } /* Prevent `sub` and `sup` elements from affecting the line height in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } /* 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) 3. Remove gaps between table borders by default. */ table { text-indent: 0; /* 1 */ border-color: inherit; /* 2 */ border-collapse: collapse; /* 3 */ } /* 1. Change the font styles in all browsers. 2. Remove the margin in Firefox and Safari. 3. Remove default padding in all browsers. */ button, input, optgroup, select, textarea { font-family: inherit; /* 1 */ font-size: 100%; /* 1 */ font-weight: inherit; /* 1 */ line-height: inherit; /* 1 */ color: inherit; /* 1 */ margin: 0; /* 2 */ padding: 0; /* 3 */ } /* Remove the inheritance of text transform in Edge and Firefox. */ button, select { text-transform: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Remove default button styles. */ button, [type='button'], [type='reset'], [type='submit'] { -webkit-appearance: button; /* 1 */ background-color: transparent; /* 2 */ background-image: none; /* 2 */ } /* Use the modern Firefox focus style for all focusable elements. */ :-moz-focusring { outline: auto; } /* Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) */ :-moz-ui-invalid { box-shadow: none; } /* Add the correct vertical alignment in Chrome and Firefox. */ progress { vertical-align: baseline; } /* Correct the cursor style of increment and decrement buttons in Safari. */ ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } /* 1. Correct the odd appearance in Chrome and Safari. 2. Correct the outline style in Safari. */ [type='search'] { -webkit-appearance: textfield; /* 1 */ outline-offset: -2px; /* 2 */ } /* Remove the inner padding in Chrome and Safari on macOS. */ ::-webkit-search-decoration { -webkit-appearance: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Change font properties to `inherit` in Safari. */ ::-webkit-file-upload-button { -webkit-appearance: button; /* 1 */ font: inherit; /* 2 */ } /* Add the correct display in Chrome and Safari. */ summary { display: list-item; } /* Removes the default spacing and border for appropriate elements. */ blockquote, dl, dd, h1, h2, h3, h4, h5, h6, hr, figure, p, pre { margin: 0; } fieldset { margin: 0; padding: 0; } legend { padding: 0; } ol, ul, menu { list-style: none; margin: 0; padding: 0; } /* Prevent resizing textareas horizontally by default. */ textarea { resize: vertical; } /* 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) 2. Set the default placeholder color to the user's configured gray 400 color. */ input::-moz-placeholder, textarea::-moz-placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } input::placeholder, textarea::placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } /* Set the default cursor for buttons. */ button, [role="button"] { cursor: pointer; } /* Make sure disabled buttons don't get the pointer cursor. */ :disabled { cursor: default; } /* 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) This can trigger a poorly considered lint error in some tools but is included by design. */ img, svg, video, canvas, audio, iframe, embed, object { display: block; /* 1 */ vertical-align: middle; /* 2 */ } /* Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) */ img, video { max-width: 100%; height: auto; } /* Make elements with the HTML hidden attribute stay hidden by default */ [hidden] { display: none; } *, ::before, ::after { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } ::backdrop { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border-width: 0; } .visible { visibility: visible; } .invisible { visibility: hidden; } .fixed { position: fixed; } .relative { position: relative; } .left-0 { left: 0px; } .right-0 { right: 0px; } .top-0 { top: 0px; } .z-40 { z-index: 40; } .z-50 { z-index: 50; } .mx-auto { margin-left: auto; margin-right: auto; } .my-4 { margin-top: 1rem; margin-bottom: 1rem; } .mb-2 { margin-bottom: 0.5rem; } .mb-4 { margin-bottom: 1rem; } .mb-6 { margin-bottom: 1.5rem; } .mb-8 { margin-bottom: 2rem; } .ml-2 { margin-left: 0.5rem; } .ml-3 { margin-left: 0.75rem; } .ml-auto { margin-left: auto; } .mr-1 { margin-right: 0.25rem; } .mr-2 { margin-right: 0.5rem; } .mr-3 { margin-right: 0.75rem; } .mr-4 { margin-right: 1rem; } .mr-6 { margin-right: 1.5rem; } .mt-14 { margin-top: 3.5rem; } .mt-6 { margin-top: 1.5rem; } .block { display: block; } .inline { display: inline; } .flex { display: flex; } .inline-flex { display: inline-flex; } .table { display: table; } .grid { display: grid; } .hidden { display: none; } .h-10 { height: 2.5rem; } .h-12 { height: 3rem; } .h-4 { height: 1rem; } .h-5 { height: 1.25rem; } .h-6 { height: 1.5rem; } .h-8 { height: 2rem; } .h-\[calc\(100\%-1rem\)\] { height: calc(100% - 1rem); } .h-auto { height: auto; } .h-full { height: 100%; } .h-screen { height: 100vh; } .max-h-full { max-height: 100%; } .w-10 { width: 2.5rem; } .w-12 { width: 3rem; } .w-4 { width: 1rem; } .w-5 { width: 1.25rem; } .w-6 { width: 1.5rem; } .w-60 { width: 15rem; } .w-8 { width: 2rem; } .w-full { width: 100%; } .max-w-2xl { max-width: 42rem; } .max-w-full { max-width: 100%; } .max-w-md { max-width: 28rem; } .max-w-sm { max-width: 24rem; } .flex-shrink-0 { flex-shrink: 0; } .-translate-x-full { --tw-translate-x: -100%; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .rotate-180 { --tw-rotate: 180deg; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .transform { transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .cursor-pointer { cursor: pointer; } .list-none { list-style-type: none; } .appearance-none { -webkit-appearance: none; -moz-appearance: none; appearance: none; } .grid-cols-1 { grid-template-columns: repeat(1, minmax(0, 1fr)); } .grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } .flex-row { flex-direction: row; } .flex-col { flex-direction: column; } .items-start { align-items: flex-start; } .items-center { align-items: center; } .justify-start { justify-content: flex-start; } .justify-end { justify-content: flex-end; } .justify-center { justify-content: center; } .justify-between { justify-content: space-between; } .gap-4 { gap: 1rem; } .gap-x-2 { -moz-column-gap: 0.5rem; column-gap: 0.5rem; } .gap-y-2 { row-gap: 0.5rem; } .gap-y-3 { row-gap: 0.75rem; } .gap-y-5 { row-gap: 1.25rem; } .space-y-4 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(1rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(1rem * var(--tw-space-y-reverse)); } .space-y-6 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(1.5rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(1.5rem * var(--tw-space-y-reverse)); } .divide-y > :not([hidden]) ~ :not([hidden]) { --tw-divide-y-reverse: 0; border-top-width: calc(1px * calc(1 - var(--tw-divide-y-reverse))); border-bottom-width: calc(1px * var(--tw-divide-y-reverse)); } .divide-gray-100 > :not([hidden]) ~ :not([hidden]) { --tw-divide-opacity: 1; border-color: rgb(243 244 246 / var(--tw-divide-opacity)); } .overflow-x-auto { overflow-x: auto; } .overflow-y-auto { overflow-y: auto; } .overflow-x-hidden { overflow-x: hidden; } .whitespace-nowrap { white-space: nowrap; } .rounded { border-radius: 0.25rem; } .rounded-full { border-radius: 9999px; } .rounded-lg { border-radius: 0.5rem; } .rounded-md { border-radius: 0.375rem; } .rounded-t { border-top-left-radius: 0.25rem; border-top-right-radius: 0.25rem; } .border { border-width: 1px; } .border-b { border-bottom-width: 1px; } .border-gray-200 { --tw-border-opacity: 1; border-color: rgb(229 231 235 / var(--tw-border-opacity)); } .border-gray-300 { --tw-border-opacity: 1; border-color: rgb(209 213 219 / var(--tw-border-opacity)); } .border-gray-500 { --tw-border-opacity: 1; border-color: rgb(107 114 128 / var(--tw-border-opacity)); } .bg-blue-600 { --tw-bg-opacity: 1; background-color: rgb(37 99 235 / var(--tw-bg-opacity)); } .bg-gray-50 { --tw-bg-opacity: 1; background-color: rgb(249 250 251 / var(--tw-bg-opacity)); } .bg-gray-800 { --tw-bg-opacity: 1; background-color: rgb(31 41 55 / var(--tw-bg-opacity)); } .bg-green-500 { --tw-bg-opacity: 1; background-color: rgb(34 197 94 / var(--tw-bg-opacity)); } .bg-green-600 { --tw-bg-opacity: 1; background-color: rgb(22 163 74 / var(--tw-bg-opacity)); } .bg-red-600 { --tw-bg-opacity: 1; background-color: rgb(220 38 38 / var(--tw-bg-opacity)); } .bg-red-700 { --tw-bg-opacity: 1; background-color: rgb(185 28 28 / var(--tw-bg-opacity)); } .bg-secondary { --tw-bg-opacity: 1; background-color: rgb(210 91 4 / var(--tw-bg-opacity)); } .bg-transparent { background-color: transparent; } .bg-white { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)); } .bg-yellow-300 { --tw-bg-opacity: 1; background-color: rgb(253 224 71 / var(--tw-bg-opacity)); } .p-1 { padding: 0.25rem; } .p-1\.5 { padding: 0.375rem; } .p-2 { padding: 0.5rem; } .p-2\.5 { padding: 0.625rem; } .p-3 { padding: 0.75rem; } .p-4 { padding: 1rem; } .p-5 { padding: 1.25rem; } .p-6 { padding: 1.5rem; } .p-\[7px\] { padding: 7px; } .px-2 { padding-left: 0.5rem; padding-right: 0.5rem; } .px-3 { padding-left: 0.75rem; padding-right: 0.75rem; } .px-5 { padding-left: 1.25rem; padding-right: 1.25rem; } .px-6 { padding-left: 1.5rem; padding-right: 1.5rem; } .py-1 { padding-top: 0.25rem; padding-bottom: 0.25rem; } .py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; } .py-2\.5 { padding-top: 0.625rem; padding-bottom: 0.625rem; } .py-3 { padding-top: 0.75rem; padding-bottom: 0.75rem; } .py-4 { padding-top: 1rem; padding-bottom: 1rem; } .py-5 { padding-top: 1.25rem; padding-bottom: 1.25rem; } .py-8 { padding-top: 2rem; padding-bottom: 2rem; } .pb-10 { padding-bottom: 2.5rem; } .pb-4 { padding-bottom: 1rem; } .pb-6 { padding-bottom: 1.5rem; } .pl-9 { padding-left: 2.25rem; } .pr-3 { padding-right: 0.75rem; } .pt-20 { padding-top: 5rem; } .text-left { text-align: left; } .text-center { text-align: center; } .font-poppins { font-family: Poppins, sans-serif; } .text-2xl { font-size: 1.5rem; line-height: 2rem; } .text-3xl { font-size: 1.875rem; line-height: 2.25rem; } .text-4xl { font-size: 2.25rem; line-height: 2.5rem; } .text-base { font-size: 1rem; line-height: 1.5rem; } .text-lg { font-size: 1.125rem; line-height: 1.75rem; } .text-sm { font-size: 0.875rem; line-height: 1.25rem; } .text-xl { font-size: 1.25rem; line-height: 1.75rem; } .text-xs { font-size: 0.75rem; line-height: 1rem; } .font-bold { font-weight: 700; } .font-light { font-weight: 300; } .font-medium { font-weight: 500; } .font-normal { font-weight: 400; } .font-semibold { font-weight: 600; } .uppercase { text-transform: uppercase; } .leading-tight { line-height: 1.25; } .tracking-tight { letter-spacing: -0.025em; } .text-gray-400 { --tw-text-opacity: 1; color: rgb(156 163 175 / var(--tw-text-opacity)); } .text-gray-500 { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity)); } .text-gray-600 { --tw-text-opacity: 1; color: rgb(75 85 99 / var(--tw-text-opacity)); } .text-gray-700 { --tw-text-opacity: 1; color: rgb(55 65 81 / var(--tw-text-opacity)); } .text-gray-900 { --tw-text-opacity: 1; color: rgb(17 24 39 / var(--tw-text-opacity)); } .text-green-500 { --tw-text-opacity: 1; color: rgb(34 197 94 / var(--tw-text-opacity)); } .text-secondary { --tw-text-opacity: 1; color: rgb(210 91 4 / var(--tw-text-opacity)); } .text-slate-500 { --tw-text-opacity: 1; color: rgb(100 116 139 / var(--tw-text-opacity)); } .text-white { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .shadow { --tw-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow-md { --tw-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow-sm { --tw-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); --tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .transition-transform { transition-property: transform; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .duration-200 { transition-duration: 200ms; } .ease-in { transition-timing-function: cubic-bezier(0.4, 0, 1, 1); } body { background: #f5f5fb; } .placeholder\:italic::-moz-placeholder { font-style: italic; } .placeholder\:italic::placeholder { font-style: italic; } .placeholder\:text-slate-400::-moz-placeholder { --tw-text-opacity: 1; color: rgb(148 163 184 / var(--tw-text-opacity)); } .placeholder\:text-slate-400::placeholder { --tw-text-opacity: 1; color: rgb(148 163 184 / var(--tw-text-opacity)); } .hover\:translate-x-2:hover { --tw-translate-x: 0.5rem; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .hover\:bg-blue-700:hover { --tw-bg-opacity: 1; background-color: rgb(29 78 216 / var(--tw-bg-opacity)); } .hover\:bg-blue-800:hover { --tw-bg-opacity: 1; background-color: rgb(30 64 175 / var(--tw-bg-opacity)); } .hover\:bg-gray-100:hover { --tw-bg-opacity: 1; background-color: rgb(243 244 246 / var(--tw-bg-opacity)); } .hover\:bg-gray-200:hover { --tw-bg-opacity: 1; background-color: rgb(229 231 235 / var(--tw-bg-opacity)); } .hover\:bg-green-800:hover { --tw-bg-opacity: 1; background-color: rgb(22 101 52 / var(--tw-bg-opacity)); } .hover\:bg-red-700:hover { --tw-bg-opacity: 1; background-color: rgb(185 28 28 / var(--tw-bg-opacity)); } .hover\:bg-secondary-hover:hover { --tw-bg-opacity: 1; background-color: rgb(171 69 0 / var(--tw-bg-opacity)); } .hover\:bg-yellow-500:hover { --tw-bg-opacity: 1; background-color: rgb(234 179 8 / var(--tw-bg-opacity)); } .hover\:text-gray-100:hover { --tw-text-opacity: 1; color: rgb(243 244 246 / var(--tw-text-opacity)); } .hover\:text-gray-600:hover { --tw-text-opacity: 1; color: rgb(75 85 99 / var(--tw-text-opacity)); } .hover\:text-gray-800:hover { --tw-text-opacity: 1; color: rgb(31 41 55 / var(--tw-text-opacity)); } .hover\:text-gray-900:hover { --tw-text-opacity: 1; color: rgb(17 24 39 / var(--tw-text-opacity)); } .hover\:text-secondary-hover:hover { --tw-text-opacity: 1; color: rgb(171 69 0 / var(--tw-text-opacity)); } .hover\:text-slate-100:hover { --tw-text-opacity: 1; color: rgb(241 245 249 / var(--tw-text-opacity)); } .hover\:underline:hover { text-decoration-line: underline; } .focus\:border-blue-500:focus { --tw-border-opacity: 1; border-color: rgb(59 130 246 / var(--tw-border-opacity)); } .focus\:border-secondary:focus { --tw-border-opacity: 1; border-color: rgb(210 91 4 / var(--tw-border-opacity)); } .focus\:outline-none:focus { outline: 2px solid transparent; outline-offset: 2px; } .focus\:ring-1:focus { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .focus\:ring-2:focus { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .focus\:ring-4:focus { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .focus\:ring-blue-500:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity)); } .focus\:ring-gray-200:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(229 231 235 / var(--tw-ring-opacity)); } .focus\:ring-gray-300:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(209 213 219 / var(--tw-ring-opacity)); } .focus\:ring-secondary:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(210 91 4 / var(--tw-ring-opacity)); } @media (prefers-color-scheme: dark) { .dark\:border-gray-600 { --tw-border-opacity: 1; border-color: rgb(75 85 99 / var(--tw-border-opacity)); } .dark\:border-gray-700 { --tw-border-opacity: 1; border-color: rgb(55 65 81 / var(--tw-border-opacity)); } .dark\:bg-gray-700 { --tw-bg-opacity: 1; background-color: rgb(55 65 81 / var(--tw-bg-opacity)); } .dark\:bg-gray-800 { --tw-bg-opacity: 1; background-color: rgb(31 41 55 / var(--tw-bg-opacity)); } .dark\:bg-gray-900 { --tw-bg-opacity: 1; background-color: rgb(17 24 39 / var(--tw-bg-opacity)); } .dark\:text-gray-400 { --tw-text-opacity: 1; color: rgb(156 163 175 / var(--tw-text-opacity)); } .dark\:text-white { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .dark\:placeholder-gray-400::-moz-placeholder { --tw-placeholder-opacity: 1; color: rgb(156 163 175 / var(--tw-placeholder-opacity)); } .dark\:placeholder-gray-400::placeholder { --tw-placeholder-opacity: 1; color: rgb(156 163 175 / var(--tw-placeholder-opacity)); } .dark\:focus\:border-blue-500:focus { --tw-border-opacity: 1; border-color: rgb(59 130 246 / var(--tw-border-opacity)); } .dark\:focus\:ring-blue-500:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity)); } } @media (min-width: 412px) { .sm\:ml-64 { margin-left: 16rem; } .sm\:translate-x-0 { --tw-translate-x: 0px; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .sm\:rounded-lg { border-radius: 0.5rem; } .sm\:p-8 { padding: 2rem; } .sm\:text-sm { font-size: 0.875rem; line-height: 1.25rem; } } @media (min-width: 768px) { .md\:inset-0 { inset: 0px; } .md\:-mt-16 { margin-top: -4rem; } .md\:ml-3 { margin-left: 0.75rem; } .md\:mr-6 { margin-right: 1.5rem; } .md\:hidden { display: none; } .md\:w-\[30rem\] { width: 30rem; } .md\:w-full { width: 100%; } .md\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } .md\:flex-row { flex-direction: row; } .md\:flex-wrap { flex-wrap: wrap; } .md\:items-center { align-items: center; } .md\:justify-between { justify-content: space-between; } .md\:gap-8 { gap: 2rem; } .md\:gap-x-2 { -moz-column-gap: 0.5rem; column-gap: 0.5rem; } .md\:space-y-6 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(1.5rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(1.5rem * var(--tw-space-y-reverse)); } .md\:bg-transparent { background-color: transparent; } .md\:p-5 { padding: 1.25rem; } .md\:text-lg { font-size: 1.125rem; line-height: 1.75rem; } } @media (min-width: 1024px) { .lg\:px-5 { padding-left: 1.25rem; padding-right: 1.25rem; } .lg\:pl-3 { padding-left: 0.75rem; } }
// // BookManager.swift // BFY // // Created by Анастасия Московчук on 16.11.2021. // import Foundation final class BookInfo: Equatable { let id: String let title: String let authors: [String]? let image: String? convenience init(from book: BooksBody) { self.init( id: book.id, title: book.volumeInfo.title, authors: book.volumeInfo.authors ?? [""], image: book.volumeInfo.imageLinks?.smallThumbnail ?? "" ) } init(id: String, title: String, authors: [String], image: String) { self.id = id self.title = title self.authors = authors self.image = image } static func ==(lhs: BookInfo, rhs: BookInfo) -> Bool { return lhs.id == rhs.id } }
--- id: 72 title: 'C#: Working with Azure IMDS' summary: 'C#: Working with Azure IMDS' date: '2023-08-22T13:58:28+00:00' author: admin layout: post guid: 'https://porotnikov.com/?p=72' permalink: /2023/08/22/c-working-with-azure-imds/ categories: - Code --- ## C#: Working with Azure IMDS ```csharp class Program { static void Main(string[] args) { //Identify Storage Type Using Azure Metadata Service string url = "http://169.254.169.254/metadata/instance?api-version=2021-02-01"; WebClient client = new WebClient(); client.Headers.Add("Metadata", "true"); try { string response = client.DownloadString(url); dynamic data = JsonConvert.DeserializeObject(response); string storageProfile = data.compute.storageProfile.ToString(); dynamic storageData = JsonConvert.DeserializeObject(storageProfile); string osDiskName = storageData.osDisk.name; string osDiskCaching = storageData.osDisk.caching; string osDiskSize = storageData.osDisk.diskSizeGB; string writeAcceleratorEnabled = storageData.osDisk.writeAcceleratorEnabled; string datadisks = storageData.dataDisks.ToString(); Console.WriteLine("OS Disk Name: " + osDiskName); Console.WriteLine("OS Disk Caching: " + osDiskCaching); Console.WriteLine("OS Disk Size: " + osDiskSize); Console.WriteLine("writeAcceleratorEnabled: " + writeAcceleratorEnabled); Console.WriteLine("Data disks: " + datadisks); //Parse Datadisks and check caching / write acceleration / SKU type same as OS disk above, by deserializing JSON response. } catch (WebException ex) { //If we are running on non Azure VM or there are networking restrictions the connection will timeout: Console.WriteLine("Error: " + ex.Message); } } } ```
import pytest from sqlalchemy.exc import IntegrityError from aurweb import db, time from aurweb.models.account_type import PACKAGE_MAINTAINER_ID from aurweb.models.user import User from aurweb.models.vote import Vote from aurweb.models.voteinfo import VoteInfo @pytest.fixture(autouse=True) def setup(db_test): return @pytest.fixture def user() -> User: with db.begin(): user = db.create( User, Username="test", Email="test@example.org", RealName="Test User", Passwd="testPassword", AccountTypeID=PACKAGE_MAINTAINER_ID, ) yield user @pytest.fixture def voteinfo(user: User) -> VoteInfo: ts = time.utcnow() with db.begin(): voteinfo = db.create( VoteInfo, Agenda="Blah blah.", User=user.Username, Submitted=ts, End=ts + 5, Quorum=0.5, Submitter=user, ) yield voteinfo def test_vote_creation(user: User, voteinfo: VoteInfo): with db.begin(): vote = db.create(Vote, User=user, VoteInfo=voteinfo) assert vote.VoteInfo == voteinfo assert vote.User == user assert vote in user.votes assert vote in voteinfo.votes def test_vote_null_user_raises_exception(voteinfo: VoteInfo): with pytest.raises(IntegrityError): Vote(VoteInfo=voteinfo) def test_vote_null_voteinfo_raises_exception(user: User): with pytest.raises(IntegrityError): Vote(User=user)
import { When, Then } from '@cucumber/cucumber'; import { AnyCcdFormPage } from '../../pages/any-ccd-form.page'; import { expect } from 'chai'; const anyCcdPage = new AnyCcdFormPage(); When('I select {string} and {string} Elements', async function (string, string2) { await anyCcdPage.clickElementById('elementsDisputedList-housing'); await anyCcdPage.clickElementById('elementsDisputedList-childcare'); await anyCcdPage.clickContinue(); }); When('I add issue codes for respective elements', async function () { expect(await anyCcdPage.pageHeadingContains('Issue codes')).to.equal(true); await anyCcdPage.addNewCollectionItem('Housing'); await anyCcdPage.selectHousingIssueCode(); await anyCcdPage.addNewCollectionItem('Childcare'); await anyCcdPage.selectChildcareIssueCode(); await anyCcdPage.clickContinue(); }); Then('the Amend elements event should be seen in "History" tab', async function () { const events = await anyCcdPage.getHistoryEvents(); expect(events).to.include('Amend elements/issues'); }); Then('I should see the choose elements and issue code within "Elements and issues" tab', async function () { await anyCcdPage.clickTab('Elements and issues'); expect(await anyCcdPage.contentContains('Housing')).to.equal(true); expect(await anyCcdPage.contentContains('Childcare')).to.equal(true); });
import "./style/App.css"; import "./style/App.mobile.css"; import React from "react"; import { createBrowserRouter, RouterProvider } from "react-router-dom"; import Home from './pages/Home'; import Detail from './pages/Detail'; import Login from "./pages/Login"; import Register from "./pages/Register"; import ChooseSeat from "./pages/ChooseSeat"; // list page const router = createBrowserRouter([ { path: "/", element: <Home />, }, { path: "/login", element: <Login />, }, { path: "/register", element: <Register />, }, { path: "/detail/:slug", element: <Detail />, }, { path: "/choose-seat/:slug", element: <ChooseSeat />, }, ]); function App() { // register to application return <RouterProvider router={router} />; } export default App;