text
stringlengths
184
4.48M
<?php namespace App\Http\Livewire; use App\Models\Job; use Livewire\Component; use Ramsey\Uuid\Type\Integer; class Search extends Component { public String $query = '' ; public $jobs = []; public Int $selectedIndex = 0; public function incrementIndex() { if ($this->selectedIndex === (count($this->jobs) - 1)) { $this->selectedIndex = 0; return; } $this->selectedIndex++; } public function decrementIndex() { if ($this->selectedIndex === 0) { $this->selectedIndex = count($this->jobs) - 1; return; } $this->selectedIndex--; } public function updatedQuery() { if (strlen($this->query) > 3 ) { $words = '%' . $this->query . '%'; $this->jobs = Job::where('title', 'like', $words) ->orWhere('description', 'like', $words) ->get(); } } public function selectIndex() { if ($this->jobs->isNotEmpty()) { $this->redirect(route('jobs.show', $this->jobs[$this->selectedIndex]['id'])); } } public function resetIndex() { $this->reset('selectedIndex'); } public function render() { return view('livewire.search'); } }
package com.palma.ecommerceArte.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import com.palma.ecommerceArte.model.Client; import com.palma.ecommerceArte.service.ClientService; @CrossOrigin(origins = "http://localhost:3000", maxAge = 360000) @Controller //@CrossOrigin(origins = "http://localhost:3000", maxAge = 360000, allowCredentials = "true") @RequestMapping("/api/clients") public class ClientController { @Autowired ClientService service; @GetMapping public ResponseEntity<?> getAll() { return new ResponseEntity<List<Client>>(service.getAllClient(), HttpStatus.OK); } @GetMapping("/id/{id}") public ResponseEntity<?> getById(@PathVariable("id") Long id) { return new ResponseEntity<>(service.getClient(id), HttpStatus.OK); } @PostMapping @PreAuthorize("hasRole('ADMIN')") public ResponseEntity<?> createClient(@RequestBody Client c) { return new ResponseEntity<Client>(service.createClient(c), HttpStatus.CREATED); } @DeleteMapping("/{id}") @PreAuthorize("hasRole('ADMIN')") public ResponseEntity<String> deleteClient(@PathVariable Long id){ return new ResponseEntity<String>(service.removeClient(id), HttpStatus.OK); } @PutMapping @PreAuthorize("hasRole('ADMIN')") public ResponseEntity<?> updateUser(@RequestBody Client c) { return new ResponseEntity<Client>(service.updateClient(c), HttpStatus.CREATED); } }
<?php namespace App\Models; use App\Models\Movie; use Laravel\Sanctum\HasApiTokens; use Spatie\Permission\Traits\HasRoles; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable, HasRoles; /** * 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 movies() { return $this->belongsToMany(Movie::class, 'user_movie'); } }
package; import Sys.sleep; #if DISCORD_ALLOWED import discord_rpc.DiscordRpc; #end #if LUA_ALLOWED import llua.Lua; import llua.State; #end using StringTools; class DiscordClient { public static var isInitialized:Bool = false; #if DISCORD_ALLOWED public static var queue:DiscordPresenceOptions = { details: "In the Menus", state: null, largeImageKey: 'icon', largeImageText: "Psych Engine" } #end public function new() { #if DISCORD_ALLOWED trace("Discord Client starting..."); DiscordRpc.start({ clientID: "926097904664473660", onReady: onReady, onError: onError, onDisconnected: onDisconnected }); trace("Discord Client started."); while (true) { DiscordRpc.process(); sleep(2); //trace("Discord Client Update"); } DiscordRpc.shutdown(); #end } public static function shutdown() { #if DISCORD_ALLOWED DiscordRpc.shutdown(); isInitialized = false; #end } static function onReady() { #if DISCORD_ALLOWED changePresence( queue.details, queue.state, queue.smallImageKey, queue.startTimestamp == 1 ? true : false, queue.endTimestamp ); #end } static function onError(_code:Int, _message:String) { trace('Error! $_code : $_message'); } static function onDisconnected(_code:Int, _message:String) { trace('Disconnected! $_code : $_message'); } public static function initialize() { #if DISCORD_ALLOWED if (ClientPrefs.discordRPC != 'Deactivated') { var DiscordDaemon = sys.thread.Thread.create(() -> { new DiscordClient(); }); trace("Discord Client initialized"); isInitialized = true; } #end } public static function changePresence(details:String, state:Null<String>, ?smallImageKey : String, ?hasStartTimestamp : Bool, ?endTimestamp: Float) { #if DISCORD_ALLOWED var startTimestamp:Float = if(hasStartTimestamp) Date.now().getTime() else 0; if (endTimestamp > 0) { endTimestamp = startTimestamp + endTimestamp; } var presence:DiscordPresenceOptions = { details: details, state: state, largeImageKey: 'icon', largeImageText: "Rhythm Engine Version: " + MainMenuState.rhythmVersion, smallImageKey : smallImageKey, // Obtained times are in milliseconds so they are divided so Discord can use it startTimestamp : Std.int(startTimestamp / 1000), endTimestamp : Std.int(endTimestamp / 1000) }; if (ClientPrefs.discordRPC == 'Deactivated' || !isInitialized) { presence.startTimestamp = if (hasStartTimestamp) 1 else 0; presence.endTimestamp = Std.int(endTimestamp); // It wont be perfectly accurated anymore, whatever, theyre just milliseconds afterall - Nex queue = presence; } else { if (ClientPrefs.discordRPC == 'Hide Infos') { presence.details = null; presence.state = null; presence.smallImageKey = null; presence.startTimestamp = 0; presence.endTimestamp = 0; } DiscordRpc.presence(presence); //trace('Discord RPC Updated. Arguments: $details, $state, $smallImageKey, $hasStartTimestamp, $endTimestamp'); } #end } #if LUA_ALLOWED public static function addLuaCallbacks(lua:State) { Lua_helper.add_callback(lua, "changePresence", function(details:String, state:Null<String>, ?smallImageKey:String, ?hasStartTimestamp:Bool, ?endTimestamp:Float) { changePresence(details, state, smallImageKey, hasStartTimestamp, endTimestamp); }); } #end }
import React, { useState } from 'react'; import bookImg from '../../images/books.jpg'; import { useHistory } from 'react-router-dom'; import { Card, Typography, CardActions, CardMedia, CardContent, Button, } from '@mui/material'; export default function BookDashboardCard({ books }) { const history = useHistory(); const [elevation, setElevation] = useState(0); return ( <div> <Card sx={{ width: 345 }} elevation={elevation} onMouseOver={() => { setElevation(20); }} onMouseOut={() => { setElevation(0); }} > <CardMedia component='img' height='140' image={bookImg} alt='green iguana' /> <CardContent> <Typography gutterBottom variant='h5' component='div'> Books </Typography> <Typography variant='body2' color='text.secondary'> Currently we have {books} in our collection contributed by our verified users </Typography> </CardContent> <CardActions> <Button size='small' onClick={() => { history.push('/books'); }} > Visit </Button> <Button size='small' onClick={() => { history.push('/contribute'); }} > Contribute </Button> </CardActions> </Card> </div> ); }
<x-layout> <x-breadcrumbs class="mb-4" :links="['Jobs'=>route('jobs.index')]" /> <x-card class="mb-4 text-sm" x-data=""> <form x-ref="filters" id="filtering-form" action="{{route('jobs.index')}}" method="GET"> <div class="mb-54 grid grid-cols-2 gap-4"> <div> <div class="mb-1 font-semibold">Search</div> <x-text-input name="search" value="{{request('search')}}" placeholder="Search for any text" form-ref="filters" /> </div> <div> <div class="mb-1 font-semibold">Salary</div> <div class="flex space-x-2"> <x-text-input name="min_salary" value="{{request('min_salary')}}" placeholder="From" form-ref="filters" /> <x-text-input name="max_salary" value="{{request('max_salary')}}" placeholder="To" form-ref="filters" /> </div> </div> <div> <div class="mb-1 font-semibold">Experience</div> <x-radio-group name="experience" :options="array_combine( array_map('ucfirst',\App\Models\Job::$experience), \App\Models\Job::$experience)" /> </div> <div> <div class="mb-1 font-semibold">Category</div> <x-radio-group name="category" :options="\App\Models\Job::$category" /> </div> </div> <x-button class="w-full bg-zinc-700 text-white px-1.5 py-2 rounded-md my-2 hover:bg-zinc-800">Filter</x-button> </form> </x-card> @foreach ($jobs as $job) <x-job-card class="mb-4" :$job> <div> <x-link-button :href="route('jobs.show',$job)"> Show </x-link-button> </div> </x-job-card> @endforeach </x-layout>
<div class="timepicker"> <ul class="nav nav-tabs" role="tablist" ng-init="tab = 'filter'"> <li ng-class="{active:tab == 'filter'}"> <a href ng-click="tab = 'filter'">Time Filter</a> </li> <li ng-class="{active:tab == 'interval'}"> <a href ng-click="tab = 'interval'">Refresh Interval</a> </li> </ul> <div class="tab-content"> <!-- Filters --> <div ng-show="tab == 'filter'" role="tabpanel" class="tab-pane active"> <br> <div class="row"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked"> <li ng-class="{active: timepicker.mode=='quick'}"> <a href ng-click="timepicker.setMode('quick')">Quick</a> </li> <li ng-class="{active: timepicker.mode=='relative'}"> <a href ng-click="timepicker.setMode('relative')">Relative</a> </li> <li ng-class="{active: timepicker.mode=='absolute'}"> <a href ng-click="timepicker.setMode('absolute')">Absolute</a> </li> </ul> </div> <div class="col-md-10"> <div ng-switch on="timepicker.mode" class="container-fluid"> <!-- Quick --> <div ng-switch-when="quick"> <div ng-repeat="list in timepicker.quickLists" class="timepicker-section"> <ul class="list-unstyled"> <li ng-repeat="option in list"> <a href ng-click="timepicker.setQuick(option)">{{ option.display }}</a> </li> </ul> </div> </div> <!-- Relative --> <div ng-switch-when="relative"> <form ng-submit="timepicker.setRelative()" class="form-inline" name="relativeTime"> <div class="timepicker-section"> <label> From: </label> <br> <div class="form-group"> <input required ng-model="timepicker.relative.count" ng-change="timepicker.relativeValidate()" type="number" class="form-control"> </div> <div class="form-group"> <select ng-model="timepicker.relative.unit" ng-options="opt.value as opt.text for opt in timepicker.relativeOptions" class="form-control col-xs-2"> </select> </div> </div> <div class="timepicker-section"> <label> To: </label> <br> <div class="form-group"> <input type="text" disabled class="form-control" value="Now"> </div> </div> <div class="timepicker-section"> <label>&nbsp;</label> <br> <div class="form-group"> <button type="submit" class="btn btn-primary" ng-disabled="!timepicker.relative.valid"> Go </button> </div> </div> </form> </div> <!-- Absolute --> <div ng-switch-when="absolute"> <form name="absoluteTime" ng-submit="timepicker.setAbsolute()"> <div class="timepicker-section"> <div> <label class="small">From: <span ng-show="!timepicker.absolute.from"><i>Invalid Date</i></span> </label> <input type="text" required class="form-control" input-datetime="{{timepicker.format}}" ng-change="timepicker.absoluteValidate()" ng-model="timepicker.absolute.from"> </div> <div> <datepicker ng-model="timepicker.absolute.from" max="timepicker.absolute.to" show-weeks="false" ng-change="timepicker.absoluteValidate()"> </datepicker> </div> </div> <div class="timepicker-section"> <div> <label class="small">To: <span ng-show="!timepicker.absolute.to"><i>Invalid Date</i></span> </label> <input type="text" required class="form-control" input-datetime="{{timepicker.format}}" ng-change="timepicker.absoluteValidate()" ng-model="timepicker.absolute.to"> </div> <div> <datepicker ng-model="timepicker.absolute.to" min="timepicker.absolute.from" show-weeks="false" ng-change="timepicker.absoluteValidate()"> </datepicker> </div> </div> <div class="timepicker-section"> <label>&nbsp;</label> <div class="form-group"> <button class="btn btn-primary" ng-disabled="!timepicker.absolute.valid" type="submit"> Go </button> <span class="small" ng-show="timepicker.absolute.from >= timepicker.absolute.to"><strong>From</strong> must occur before <strong>To</strong></span> </div> </div> </form> </div> </div> </div> </div> </div> <!-- Refresh Intervals --> <div ng-show="tab == 'interval'" role="tabpanel" class="tab-pane active"> <div ng-repeat="list in timepicker.refreshLists" class="timepicker-section"> <ul class="list-unstyled"> <li ng-repeat="interval in list"><a ng-click="timepicker.setRefreshInterval(interval)">{{interval.display}}</a></li> </ul> </div> <div class="clearfix"></div> </div> </div> </div>
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class accountValidator extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required', 'desc' => 'required' ]; } public function messages() { return [ 'name.required' => 'We need to know your name.', 'desc.required' => 'The description field is required.' ]; } }
signature ========= Ever wanted to have witty and pithy sigs attached to your e-mail and news postings, but got tired having the same old one attached every time? That's where signature comes in. signature is a free, open-source producer of dynamic signatures for livening up your e-mail and news postings. It will allow you to sign your messages with a different sig every time. The idea for the program came from an old Perl script in the Camel Book (http://www.oreilly.com/catalog/pperl2/) that demonstrated the use of named pipes. This C implementation was written as an exercise in programming. I'm an experienced UNIX sysadmin, not a professional programmer, although back in the dark ages I used to program for pleasure quite a lot in BASIC (back when they still used line numbers), Pascal, Modula-2 and Z80 assembler. In recent years, I've used Perl more or less exclusively, and - since it's such a flexible language - I just never got further than the basics of C. I decided to change all that recently and have been doing a lot of reading and sifting through C code. signature is pretty much the first fruit to come of these labours. Since this program is the work of a novice in C, please excuse any golden rules of programming that I've inadvertently broken in the code. Do feel free to inform me of them, however, and I'll endeavour to find a way to program more elegantly. signature has been successfully compiled and tested on Linux 2.2.x. Early versions were also known to work on Solaris 2.6. Maybe the current one still does, but I no longer have access to such a box to test it. I'd like signature to be portable if at all possible, so if there's a platform you'd like it to work on, let me know what's required (or better still, send a diff). The program was developed on an x86 Red Hat Linux 6.2 system. Sources consulted during the development of this software include: 'Beginning Linux Programming' by Richard Stones & Neil Matthew (1996 Wrox Press ISBN 1-874416-68-0) This excellent book gave me the lowdown on many of the techniques used in the code. Linux Man Page HOWTO by Jens Schweikhardt <schweikh@noc.dfn.de> and man(7) by Rickard E. Faith <faith@cs.unc.edu> & David A. Wheeler <dwheeler@ida.org> (http://www.linuxdoc.org/HOWTO/mini/Man-Page.html) These gave me the Linux standard by which to write my man page, plus many useful tips on producing documentation. GNU Coding Standards by Richard Stallman (http://www.fsf.org/prep/standards_toc.html) This very thorough document provided some excellent pointers on how to write the code. I can't say I agree with the whole document, however, so the code in signature isn't entirely compliant. GNU autoconf & automake manuals (http://www.fsf.org/manual/manual.html) These explained how to create a decent build environment. Software Release Practice HOWTO v2.0 by Eric S. Raymond <esr@thyrsus.com> (http://www.linuxdoc.org/HOWTO/Software-Release-Practice-HOWTO.html) This explained how to go about releasing the package. Read INSTALL for details on how to compile and install the program and its man page. The software can be obtained from: http://www.caliban.org/files/signature/signature-0.14.tar.gz RPM format packages can be obtained from: http://www.caliban.org/files/signature/signature-0.14-1.i386.rpm http://www.caliban.org/files/signature/signature-0.14-1.src.rpm The source code is available under the GPL 2.0 licence. -- Ian Macdonald <ian@caliban.org>
<template> <section :style="{ left: posX + 'px', top: posY + 'px' }" class="doodle"> <div @mousedown="startDrag" class="name"> <div class="line"> </div> <div class="line"> </div> <div class="line"> </div> <h1 class="name"> Doodle a duck</h1> <div class="line"> </div> <div class="line"> </div> <div class="line"> </div> </div> <div class="doodle-ui" id="canvasContainer"> <div class="colors"> <div v-for="(color, index) in colorSwatches" :key="index" :id="color.id" :class="{ 'color-swatch': true, active: color.isActive }" @click="selectColor(color.id)"></div> </div> <div class="p5-sketch"> <div id="p5Sketch"></div> <div class="controls"> <div class="brush-controls"> <button v-for="(size, index) in brushThickness" :key="index" :id="size.id" :class="{ 'brush-thickness': true, active: size.isActive }" @click="selectSize(size.id)">●</button> </div> <div class="canvas-controls"> <button id="clearButton"><img class="button-icons" src="@/assets/icons/clear.svg" alt="clear canvas"> Clear </button> <button id="saveButton"><img class="button-icons" src="@/assets/icons/save.svg" alt="download canvas">Download</button> </div> </div> </div> </div> </section> </template> <script> export default { name: 'Doodle', data() { return { posX: 0, posY: 0, dragging: false, offsetX: 0, offsetY: 0, colorSwatches: [ { id: 'red', isActive: false }, { id: 'orange', isActive: false }, { id: 'yellow', isActive: false }, { id: 'black', isActive: true }, { id: 'white', isActive: false }, { id: 'green', isActive: false }, { id: 'blue', isActive: false }, { id: 'purple', isActive: false }, ], brushThickness: [ { id: 'small', isActive: false }, { id: 'medium', isActive: true }, { id: 'big', isActive: false }, ] } }, methods: { startDrag(event) { this.dragging = true; this.offsetX = event.clientX - this.posX; this.offsetY = event.clientY - this.posY; document.addEventListener('mousemove', this.drag); document.addEventListener('mouseup', this.stopDrag); }, drag(event) { if (this.dragging) { this.posX = event.clientX - this.offsetX; this.posY = event.clientY - this.offsetY; } }, stopDrag() { this.dragging = false; document.removeEventListener('mousemove', this.drag); document.removeEventListener('mouseup', this.stopDrag); }, selectColor(selectedId) { this.colorSwatches.forEach((color) => { color.isActive = color.id === selectedId; }); }, selectSize(selectedId) { this.brushThickness.forEach((size) => { size.isActive = size.id === selectedId; }) } }, } </script> <style lang="scss" scoped> @import "../assets/variables.scss"; section.doodle { position: relative; border: 1px solid $black; width: auto; background-color: $white; box-shadow: -4px 4px 0px 0px $black; } div.doodle-ui { display: flex; align-items: center; width: auto; height: 100%; background-color: $darkerGrey; overflow: auto; padding: 0 24px 64px 24px; } .p5-sketch { display: flex; flex-direction: column; height: auto; width: auto; } .colors { display: flex; flex-direction: column; } .color-swatch { width: 40px; height: 40px; margin: 8px 24px 8px 0; border-top: 1px solid #000; border-right: 1px solid #000; border-bottom: 2px solid #000; border-left: 2px solid #000; cursor: pointer; opacity: .48; } .color-swatch.active { opacity: 1; transform: scale(1.15); box-shadow: 6px -6px 0.5px 0px rgba(0, 0, 0, 0.08) inset, -4px 4px 0px 0px rgba(255, 255, 255, 0.25) inset; } .color-swatch:hover { opacity: .9; transform: scale(1.15); } .controls { display: flex; width: 100%; margin: 16px 0; justify-content: space-between; } .brush-controls { display: flex; gap: 16px; } .brush-thickness { width: 40px; padding: 0; display: flex; justify-content: center; align-content: center; opacity: .48; } .brush-thickness.active { opacity: 1; transform: scale(1.15); box-shadow: 6px -6px 0.5px 0px rgba(0, 0, 0, 0.08) inset, -4px 4px 0px 0px rgba(255, 255, 255, 0.25) inset; } .canvas-controls { display: flex; gap: 16px; } button { font-family: 'IBM Plex Mono', monospace; font-weight: bold; background-color: $white; border-top: 1px solid #000; border-right: 1px solid #000; border-bottom: 2px solid #000; border-left: 2px solid #000; padding: 12px 16px; height: 40px; cursor: pointer; display: flex; align-items: center; } .canvas-controls button:active { transform: translateY(2px); } .canvas-controls button:hover { background-color: $lightGrey; } .button-icons { width: 24px; border: 4px; stroke: 4px; margin: 0 8px 0 0; } #red { background-color: #E64E4E; } #orange { background-color: #FF9922; } #yellow { background-color: #FFD12E; } #green { background-color: #72F170; } #blue { background-color: #2E75FF; } #purple { background-color: #C92EFF; } #white { background-color: white; } #black { background-color: black; } #small { font-size: 8px; } #medium { font-size: 16px; } #big { font-size: 32px; padding-bottom: 5px; } </style>
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.omnibox.suggestions.querytiles; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; import static org.chromium.components.omnibox.GroupConfigTestSupport.SECTION_QUERY_TILES; import androidx.test.filters.SmallTest; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.chromium.base.test.util.Batch; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.JniMocker; import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.omnibox.OmniboxFeatures; import org.chromium.chrome.browser.omnibox.suggestions.AutocompleteController; import org.chromium.chrome.browser.omnibox.suggestions.AutocompleteControllerJni; import org.chromium.chrome.browser.omnibox.suggestions.carousel.BaseCarouselSuggestionView; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.chrome.test.util.OmniboxTestUtils; import org.chromium.components.omnibox.AutocompleteMatchBuilder; import org.chromium.components.omnibox.AutocompleteResult; import org.chromium.components.omnibox.GroupsProto.GroupsInfo; import org.chromium.components.omnibox.OmniboxSuggestionType; import org.chromium.components.omnibox.suggestions.OmniboxSuggestionUiType; import org.chromium.content_public.browser.test.util.TestThreadUtils; import java.util.List; /** Tests of the Query Tiles. */ @RunWith(ChromeJUnit4ClassRunner.class) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) @Batch(Batch.PER_CLASS) public class QueryTilesTest { private static final int QUERY_TILE_CAROUSEL_MATCH_POSITION = 1; public final @Rule ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule(); public @Rule MockitoRule mMockitoRule = MockitoJUnit.rule(); public @Rule JniMocker mJniMocker = new JniMocker(); private @Mock AutocompleteController.Natives mAutocompleteControllerJniMock; private @Mock AutocompleteController mController; private ChromeTabbedActivity mActivity; private AutocompleteController.OnSuggestionsReceivedListener mListener; private OmniboxTestUtils mOmnibox; @Before public void setUp() throws Exception { mJniMocker.mock(AutocompleteControllerJni.TEST_HOOKS, mAutocompleteControllerJniMock); doReturn(mController).when(mAutocompleteControllerJniMock).getForProfile(any()); doAnswer( inv -> { mListener = inv.getArgument(0); return null; }) .when(mController) .addOnSuggestionsReceivedListener(any()); mActivityTestRule.startMainActivityOnBlankPage(); mActivityTestRule.waitForActivityNativeInitializationComplete(); mActivity = mActivityTestRule.getActivity(); OmniboxFeatures.QUERY_TILES_SHOW_AS_CAROUSEL.setForTesting(true); mOmnibox = new OmniboxTestUtils(mActivity); setUpSuggestionsToShow(); } @After public void tearDown() { mOmnibox.clearFocus(); } /** Initialize a small set of suggestions with QueryTiles, and focus the Omnibox. */ private void setUpSuggestionsToShow() { var search = AutocompleteMatchBuilder.searchWithType(OmniboxSuggestionType.SEARCH_SUGGEST) .setDisplayText("Search") .build(); var queryTile = AutocompleteMatchBuilder.searchWithType(OmniboxSuggestionType.TILE_SUGGESTION) .setGroupId(1); var acResult = AutocompleteResult.fromCache( List.of( search, queryTile.setDisplayText("News").build(), queryTile.setDisplayText("Music").build(), queryTile.setDisplayText("Movies").build(), queryTile.setDisplayText("Sports").build(), queryTile.setDisplayText("Fun").build(), search), GroupsInfo.newBuilder().putGroupConfigs(1, SECTION_QUERY_TILES).build()); mOmnibox.requestFocus(); verify(mController).startZeroSuggest(anyString(), any(), anyInt(), anyString()); TestThreadUtils.runOnUiThreadBlocking( () -> mListener.onSuggestionsReceived(acResult, "", true)); mOmnibox.checkSuggestionsShown(); } @Test @SmallTest public void queryTilesCarouselIsShowing() throws Exception { var carousel = mOmnibox.findSuggestionWithType(OmniboxSuggestionUiType.QUERY_TILES); assertNotNull(carousel); assertTrue(carousel.view instanceof BaseCarouselSuggestionView); assertEquals(QUERY_TILE_CAROUSEL_MATCH_POSITION, carousel.index); } }
import React, {useState, useRef} from "react"; import CommonSection from "../components/UI/CommonSection"; import Helmet from '../components/Helmet/Helmet' import {Container, Row, Col} from 'reactstrap' import '../styles/Shop.css' import products from '../assets/data/products' import ProductList from '../components/UI/ProductList' const Shop = () => { // useState method for productsData asset const [productsData, setProductsData] = useState(products) // Refactoring, created a better Handler! // Handler fn for filtered Data const optionHandler = (e) => { e.preventDefault() // Preventing refresh // Setting the filtered products based on the filter applied on products const filteredProducts = products.filter(item => item.category === e.target.value) // update the current state of products data // based on a statement if (filteredProducts) setProductsData(filteredProducts) // If there is not a correct option I manage the current state with array of products if(!filteredProducts) setProductsData(products) } // Handler fn for filtered data with search field const searchInputHandler = (e) => { // Find out what the user write in the field const searchTerm = e.target.value // Sorting products based on what user Search const searchedProducts = products.filter(item => item.productName.toLowerCase().includes(searchTerm.toLowerCase())) // Update the current state setProductsData(searchedProducts) } // Handler fn for filtered Data (Bad Way in my opinion) /* const handleFilter = (e) => { e.preventDefault() // Prevent Default const filterValue = e.target.value // Find out the filtered Value // Statement for the filter Value options if (filterValue === 'sofa') { // Setting the filtered products based on the filter applied on products const filteredProducts = products.filter(item => item.category === 'sofa') // update the current state of products data setProductsData(filteredProducts) } // Statement for the filter Value options if (filterValue === 'mobile') { // Setting the filtered products based on the filter applied on products const filteredProducts = products.filter(item => item.category === 'mobile') // update the current state of products data setProductsData(filteredProducts) } // Statement for the filter Value options if (filterValue === 'chair') { // Setting the filtered products based on the filter applied on products const filteredProducts = products.filter(item => item.category === 'chair') // update the current state of products data setProductsData(filteredProducts) } // Statement for the filter Value options if (filterValue === 'watch') { // Setting the filtered products based on the filter applied on products const filteredProducts = products.filter(item => item.category === 'watch') // update the current state of products data setProductsData(filteredProducts) } // Statement for the filter Value options if (filterValue === 'wireless') { // Setting the filtered products based on the filter applied on products const filteredProducts = products.filter(item => item.category === 'wireless') // update the current state of products data setProductsData(filteredProducts) } } */ return ( /* Shop */ <Helmet title='Shop'> {/* Products */} <CommonSection title='Products' /> {/* Section */} <section> {/* Container */} <Container> {/* Row */} <Row> {/* lg='3' md='6' */} <Col lg='3' md='6'> {/* filter_widget */} <div className="filter_widget"> <select onChange={optionHandler}> <option>Filter By Category</option> <option value="sofa">Sofa</option> <option value="mobile">Mobile</option> <option value="chair">Chair</option> <option value="watch">Watch</option> <option value="wireless">Wireless</option> </select> </div> </Col> {/* lg='3' md='6' */} <Col lg='3' md='6' className="text-end"> {/* filter_widget */} <div className="filter_widget"> <select> <option>Sort By </option> <option value="ascending">Ascending</option> <option value="descending">Descending</option> </select> </div> </Col> {/* lg='6' md='12' */} <Col lg='6' md='12'> {/* search_box */} <div className="search_box"> <input type="text" placeholder="Search" onChange={searchInputHandler} /> {/* ri-search-line */} <span><i className="ri-search-line"></i></span> </div> </Col> </Row> </Container> </section> {/* Product List */} <section className="pt-0"> {/* Container */} <Container> <Row> {/* Products */} { productsData.length === 0 ? ( /* If was true */ <h1 className="text-center fs-4">No products was found!</h1> ) : ( /* If was False */ <ProductList data={productsData} /> ) } </Row> </Container> </section> </Helmet> ); }; export default Shop;
import { TestBed } from '@angular/core/testing'; import { sampleWithRequiredData, sampleWithNewData } from '../organization-member-role.test-samples'; import { OrganizationMemberRoleFormService } from './organization-member-role-form.service'; describe('OrganizationMemberRole Form Service', () => { let service: OrganizationMemberRoleFormService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(OrganizationMemberRoleFormService); }); describe('Service methods', () => { describe('createOrganizationMemberRoleFormGroup', () => { it('should create a new form with FormControl', () => { const formGroup = service.createOrganizationMemberRoleFormGroup(); expect(formGroup.controls).toEqual( expect.objectContaining({ id: expect.any(Object), joinedAt: expect.any(Object), organizationMembership: expect.any(Object), organizationRole: expect.any(Object), }), ); }); it('passing IOrganizationMemberRole should create a new form with FormGroup', () => { const formGroup = service.createOrganizationMemberRoleFormGroup(sampleWithRequiredData); expect(formGroup.controls).toEqual( expect.objectContaining({ id: expect.any(Object), joinedAt: expect.any(Object), organizationMembership: expect.any(Object), organizationRole: expect.any(Object), }), ); }); }); describe('getOrganizationMemberRole', () => { it('should return NewOrganizationMemberRole for default OrganizationMemberRole initial value', () => { const formGroup = service.createOrganizationMemberRoleFormGroup(sampleWithNewData); const organizationMemberRole = service.getOrganizationMemberRole(formGroup) as any; expect(organizationMemberRole).toMatchObject(sampleWithNewData); }); it('should return NewOrganizationMemberRole for empty OrganizationMemberRole initial value', () => { const formGroup = service.createOrganizationMemberRoleFormGroup(); const organizationMemberRole = service.getOrganizationMemberRole(formGroup) as any; expect(organizationMemberRole).toMatchObject({}); }); it('should return IOrganizationMemberRole', () => { const formGroup = service.createOrganizationMemberRoleFormGroup(sampleWithRequiredData); const organizationMemberRole = service.getOrganizationMemberRole(formGroup) as any; expect(organizationMemberRole).toMatchObject(sampleWithRequiredData); }); }); describe('resetForm', () => { it('passing IOrganizationMemberRole should not enable id FormControl', () => { const formGroup = service.createOrganizationMemberRoleFormGroup(); expect(formGroup.controls.id.disabled).toBe(true); service.resetForm(formGroup, sampleWithRequiredData); expect(formGroup.controls.id.disabled).toBe(true); }); it('passing NewOrganizationMemberRole should disable id FormControl', () => { const formGroup = service.createOrganizationMemberRoleFormGroup(sampleWithRequiredData); expect(formGroup.controls.id.disabled).toBe(true); service.resetForm(formGroup, { id: null }); expect(formGroup.controls.id.disabled).toBe(true); }); }); }); });
# LiLi-OM (LIvox LiDAR-Inertial Odometry and Mapping) ## -- Towards High-Performance Solid-State-LiDAR-Inertial Odometry and Mapping This is the code repository of LiLi-OM, a real-time tightly-coupled LiDAR-inertial odometry and mapping system for solid-state LiDAR (Livox Horizon) and conventional LiDARs (e.g., Velodyne). It has two variants as shown in the folder: - LiLi-OM, for [Livox Horizon](https://www.livoxtech.com/de/horizon) with a newly proposed feature extraction module, - LiLi-OM-ROT, for conventional LiDARs of spinning mechanism with feature extraction module similar to [LOAM](https://github.com/HKUST-Aerial-Robotics/A-LOAM). Both variants exploit the same backend module, which is proposed to directly fuse LiDAR and (preintegrated) IMU measurements based on a keyframe-based sliding window optimization. Detailed information can be found in the paper below and on [Youtube](https://www.youtube.com/watch?v=c6K5byDCkyE&feature=youtu.be). <p align='center'> <img src="./doc/fr_iosb.gif" alt="drawing" width="800"/> </p> <p align='center'> <img src="./doc/platform.jpg" alt="drawing" width="600"/> </p> ## BibTex Citation Thank you for citing our LiLi-OM paper on [IEEE](https://ieeexplore.ieee.org/document/9392274) or [ArXiv](https://arxiv.org/abs/2010.13150) if you use any of this code: ``` @article{liliom, author={Li, Kailai and Li, Meng and Hanebeck, Uwe D.}, journal={IEEE Robotics and Automation Letters}, title={Towards High-Performance Solid-State-LiDAR-Inertial Odometry and Mapping}, year={2021}, volume={6}, number={3}, pages={5167-5174}, doi={10.1109/LRA.2021.3070251} } ``` ## Data sets We provide data sets recorded by Livox Horizon (10 Hz) and Xsens MTi-670 (200 Hz) Download from [isas-server](https://isas-server.iar.kit.edu/lidardataset/) ## Dependency System dependencies (tested on Ubuntu 18.04/20.04) - [ROS](http://wiki.ros.org/noetic/Installation) (tested with Melodic/Noetic) - [gtsam](https://gtsam.org/) (GTSAM 4.0) - [ceres](http://ceres-solver.org/installation.html) (Ceres Solver 2.0) In ROS workspce: - [livox_ros_driver (v2.5.0)](https://github.com/Livox-SDK/livox_ros_driver/releases/tag/v2.5.0) (ROS driver for Livox Horizon) ## Compilation Compile with [catkin_tools](https://catkin-tools.readthedocs.io/en/latest/index.html): ``` cd ~/catkin_ws/src git clone https://github.com/KIT-ISAS/lili-om cd .. catkin build livox_ros_driver catkin build lili_om catkin build lili_om_rot ``` ## Usage 1. Run a launch file for lili_om or lili_om_rot 2. Play the bag file - Example for running lili_om (Livox Horizon): ``` roslaunch lili_om run_fr_iosb.launch rosbag play FR_IOSB_Short.bag -r 1.0 --clock --pause ``` - Example for running lili_om_rot (spinning LiDAR like the Velodyne HDL-64E in FR_IOSB data set): ``` roslaunch lili_om_rot run_fr_iosb.launch rosbag play FR_IOSB_Short_64.bag -r 1.0 --clock --pause ``` - Example for running lili_om using the internal IMU of Livox Horizon: ``` roslaunch lili_om run_fr_iosb_internal_imu.launch rosbag play FR_IOSB_Short.bag -r 1.0 --clock --pause --topics /livox/lidar /livox/imu ``` For live test or own recorded data sets, the system should start at a stationary state. ## Contributors Meng Li (Email: [limeng1523@outlook.com](limeng1523@outlook.com)) Kailai Li (Email: [kailai.li@liu.se](kailai.li@liu.se)) [kamibukuro5656](https://github.com/kamibukuro5656) ## Credits We hereby recommend reading [VINS-Fusion](https://github.com/HKUST-Aerial-Robotics/VINS-Fusion) and [LIO-mapping](https://github.com/hyye/lio-mapping) for reference. ## License The source code is released under [GPLv3](http://www.gnu.org/licenses/) license. We are constantly working on improving our code. For any technical issues or commercial use, please contact Kailai Li < kailai.li@kit.edu > with Intelligent Sensor-Actuator-Systems Lab ([ISAS](https://isas.iar.kit.edu/)), Karlsruhe Institute of Technology ([KIT](http://www.kit.edu/english/index.php)).
<?php namespace App\Controllers; use App\Controllers\BaseController; class LoginController extends BaseController { public function index() { return view('auth/index', $this->data); } public function login() { if($this->request->getMethod('POST')) { $data = $this->request->getPost(); $rules = [ 'email' => 'required|valid_email', 'password' => 'required|min_length[6]|max_length[16]' ]; if(!$this->validate($rules)) { $response = [ 'status' => 400, 'error' => true, 'message' => $this->validator->getErrors() ]; } else { $email = $data['email']; $password = $data['password']; $userModel = new \App\Models\UserModel(); $user = $userModel->where('email', $email)->first(); if(!$user) { $response = [ 'status' => 401, 'error' => true, 'message' => 'Usuário não encontrado' ]; } else { if(!password_verify($password, $user['password'])) { $response = [ 'status' => 401, 'error' => true, 'message' => 'Senha incorreta' ]; } else { $SessionData = [ 'id' => $user['id'], 'name' => $user['name'], 'email' => $user['email'], 'isLoggedIn' => true, 'company_id' => $user['company_id'], ]; session()->set($SessionData); $response = [ 'status' => 200, 'error' => false, 'message' => 'Login efetuado com sucesso' ]; } } return $this->response->setJSON($response); } } } public function logout() { session()->destroy(); return redirect()->to(base_url()); } }
#include <iostream> #include <unistd.h> #include <iomanip> using namespace std; void printMainMenu() { system("clear"); cout << "\n\t 1. Regisration"; cout << "\n\t 2. Login"; cout << "\n\t 3. Exit"; } void printSubMenu() { system("clear"); cout << "\n\t 1. Send a message"; cout << "\n\t 2. Read a message"; cout << "\n\t 3. Logout"; } bool isRegistrationAvailable(int nUsers) { if (nUsers != 2) return true; return false; } void askUsernamePassword(string &userEnteredUsername, string &userEnteredPassword) { cout << "\n Enter username: "; cin >> userEnteredUsername; cout << "\n Enter password: "; userEnteredPassword = getpass(""); } void registerUser(string &username, string &password, string &userEnteredUsername, string &userEnteredPassword, int &nUsers) { username = userEnteredUsername; password = userEnteredPassword; nUsers++; } bool login(string &username, string &password, string &userEnteredUsername, string &userEnteredPassword) { if (username == userEnteredUsername && password == userEnteredPassword) { return true; } return false; } void readMessage(string &message, string &username) { if (message != "") { cout << "\n\t Message: " << message; cout << "\n\t Sent by: " << username; } else cout << "\n\t No message in Inbox"; } void pressAnyKey() { cout << "\n\n" << setw(120) << "Press any key to continue..."; getpass(""); } int main() { string username1, password1, message1 = ""; string username2, password2, message2 = ""; int choiceMainMenu = 0, nUsers = 0; printMainMenu(); while (choiceMainMenu != 3) { printMainMenu(); cout << "\n Enter your choice: "; cin >> choiceMainMenu; switch (choiceMainMenu) { case 1: { string userEnteredUsername, userEnteredPassword; if (isRegistrationAvailable(nUsers)) { askUsernamePassword(userEnteredUsername, userEnteredPassword); if (nUsers == 0) { registerUser(username1, password1, userEnteredUsername, userEnteredPassword, nUsers); } else { registerUser(username2, password2, userEnteredUsername, userEnteredPassword, nUsers); } cout << "\n\t\t ***Registration is successfull!!!. Please login"; } else cout << "\n Registration iss closed!!"; break; } case 2: { string userEnteredUsername, userEnteredPassword; askUsernamePassword(userEnteredUsername, userEnteredPassword); int loginId = 0; if (login(username1, password1, userEnteredUsername, userEnteredPassword)) { loginId = 1; } else if (login(username2, password2, userEnteredUsername, userEnteredPassword)) { loginId = 2; } else { cout << "\n\t ***Invalid credentials***"; break; } int choiceSubMenu = 0; while (choiceSubMenu != 3) { printSubMenu(); cout << "\n Enter your choice: "; cin >> choiceSubMenu; switch (choiceSubMenu) { case 1: { string message = ""; cout << "\n\t Enter a message: "; cin >> message; if (loginId == 1) { message2 = message; } else { message1 = message; } } break; case 2: if (loginId == 1) { readMessage(message1, username2); } else { readMessage(message1, username2); } break; case 3: cout << "\n\t Logout Successfull!!!"; break; default: cout << "\n Invalid option"; break; } pressAnyKey(); } break; } case 3: cout << "\n Thanks for using our software!!!"; break; default: cout << "\n Invalid option"; break; } pressAnyKey(); } }
#include <ESP8266WiFi.h> #include <NTPClient.h> #include <WiFiUdp.h> // Replace with your network credentials #define WIFI_SSID "Tahsin" #define WIFI_PASSWORD "Rasel@@@@1988" // Define NTP Client to get time WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org"); // Variable to save current epoch time unsigned long epochTime; // Function that gets current epoch time unsigned long getTime() { timeClient.update(); unsigned long now = timeClient.getEpochTime(); return now; } // Initialize WiFi void initWiFi() { WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("Connecting to WiFi .."); while (WiFi.status() != WL_CONNECTED) { Serial.print('.'); delay(1000); } Serial.println(WiFi.localIP()); } void setup() { Serial.begin(115200); initWiFi(); timeClient.begin(); } void loop() { epochTime = getTime(); Serial.print("Epoch Time: "); Serial.println(epochTime); delay(1000); }
#!/usr/bin/env python # -*- coding: utf-8 -*- """Generate path files for pypaw :copyright: Ridvan Orsvuran (orsvuran@geoazur.unice.fr), 2017 :license: GNU Lesser General Public License, version 3 (LGPLv3) (http://www.gnu.org/licenses/lgpl-3.0.en.html) """ from __future__ import division, absolute_import from __future__ import print_function, unicode_literals import argparse import os import json import yaml class FileOperator(object): """Documentation for FileOperator """ def __init__(self): super(FileOperator, self).__init__() def load_json(self, filename): with open(filename) as f: data = json.load(f) return data def dump_json(self, data, filename): with open(filename, "w") as file_: json.dump(data, file_, indent=2, sort_keys=True) print("{} is written.".format(filename)) def load_yaml(self, filename): with open(filename) as f: data = yaml.safe_load(f) return data def dump_yaml(self, data, filename): with open(filename, "w") as f: data = yaml.safe_dump(data, f, indent=2) return data print("{} is written.".format(filename)) def load_events(self, filename): with open(filename) as f: events = [line.replace("\n", "") for line in f] return events def parse_folder(self, folder, parent): name, data = list(folder.items())[0] paths = {} files = {} if isinstance(data, str): path = data subfolders = [] child_files = [] else: path = data.get("path", name) subfolders = data.get("subfolders", []) child_files = data.get("files", []) paths[name] = os.path.join(parent, path) for child_file in child_files: fname, filepath = list(child_file.items())[0] files[fname] = os.path.join(paths[name], filepath) for subfolder in subfolders: sub_paths, sub_files = self.parse_folder(subfolder, paths[name]) paths.update(sub_paths) files.update(sub_files) return paths, files def load_path_config(self, filename): data = self.load_yaml(filename) root = os.getcwd() folders = {} files = {} for subfolder in data: subfolders, subfiles = self.parse_folder(subfolder, parent=root) folders.update(subfolders) files.update(subfiles) return folders, files def makedir(self, dirname): try: os.makedirs(dirname) except OSError: pass class FileGenerator(FileOperator): """Documentation for FileGenerator """ def __init__(self): super(FileGenerator, self).__init__() self.generators = [] def f(self, name, eventname=None, period_band=None): return self.files[name].format(eventname=eventname, period_band=period_band) def d(self, name, eventname=None, period_band=None): return self.folders[name].format(eventname=eventname, period_band=period_band) def generate_list_events(self): for eventname in self.events: print(eventname) def generate_list_period_bands(self): for period_band in self.settings["period_bands"]: print(period_band) def generate_folders(self): for eventname in self.events: for period_band in self.settings["period_bands"]: for name, path in self.folders.items(): self.makedir(path.format(eventname=eventname, period_band=period_band)) def generate_converter(self): for eventname in self.events: for seis_type in ["obsd_glad", "synt"]: data = { "filetype": "sac", "output_file": self.f("raw_"+seis_type, eventname), "tag": self.settings["raw_{}_tag".format(seis_type)], "quakeml_file": self.f("quakeml", eventname), "staxml_dir": self.d("staxml", eventname), "waveform_dir": self.d("{}_sac".format(seis_type), eventname) } self.dump_json(data, self.f("{}_converter_path".format(seis_type), eventname)) def generate_proc(self): tags=["obsd_1","synt"] for eventname in self.events: for period_band in self.settings["period_bands"]: for j,seis_type in enumerate(["obsd_3D_crust", "synt"]): data = { "input_asdf": self.f("raw_"+seis_type, eventname), "input_tag": self.settings["raw_{}_tag".format(tags[j])], # NOQA "output_asdf": self.f("proc_"+seis_type, eventname, period_band), "output_tag": self.settings["proc_{}_tag".format(tags[j])] # NOQA } self.dump_json(data, self.f("{}_proc_path".format(seis_type), eventname, period_band)) def generate_windows(self): for eventname in self.events: for period_band in self.settings["period_bands"]: data = { "figure_mode": True, "obsd_asdf": self.f("proc_obsd", eventname, period_band), "obsd_tag": self.settings["proc_obsd_tag"], "output_file": self.f("windows_file", eventname, period_band), # NOQA "synt_asdf": self.f("proc_synt", eventname, period_band), "synt_tag": self.settings["proc_synt_tag"] } self.dump_json(data, self.f("window_path", eventname, period_band)) def generate_measure(self): for eventname in self.events: for period_band in self.settings["period_bands"]: data = { "figure_dir": self.d("measure_figures"), "figure_mode": True, "obsd_asdf": self.f("proc_obsd", eventname, period_band), "obsd_tag": self.settings["proc_obsd_tag"], "output_file": self.f("measure_file", eventname, period_band), # NOQA "synt_asdf": self.f("proc_synt", eventname, period_band), "synt_tag": self.settings["proc_synt_tag"], "window_file": self.f("windows_file", eventname, period_band) # NOQA } self.dump_json(data, self.f("measure_path", eventname, period_band)) def generate_stations(self): for eventname in self.events: data = { "input_asdf": self.f("raw_synt", eventname), "outputfile": self.f("stations_file", eventname), } self.dump_json(data, self.f("stations_path", eventname)) def generate_filter(self): for eventname in self.events: for period_band in self.settings["period_bands"]: data = { "measurement_file": self.f("measure_file", eventname, period_band), # NOQA "output_file": self.f("windows_filter_file", eventname, period_band), # NOQA "station_file": self.f("stations_file", eventname), "window_file": self.f("windows_file", eventname, period_band) # NOQA } self.dump_json(data, self.f("filter_path", eventname, period_band)) def generate_adjoint(self): for eventname in self.events: for period_band in self.settings["period_bands"]: data = { "figure_dir": self.d("adjoint_figures"), "figure_mode": False, "obsd_asdf": self.f("proc_obsd", eventname, period_band), "obsd_tag": self.settings["proc_obsd_tag"], "output_file": self.f("adjoint_file", eventname, period_band), # NOQA "synt_asdf": self.f("proc_synt", eventname, period_band), "synt_tag": self.settings["proc_synt_tag"], "window_file": self.f("windows_filter_file", eventname, period_band) # NOQA } self.dump_json(data, self.f("adjoint_path", eventname, period_band)) def count_windows(self, eventname): measurements = {} for period_band in self.settings["period_bands"]: windows_file = self.f("windows_filter_file", eventname, period_band) # NOQA windows_data = self.load_json(windows_file) measurements[period_band] = dict((x, 0) for x in ["BHR", "BHT", "BHZ"]) # NOQA for station, components in windows_data.items(): for component, windows in components.items(): c = component.split(".")[-1] measurements[period_band][c] += len(windows) return measurements def get_ratio(self, eventname): counts = self.count_windows(eventname) for p in counts: for c in counts[p]: counts[p][c] = 1 / counts[p][c] return counts def generate_weight_params(self): template = self.load_yaml(self.f("weight_template")) for eventname in self.events: ratio = self.get_ratio(eventname) data = template.copy() data["category_weighting"]["ratio"] = ratio self.dump_yaml(data, self.f("weight_parfile", eventname)) def generate_weight_paths(self): for eventname in self.events: data = {"input": {}, "logfile": self.f("weight_log", eventname)} for period_band in self.settings["period_bands"]: data["input"][period_band] = { "asdf_file": self.f("proc_synt", eventname, period_band), "output_file": self.f("weight_file", eventname, period_band), # NOQA "station_file": self.f("stations_file", eventname), "window_file": self.f("windows_filter_file", eventname, period_band) # NOQA } self.dump_json(data, self.f("weight_path", eventname)) def generate_sum(self): for eventname in self.events: data = {"input_file": {}, "output_file": self.f("sum_adjoint_file", eventname)} for period_band in self.settings["period_bands"]: data["input_file"][period_band] = { "asdf_file": self.f("adjoint_file", eventname, period_band), # NOQA "weight_file": self.f("weight_file", eventname, period_band), # NOQA } self.dump_json(data, self.f("sum_adjoint_path", eventname)) def run(self): steps = dict([(x[9:], x) for x in dir(self) if x.startswith('generate_')]) parser = argparse.ArgumentParser( description='Generate path files') parser.add_argument('-p', '--paths-file', default="paths.yml") parser.add_argument('-s', '--settings-file', default="settings.yml") parser.add_argument('-e', '--events-file', default="event_list") parser.add_argument("step", help="file to generate", choices=steps.keys()) args = parser.parse_args() self.folders, self.files = self.load_path_config(args.paths_file) self.settings = self.load_yaml(args.settings_file) self.events = self.load_events(args.events_file) getattr(self, steps[args.step])() if __name__ == '__main__': FileGenerator().run()
import { Container, Brand, Menu, Search, Content, NewNote } from "./styles"; import { FiPlus, FiSearch } from "react-icons/fi"; import { Header } from "../../components/Header/index"; import { ButtonText } from "../../components/ButtonText/index"; import { Input } from "../../components/Input"; import { Section } from "../../components/Section"; import { Note } from "../../components/Note"; export function Home() { return ( <Container> <Brand> <h1>Rocketnotes</h1> </Brand> <Header /> <Menu> <li> <ButtonText title="Todos" isActive /> </li> <li> <ButtonText title="Next" /> </li> <li> <ButtonText title="Nodejs" /> </li> </Menu> <Search> <Input placeholder="Pesquisar pelo título" icon={FiSearch} /> </Search> <Content> <Section title="Minhas notas"> <Note data={{ title: "React", tags: [ { id: "1", name: "react" }, { id: "2", name: "rocketseat" }, ], }} /> <Note data={{ title: "React", tags: [ { id: "1", name: "react" }, { id: "2", name: "rocketseat" }, ], }} /> </Section> </Content> <NewNote> <FiPlus /> Criar nota </NewNote> </Container> ); }
import { NextFunction, Response } from 'express'; import { AuthRequest } from '@/interfaces/routes.interface'; import { ApplyJobDto, DetermineJobDto, InterviewDto, JobOfferDto } from '@/dtos/jobs.dto'; import JobsService from '@/services/jobs.service'; import { DIRECTOR, WORKER } from '@/utils/userTypes'; class JobsController { public jobsService = new JobsService(); public createJobOffer = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => { try { const jobOfferData: JobOfferDto = req.body; const jobOffer = await this.jobsService.createJobOffer(jobOfferData, req.cf); res.status(200).json({ message: `Nuova offerta di lavoro creata`, jobOffer }); } catch (error) { next(error); } }; public updateJobOffer = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => { try { const jobOfferData: JobOfferDto = req.body; const jobOfferId = Number(req.params.offerId); const jobOffer = await this.jobsService.updateJobOffer(jobOfferData, jobOfferId); res.status(200).json({ message: `Offerta di lavoro aggiornata`, jobOffer }); } catch (error) { next(error); } }; public getJobOffers = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => { try { const skip = Number(req.params.skip); const jobOffers = req.tipoUtenteId === WORKER ? await this.jobsService.getWorkerJobOffers(req.cf, skip) : req.tipoUtenteId === DIRECTOR ? await this.jobsService.getDirectorJobOffers(skip) : await this.jobsService.getStructureJobOffers(req.cf, skip); res.status(200).json(jobOffers); } catch (error) { next(error); } }; public getActiveJobs = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => { try { const skip = Number(req.params.skip); const jobOffers = await this.jobsService.getDirectorActiveJobs(skip); res.status(200).json(jobOffers); } catch (error) { next(error); } }; public removeJobOffer = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => { try { const jobOfferId = Number(req.params.offerId); const jobOffer = await this.jobsService.removeJobOffer(req.cf, jobOfferId); res.status(200).json({ message: `Offerta di lavoro rimossa`, jobOffer }); } catch (error) { next(error); } }; public applyToJobOffer = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => { try { const applyJobData: ApplyJobDto = req.body; await this.jobsService.applyToJobOffer(req.cf, applyJobData); res.status(200).json({ message: `Candidatura inviata`, success: true }); } catch (error) { next(error); } }; public closeOffer = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => { try { const jobOfferId = Number(req.params.offerId); const applicationId = req.params?.applicationId ? Number(req.params.applicationId) : null; await this.jobsService.closeOffer(jobOfferId, applicationId && applicationId); res.status(200).json({ message: `${applicationId ? 'Candidatura accettata.' : ''} Offerta lavorativa chiusa`, success: true }); } catch (error) { next(error); } }; public determineJob = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => { try { const determineJobData: DetermineJobDto = req.body; await this.jobsService.determineJob(determineJobData, req.cf); res.status(200).json({ message: `Offerta di lavoro ${determineJobData.approved ? 'approvata' : 'non approvata'}`, success: true }); } catch (error) { next(error); } }; public getJobsHistory = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => { try { const skip = Number(req.params.skip); const jobsHistory = req.tipoUtenteId === WORKER ? await this.jobsService.getWorkerJobsHistory(req.cf, skip) : req.tipoUtenteId === DIRECTOR ? await this.jobsService.getDirectorJobsHistory(skip) : await this.jobsService.getStructureJobHistory(req.cf, skip); res.status(200).json(jobsHistory); } catch (error) { next(error); } }; public withdrawApplication = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => { try { const applicationId = Number(req.params.applicationId); await this.jobsService.withdrawApplication(applicationId); res.status(200).json({ message: 'Candidatura annullata', success: true }); } catch (error) { next(error); } }; public sendInterviewInvite = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => { try { const interviewData: InterviewDto = req.body; const candidaturas = await this.jobsService.sendInterviewInvite(interviewData); res.status(200).json({ message: 'Inviti al colloquio inviati', candidaturas }); } catch (error) { next(error); } }; public suggestCandidate = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => { try { const applicationId = Number(req.params.applicationId); await this.jobsService.suggestCandidate(applicationId); res.status(200).json({ message: `Candidato proposto`, success: true }); } catch (error) { next(error); } }; } export default JobsController;
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <title>Agregar Movimiento</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <style> a{ color:white; } a:hover{ color: darkgrey; text-decoration: none; } </style> </head> <body> <div class="container"> <h1> Agregue aqui los datos del Movimiento</h1> <br> <!--Crear formulario para llenar los datos del movimiento y guardarlo en el objeto mov --> <form th:action="@{/GuardarMovimiento}" th:object="${mov}" method="post"> <!--Campo para Concepto--> <div class="row"> <div class="form-group col-md-12"> <label class="col-md-3" for="concepto">Concepto del Movimiento:</label> <div class="col-md-4"> <input type="text" th:field="*{concepto}" class="form-control" id="concepto" required="required"> </div> </div> </div> <!--Campo para monto--> <div class="row"> <div class="form-group col-md-12"> <label class="col-md-3" for="monto">Valor del movimiento:</label> <div class="col-md-4"> <input type="number" th:field="*{monto}" class="form-control" id="monto" required="required"> </div> </div> </div> <!--Campo para empleado (usuario responsable)--> <div class="row"> <div class="form-group col-md-12"> <label class="col-md-3" for="empleado">Empleado responsable:</label> <div class="col-md-4"> <select th:field="*{empleado}" class="form-control" id="empleado" required="required" > <option th:each="empleado : ${emplelist}" th:text="${empleado.nombre}" th:value="${empleado.id}"></option> </select> </div> </div> </div> <!--Boton para enviar todo y ejecutar accion --> <div class="row"> <div class="col-md-2"> <button class="btn btn-success">Registrar Movimiento</button> </div> </div> </form> <br> <a href="javascript: history.go(-1)" class="btn btn-info" role="button">Atrás</a> </div> <script th:inline="javascript"> window.onload=function(){ document.getElementById("fecha").value=new Date().toJSON().slice(0,10).replace(/-/g,'-'); } </script> </body> </html>
using ECOM.Web.Models; using ECOM.Web.Services.IService; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System.Diagnostics; using System.IdentityModel.Tokens.Jwt; namespace ECOM.Web.Controllers; public class HomeController : Controller { private readonly IProductService _productService; private readonly IShoppingCartService _shoppingCartService; public HomeController(IProductService productService, IShoppingCartService shoppingCartService) { _productService = productService; _shoppingCartService = shoppingCartService; } public async Task<IActionResult> Index() { List<ProductDTO> productDTOList = new(); ResponseDTO? response = await _productService.GetAllProductsAsync(); if (response != null && response.IsSuccess) { productDTOList = JsonConvert.DeserializeObject<List<ProductDTO>>(Convert.ToString(response.Result)); } else { TempData["error"] = response?.Message; } return View(productDTOList); } [Authorize] public async Task<IActionResult> Details(int productId) { var product = new ProductDTO(); ResponseDTO? response = await _productService.GetProductByIDAsync(productId); if (response != null && response.IsSuccess) { product = JsonConvert.DeserializeObject<ProductDTO>(Convert.ToString(response.Result)); } else { TempData["error"] = response?.Message; } return View(product); } [Authorize] [HttpPost] public async Task<IActionResult> Details(ProductDTO product) { ShoppingCartDTO shoppingCart = new ShoppingCartDTO() { CartHeader = new CartHeaderDTO() { UserID = User.Claims.FirstOrDefault(u => u.Type == JwtRegisteredClaimNames.Sub)?.Value, CartHeaderID = 0 }, CartDetails = new List<CartDetailDTO>() { new CartDetailDTO() { Count = product.Count, ProductID = product.ProductId } } }; var response = await _shoppingCartService.CartUpsertAsync(shoppingCart); if (response != null && response.IsSuccess) { TempData["success"] = "Item has been added to the shopping cart"; return RedirectToAction(nameof(Index)); } else { TempData["error"] = response?.Message; } return View(product); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current.Id ?? HttpContext.TraceIdentifier }); } }
/* * Copyright (C) 2000-2013 The Exult Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <cstring> #include "files/U7file.h" #include "palette.h" #include "ibuf8.h" #include "utils.h" #include "fnames.h" #include "gamewin.h" #include "exceptions.h" #include "ignore_unused_variable_warning.h" #include "SDL_timer.h" using std::memcpy; using std::memset; using std::size_t; using std::string; unsigned char Palette::border[3] = { 0, 0, 0 }; Palette::Palette() : win(Game_window::get_instance()->get_win()), palette(-1), brightness(100), max_val(63), border255(false), faded_out(false), fades_enabled(true) { memset(pal1, 0, 768); memset(pal2, 0, 768); } Palette::Palette(Palette *pal) : win(Game_window::get_instance()->get_win()), max_val(63) { take(pal); } void Palette::take(Palette *pal) { palette = pal->palette; brightness = pal->brightness; faded_out = pal->faded_out; fades_enabled = pal->fades_enabled; memcpy(pal1, pal->pal1, 768); memcpy(pal2, pal->pal2, 768); } Palette::~Palette() { } /* * Fade the current palette in or out. * Note: If pal_num != -1, the current palette is set to it. */ void Palette::fade( int cycles, // Length of fade. int inout, // 1 to fade in, 0 to fade to black. int pal_num // 0-11, or -1 for current. ) { if (pal_num == -1) pal_num = palette; palette = pal_num; border255 = (palette >= 0 && palette <= 12) && palette != 9; load(PALETTES_FLX, PATCH_PALETTES, pal_num); if (inout) fade_in(cycles); else fade_out(cycles); faded_out = !inout; // Be sure to set flag. } /* * Flash the current palette red. */ void Palette::flash_red( ) { int savepal = palette; set(PALETTE_RED); // Palette 8 is the red one. win->show(); SDL_Delay(100); set(savepal); Game_window::get_instance()->set_painted(); } /* * Read in a palette. */ void Palette::set( int pal_num, // 0-11, or -1 to leave unchanged. int new_brightness, // New percentage, or -1. bool repaint ) { border255 = (pal_num >= 0 && pal_num <= 12) && pal_num != 9; if ((palette == pal_num || pal_num == -1) && (brightness == new_brightness || new_brightness == -1)) // Already set. return; if (pal_num != -1) palette = pal_num; // Store #. if (new_brightness > 0) brightness = new_brightness; if (faded_out) return; // In the black. // could throw! load(PALETTES_FLX, PATCH_PALETTES, palette); set_brightness(brightness); apply(repaint); } /* * Read in a palette. */ void Palette::set( unsigned char palnew[768], int new_brightness, // New percentage, or -1. bool repaint, bool border255 ) { this->border255 = border255; memcpy(pal1, palnew, 768); memset(pal2, 0, 768); palette = -1; if (new_brightness > 0) brightness = new_brightness; if (faded_out) return; // In the black. set_brightness(brightness); apply(repaint); } void Palette::apply(bool repaint) { uint8 r = pal1[255 * 3 + 0]; uint8 g = pal1[255 * 3 + 1]; uint8 b = pal1[255 * 3 + 2]; if (border255) { pal1[255 * 3 + 0] = border[0] * 63 / 255; pal1[255 * 3 + 1] = border[1] * 63 / 255; pal1[255 * 3 + 2] = border[2] * 63 / 255; } win->set_palette(pal1, max_val, brightness); pal1[255 * 3 + 0] = r; pal1[255 * 3 + 1] = g; pal1[255 * 3 + 2] = b; if (!repaint) return; if (!Set_glpalette()) win->show(); } /** * Loads and a xform table and sets palette from a buffer. * @param buf What to base palette on. * @param xfname xform file name. * @param xindex xform index. */ void Palette::loadxform(const char *buf, const char *xfname, int &xindex) { U7object xform(xfname, xindex); size_t xlen; unsigned char *xbuf = reinterpret_cast<unsigned char *>(xform.retrieve(xlen)); if (!xbuf || xlen <= 0) xindex = -1; else for (int i = 0; i < 256; i++) { int ix = xbuf[i]; pal1[3 * i] = buf[3 * ix]; pal1[3 * i + 1] = buf[3 * ix + 1]; pal1[3 * i + 2] = buf[3 * ix + 2]; } delete [] xbuf; } /** * Actually loads and sets the palette and xform table. * @param pal What is being loaded. * @param xfname xform file name. * @param xindex xform index. */ void Palette::set_loaded( const U7multiobject &pal, const char *xfname, int xindex ) { size_t len; char *buf = pal.retrieve(len); if (len == 768) { // Simple palette if (xindex >= 0) // Get xform table. loadxform(buf, xfname, xindex); if (xindex < 0) // Set the first palette memcpy(pal1, buf, 768); // The second one is black. memset(pal2, 0, 768); } else if (buf && len > 0) { // Double palette for (int i = 0; i < 768; i++) { pal1[i] = buf[i * 2]; pal2[i] = buf[i * 2 + 1]; } } else { // Something went wrong during palette load. This probably // happens because a dev is being used, which means that // the palette won't be loaded. // For now, let's try to avoid overwriting any palette that // may be loaded and just cleanup. delete [] buf; return; } Set_glpalette(this); delete [] buf; } /** * Loads a palette from the given spec. Optionally loads a * xform from the desired file. * @param fname0 Specification of pallete to load. * @param index Index of the palette. * @param xfname Optional xform file name. * @param xindex Optional xform index. */ void Palette::load( const File_spec &fname0, int index, const char *xfname, int xindex ) { U7multiobject pal(fname0, index); set_loaded(pal, xfname, xindex); } /** * Loads a palette from the given spec. Optionally loads a * xform from the desired file. * @param fname0 Specification of first pallete to load (likely <STATIC>). * @param fname1 Specification of second pallete to load (likely <PATCH>). * @param index Index of the palette. * @param xfname Optional xform file name. * @param xindex Optional xform index. */ void Palette::load( const File_spec &fname0, const File_spec &fname1, int index, const char *xfname, int xindex ) { U7multiobject pal(fname0, fname1, index); set_loaded(pal, xfname, xindex); } /** * Loads a palette from the given spec. Optionally loads a * xform from the desired file. * @param fname0 Specification of first pallete to load (likely <STATIC>). * @param fname1 Specification of second pallete to load. * @param fname2 Specification of third pallete to load (likely <PATCH>). * @param index Index of the palette. * @param xfname Optional xform file name. * @param xindex Optional xform index. */ void Palette::load( const File_spec &fname0, const File_spec &fname1, const File_spec &fname2, int index, const char *xfname, int xindex ) { U7multiobject pal(fname0, fname1, fname2, index); set_loaded(pal, xfname, xindex); } void Palette::set_brightness(int bright) { brightness = bright; } #ifdef HAVE_OPENGL static inline void glfade( Image_window *win, int cycles, bool fadein, unsigned char *pal1, unsigned char *pal2, int max_val, int brightness ) { #if 1 ignore_unused_variable_warning(cycles); win->set_palette(fadein ? pal1 : pal2, max_val, brightness); win->show(); #else // FIXME: For some reason, this doesn't work always. I have no idea why. int scale = win->get_scale(); int width = win->get_width(), height = win->get_height(); int w = width * scale, h = height * scale; unsigned char *rgba_pixels = GL_manager::get_instance()->get_screen_rgba( width, height); win->set_palette(fadein ? pal1 : pal2, max_val, brightness); unsigned char *fade_blend = new unsigned char[4 * w * h]; //std::memset(fade_blend, 0, 4*w*h); unsigned int ticks = SDL_GetTicks() + 20; cycles >>= 2; for (int i = 0; i <= cycles; i++) { //int alpha = fadein ? 255 - ((255*i)/cycles) : (255*i)/cycles; int from = fadein ? i : cycles - i; for (int j = 0; j < w * h; j++) { for (int k = 0; k < 3; k++) fade_blend[4 * j + k] = (from * rgba_pixels[4 * j + k]) / cycles; fade_blend[4 * j + 3] = rgba_pixels[4 * j + 3]; //fade_blend[4*j+3] = alpha; } //gl_paint_rgba_bitmap(rgba_pixels, 0, 0, w, h, 1); gl_paint_rgba_bitmap(fade_blend , 0, 0, w, h, 1); while (ticks >= SDL_GetTicks()) ; win->show(); ticks += 20; } delete [] rgba_pixels; delete [] fade_blend; #endif } #endif void Palette::fade_in(int cycles) { if (cycles && fades_enabled) { #ifdef HAVE_OPENGL if (GL_manager::get_instance()) { glfade(win, cycles, true, pal1, pal2, max_val, brightness); return; } #endif unsigned char fade_pal[768]; unsigned int ticks = SDL_GetTicks() + 20; for (int i = 0; i <= cycles; i++) { uint8 r = pal1[255 * 3 + 0]; uint8 g = pal1[255 * 3 + 1]; uint8 b = pal1[255 * 3 + 2]; if (border255) { pal1[255 * 3 + 0] = border[0] * 63 / 255; pal1[255 * 3 + 1] = border[1] * 63 / 255; pal1[255 * 3 + 2] = border[2] * 63 / 255; } for (int c = 0; c < 768; c++) fade_pal[c] = ((pal1[c] - pal2[c]) * i) / cycles + pal2[c]; pal1[255 * 3 + 0] = r; pal1[255 * 3 + 1] = g; pal1[255 * 3 + 2] = b; win->set_palette(fade_pal, max_val, brightness); // Frame skipping on slow systems if (i == cycles || ticks >= SDL_GetTicks() || !Game_window::get_instance()->get_frame_skipping()) win->show(); while (ticks >= SDL_GetTicks()) ; ticks += 20; } } else { uint8 r = pal1[255 * 3 + 0]; uint8 g = pal1[255 * 3 + 1]; uint8 b = pal1[255 * 3 + 2]; if ((palette >= 0 && palette <= 12) && palette != 9) { pal1[255 * 3 + 0] = border[0] * 63 / 255; pal1[255 * 3 + 1] = border[1] * 63 / 255; pal1[255 * 3 + 2] = border[2] * 63 / 255; } win->set_palette(pal1, max_val, brightness); pal1[255 * 3 + 0] = r; pal1[255 * 3 + 1] = g; pal1[255 * 3 + 2] = b; win->show(); } } void Palette::fade_out(int cycles) { faded_out = true; // Be sure to set flag. if (cycles && fades_enabled) { #ifdef HAVE_OPENGL if (GL_manager::get_instance()) { glfade(win, cycles, false, pal1, pal2, max_val, brightness); return; } #endif unsigned char fade_pal[768]; unsigned int ticks = SDL_GetTicks() + 20; for (int i = cycles; i >= 0; i--) { uint8 r = pal1[255 * 3 + 0]; uint8 g = pal1[255 * 3 + 1]; uint8 b = pal1[255 * 3 + 2]; if (border255) { pal1[255 * 3 + 0] = border[0] * 63 / 255; pal1[255 * 3 + 1] = border[1] * 63 / 255; pal1[255 * 3 + 2] = border[2] * 63 / 255; } for (int c = 0; c < 768; c++) fade_pal[c] = ((pal1[c] - pal2[c]) * i) / cycles + pal2[c]; pal1[255 * 3 + 0] = r; pal1[255 * 3 + 1] = g; pal1[255 * 3 + 2] = b; win->set_palette(fade_pal, max_val, brightness); // Frame skipping on slow systems if (i == 0 || ticks >= SDL_GetTicks() || !Game_window::get_instance()->get_frame_skipping()) win->show(); while (ticks >= SDL_GetTicks()) ; ticks += 20; } } else { win->set_palette(pal2, max_val, brightness); win->show(); } //Messes up sleep. win->set_palette(pal1, max_val, brightness); } // Find index (0-255) of closest color (r,g,b < 64). int Palette::find_color(int r, int g, int b, int last) { int best_index = -1; long best_distance = 0xfffffff; // But don't search rotating colors. for (int i = 0; i < last; i++) { // Get deltas. long dr = r - pal1[3 * i], dg = g - pal1[3 * i + 1], db = b - pal1[3 * i + 2]; // Figure distance-squared. long dist = dr * dr + dg * dg + db * db; if (dist < best_distance) { // Better than prev? best_index = i; best_distance = dist; } } return best_index; } /* * Creates a translation table between two palettes. */ void Palette::create_palette_map(Palette *to, unsigned char *&buf) { // Assume buf has 256 elements for (int i = 0; i < 256; i++) buf[i] = to->find_color(pal1[3 * i], pal1[3 * i + 1], pal1[3 * i + 2], 256); } /* * Creates a palette in-between two palettes. */ Palette *Palette::create_intermediate(Palette *to, int nsteps, int pos) { unsigned char palnew[768]; if (fades_enabled) { for (int c = 0; c < 768; c++) palnew[c] = ((to->pal1[c] - pal1[c]) * pos) / nsteps + pal1[c]; } else { unsigned char *palold; if (2 * pos >= nsteps) palold = to->pal1; else palold = pal1; memcpy(palnew, palold, 768); } Palette *ret = new Palette(); ret->set(palnew, -1, true, true); return ret; } /* * Create a translucency table for this palette seen through a given * color. (Based on a www.gamedev.net article by Jesse Towner.) */ void Palette::create_trans_table( // Color to blend with: unsigned char br, unsigned bg, unsigned bb, int alpha, // 0-255, applied to 'blend' color. unsigned char *table // 256 indices are stored here. ) { for (int i = 0; i < 256; i++) { int newr = (static_cast<int>(br) * alpha) / 255 + (static_cast<int>(pal1[i * 3]) * (255 - alpha)) / 255; int newg = (static_cast<int>(bg) * alpha) / 255 + (static_cast<int>(pal1[i * 3 + 1]) * (255 - alpha)) / 255; int newb = (static_cast<int>(bb) * alpha) / 255 + (static_cast<int>(pal1[i * 3 + 2]) * (255 - alpha)) / 255; table[i] = find_color(newr, newg, newb); } } void Palette::show() { for (int x = 0; x < 16; x++) { for (int y = 0; y < 16; y++) { win->fill8(y * 16 + x, 8, 8, x * 8, y * 8); } } } void Palette::set_color(int nr, int r, int g, int b) { pal1[nr * 3] = r; pal1[nr * 3 + 1] = g; pal1[nr * 3 + 2] = b; } void Palette::set_palette(unsigned char palnew[768]) { memcpy(pal1, palnew, 768); memset(pal2, 0, 768); } void Palette::set_max_val(int max) { max_val = max; } int Palette::get_max_val() { return max_val; } Palette_transition::Palette_transition( int from, int to, int ch, int cm, int r, int nsteps, int sh, int smin ) : current(0), step(0), max_steps(nsteps), start_hour(sh), start_minute(smin), rate(r) { start = new Palette(); start->load(PALETTES_FLX, PATCH_PALETTES, from); end = new Palette(); end->load(PALETTES_FLX, PATCH_PALETTES, to); set_step(ch, cm); } Palette_transition::Palette_transition( Palette *from, int to, int ch, int cm, int r, int nsteps, int sh, int smin ) : current(0), step(0), max_steps(nsteps), start_hour(sh), start_minute(smin), rate(r) { start = new Palette(from); end = new Palette(); end->load(PALETTES_FLX, PATCH_PALETTES, to); set_step(ch, cm); } Palette_transition::Palette_transition( Palette *from, Palette *to, int ch, int cm, int r, int nsteps, int sh, int smin ) : current(0), step(0), max_steps(nsteps), start_hour(sh), start_minute(smin), rate(r) { start = new Palette(from); end = new Palette(to); set_step(ch, cm); } bool Palette_transition::set_step(int hour, int min) { int new_step = 60 * (hour - start_hour) + min - start_minute; while (new_step < 0) new_step += 60; new_step /= rate; Game_window *gwin = Game_window::get_instance(); if (gwin->get_pal()->is_faded_out()) return false; if (!current || new_step != step) { step = new_step; delete current; current = start->create_intermediate(end, max_steps, step); } if (current) current->apply(true); if (step >= max_steps) return false; else return true; } Palette_transition::~Palette_transition( ) { delete start; delete end; delete current; }
# 이 함수는 주어진 보드의 특정 위치에 숫자를 배치할 수 있는지 여부를 확인 # 1. 해당 숫자가 이미 같은 행에 있는지. # 2. 해당 숫자가 이미 같은 열에 있는지. # 3. 해당 숫자가 현재 위치의 3x3 박스 내에 있는지. import json def is_valid(board, row, col, num): # Check if num is present in the specified row for x in range(9): if board[row][x] == num: return False # Check if num is present in the specified column for x in range(9): if board[x][col] == num: return False # Check if num is present in the specified 3x3 box startRow, startCol = 3 * (row // 3), 3 * (col // 3) for i in range(3): for j in range(3): if board[i + startRow][j + startCol] == num: return False return True # 이 함수는 재귀적으로 스도쿠 보드를 풉니다. # 먼저, find_empty_location 함수를 사용하여 보드 상에서 빈 위치를 찾습니다. # 빈 위치가 없다면 모든 칸이 채워진 것이므로 보드는 해결되었습니다. # 빈 위치가 있다면, 해당 위치에 1부터 9까지의 숫자를 하나씩 시도해 봅니다. # 만약 숫자가 해당 위치에 배치될 수 있다면 (is_valid 함수를 사용하여 확인), 해당 숫자를 배치하고 다음 빈 칸을 해결하기 위해 재귀적으로 solve_sudoku 함수를 호출합니다. # 만약 이후의 칸들을 해결하는 데 실패한다면, 현재 칸의 숫자를 다시 0으로 바꾸어 초기화하고 (이것이 "백트래킹"입니다) 다른 숫자를 시도합니다. def solve_sudoku(board): empty = find_empty_location(board) if not empty: return True row, col = empty for num in map(str, range(1, 10)): if is_valid(board, row, col, num): board[row][col] = num if solve_sudoku(board): return True board[row][col] = '0' # backtrack return False # 보드에서 값이 '0'인 첫 번째 위치를 반환합니다. 만약 모든 칸이 채워져 있다면 None을 반환합니다. def find_empty_location(board): for i in range(len(board)): for j in range(len(board[i])): if board[i][j] == '0': return i, j return None # 이 두 함수는 주어진 스도쿠 문자열과 2D 리스트 형태의 보드 사이에서 변환을 수행합니다. def string_to_board(s): return [list(s[i:i+9]) for i in range(0, 81, 9)] def board_to_string(board): return ''.join(''.join(row) for row in board) def get_easy_response_api(driver): logs = driver.get_log('performance') for entry in logs: log = json.loads(entry['message'])['message'] if 'response' in log['params']: if log['method'] == 'Network.responseReceived' and log['params']['response'][ 'url'] == 'https://sudoku.com/api/level/easy': request_id = log['params']['requestId'] # Network.getResponseBody를 사용하여 응답 본문 가져오기 response_body = driver.execute_cdp_cmd("Network.getResponseBody", {"requestId": request_id}) # 응답 본문 변환 json_data = json.loads(response_body['body']) return json_data
import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { UsersModule } from './users/users.module'; import { AuthModule } from './auth/auth.module'; import { ConfigModule } from '@nestjs/config'; import { join } from 'path'; import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo'; import { MongooseModule } from '@nestjs/mongoose'; import { DonationsModule } from './donations/donations.module'; @Module({ imports: [ ConfigModule.forRoot(), MongooseModule.forRoot(process.env.MONGO_URI), GraphQLModule.forRoot<ApolloDriverConfig>({ driver: ApolloDriver, autoSchemaFile: join(process.cwd(), 'src/utils/graphql/schema.gql'), sortSchema: true, playground: true, debug: false, }), UsersModule, AuthModule, DonationsModule, ], controllers: [], providers: [], }) export class AppModule {}
Either / Neither = Tampoco > **Either**: Pronombre + Auxiliar `-` / to be `-` / v. modal `-` + Either > **Neither**: Neither + Auxiliar `+` / to be `+` / v. modal `+` + Pronombre > Nombre + Neither > Pronombre objeto + Neither > Sujeto + Neither ### Examples: A. I wouldn't go with them. B. I wouldn't `either`. Yo tampoco. B. `Neither` would I. B. Me `neither`. A. They shouldn't drink alcohol. B. We shouldn't `either`. Nosotros tampoco. B. `Neither` should we. B. Us `neither`. A. Griselda isn't in her house. B. Her mother isn't `either`. B. `Neither` is her mother. B. Her mother `neither`. A. I don't like onion. B. My wife doesn't `either`. A mi esposa tampoco. B. `Neither` does my wife. B. My wife `neither`. ### 🔥 Practice: 1. John is not saving money. (We / neither) - Neither are we. - Us neither. 2. She couldn't help me. (I / either) - I couldn't either. - Me neither. 3. I can't believe it. (They / neither) - Neither can They. - Them neither. 4. Claudia doesn't love you. (Juan / either) - Juan doesn't either. - Juan neither. ### Vocabulary - Onion: cebolla - Heights: alturas - Maths: matemáticas - Place: lugar - Present: regalo - Cousin: primo - Afraid: asustado - Smoke: fumar - Alone: solo(a) - Husband: esposo - Behave: comportarse - Movie: película ### Explicación de EITHER y NEITHER "Either" y "neither" son palabras que se usan para expresar negación en inglés. - "Either" se utiliza para indicar que una de dos opciones es verdadera o posible. Ejemplo: "I can either go to the movies or stay home tonight" (Puedo ir al cine o quedarme en casa esta noche). - "Neither" se utiliza para indicar que ninguna de las dos opciones es verdadera o posible. Ejemplo: "Neither of us likes broccoli" (A ninguno de los dos nos gusta el brócoli). En cuanto a su uso para expresar "tampoco", se utilizan de la siguiente manera: - "Either" se utiliza en una oración negativa para expresar que la otra persona tampoco lo hizo o no quiere hacer algo. Ejemplo: "I didn't go to the party last night, and she didn't either" (No fui a la fiesta anoche, y ella tampoco). - "Neither" se utiliza en una oración afirmativa para expresar que uno también está de acuerdo en no hacer algo o no tener algo. Ejemplo: "I don't like coffee, and neither does my friend" (No me gusta el café y a mi amigo tampoco). [Clase en YouTube](https://www.youtube.com/watch?v=zTX22ZUZoJk&list=PLgrNDDl9MxYmUmf19zPiljdg8FKIRmP78&index=43) [Clase en la Web + Guía práctica](https://www.pacho8a.com/ingl%C3%A9s/curso-ingl%C3%A9s-nivel-b%C3%A1sico/lecci%C3%B3n-38/)
import React from 'react'; import './Header.css'; import SearchIcon from '@material-ui/icons/Search'; import logo from './images/logo.png'; import HeaderOption from './HeaderOption'; import HomeIcon from '@material-ui/icons/Home'; import ChatIcon from '@material-ui/icons/Chat'; import NotificationsIcon from '@material-ui/icons/Notifications'; import { useDispatch } from 'react-redux'; import { auth } from './firebase'; import { logout } from './features/userSlice'; function Header() { const dispatch = useDispatch(); const logoutOfApp = () => { dispatch(logout()); auth.signOut(); }; return ( <div className="header"> <div className="header__left"> <img src={logo} alt="" /> <div className="header__search"> <SearchIcon /> <input placeholder="Search" type="text" /> </div> </div> <div className="header__right"> <HeaderOption Icon={HomeIcon} title="Home" /> <HeaderOption Icon={ChatIcon} title="Messaging" /> <HeaderOption Icon={NotificationsIcon} title="Notifications" /> <HeaderOption avatar={true} title="Logout" onClick={logoutOfApp} /> </div> </div> ); } export default Header;
import * as React from 'react'; interface ImageProps { source: string; fallback: string; alt?: string; width?: number; height?: number; } function getType(file: string) { return `image/${file.substring(file.lastIndexOf('.') + 1)}`; } function Image({ source, fallback, alt, width, height }: ImageProps) { return ( <picture> <source srcSet={source} type={getType(source)} /> <source srcSet={fallback} type={getType(fallback)} /> <img src={fallback} alt={alt} width={width} height={height} /> </picture> ); } export default Image;
# Golang Bindings In order to build the underlying ICICLE libraries you should run the build script `build.sh` found in the `wrappers/golang` directory. Build script USAGE ``` ./build <curve> [G2_enabled] curve - The name of the curve to build or "all" to build all curves G2_enabled - Optional - To build with G2 enabled ``` To build ICICLE libraries for all supported curves with G2 enabled. ``` ./build.sh all ON ``` If you wish to build for a specific curve, for example bn254, without G2 enabled. ``` ./build.sh bn254 ``` >[!NOTE] >Current supported curves are `bn254`, `bls12_381`, `bls12_377` and `bw6_671` >[!NOTE] >G2 is enabled by building your golang project with the build tag `g2` >Make sure to add it to your build tags if you want it enabled ## Running golang tests To run the tests for curve bn254. ``` go test ./wrappers/golang/curves/bn254 -count=1 ``` To run all the tests in the golang bindings ``` go test --tags=g2 ./... -count=1 ``` ## How do Golang bindings work? The libraries produced from the CUDA code compilation are used to bind Golang to ICICLE's CUDA code. 1. These libraries (named `libingo_<curve>.a`) can be imported in your Go project to leverage the GPU accelerated functionalities provided by ICICLE. 2. In your Go project, you can use `cgo` to link these libraries. Here's a basic example on how you can use `cgo` to link these libraries: ```go /* #cgo LDFLAGS: -L/path/to/shared/libs -lingo_bn254 #include "icicle.h" // make sure you use the correct header file(s) */ import "C" func main() { // Now you can call the C functions from the ICICLE libraries. // Note that C function calls are prefixed with 'C.' in Go code. } ``` Replace `/path/to/shared/libs` with the actual path where the shared libraries are located on your system. ## Common issues ### Cannot find shared library In some cases you may encounter the following error, despite exporting the correct `LD_LIBRARY_PATH`. ``` /usr/local/go/pkg/tool/linux_amd64/link: running gcc failed: exit status 1 /usr/bin/ld: cannot find -lbn254: No such file or directory /usr/bin/ld: cannot find -lbn254: No such file or directory /usr/bin/ld: cannot find -lbn254: No such file or directory /usr/bin/ld: cannot find -lbn254: No such file or directory /usr/bin/ld: cannot find -lbn254: No such file or directory collect2: error: ld returned 1 exit status ``` This is normally fixed by exporting the path to the shared library location in the following way: `export CGO_LDFLAGS="-L/<path_to_shared_lib>/"` ### cuda_runtime.h: No such file or directory ``` # github.com/ingonyama-zk/icicle/wrappers/golang/curves/bls12381 In file included from wrappers/golang/curves/bls12381/curve.go:5: wrappers/golang/curves/bls12381/include/curve.h:1:10: fatal error: cuda_runtime.h: No such file or directory 1 | #include <cuda_runtime.h> | ^~~~~~~~~~~~~~~~ compilation terminated. ``` Our golang bindings rely on cuda headers and require that they can be found as system headers. Make sure to add the `cuda/include` of your cuda installation to your CPATH ``` export CPATH=$CPATH:<path/to/cuda/include> ```
<!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>Barbershop</title> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&family=Raleway:wght@700&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css" /> <link href="./css/main.min.css" rel="stylesheet" /> </head> <body> <header> <div class="container header-wrapper"> <a class="logo__link" href=""> <svg class="logo" height="56" width="70" aria-label="logo"> <use class="logo__icon" href="./images/sprite.svg#icon-logo"></use> </svg> </a> <svg class="burger-icon js-open-menu" type="button" height="40" width="40" > <use href="./images/sprite.svg#icon-burger"></use> </svg> <div class="header"> <nav class="header__navigation"> <ul class="header__navigation-list"> <li> <a href="">About</a> </li> <li><a href="">Services and prices</a></li> <li><a href="">Barbers</a></li> <li><a href="">Contacts</a></li> </ul> </nav> <div class="header__contacts"> <a href="" class="header__phone-link">+38 044 111 11 11</a> <button class="button button--on-dark header__button"> online-booking </button> </div> <ul class="header__socials-list"> <li class="header__socials-item"> <a href="" class="header__socials-link">Instagram</a> </li> <li class="header__socials-item"> <a href="" class="header__socials-link">Youtube</a> </li> </ul> </div> </div> </header> <main> <section class="hero container"> <div class="hero__wrap"> <p class="pre-title-master hero__pre-title-master add-line"> A hair salon for men in Kyiv </p> <h1 class="title-h1 hero__title-h1">BarberShop</h1> <p class="hero__intro"> We are experts in trendy men's haircuts. <br /> We work quickly, carefully and with style. </p> <ul class="switcher-list hero__switcher-list"> <li class="switcher__item"> <a href="" class="switcher__link">Back</a> </li> <li class="switcher__item"> <a href="" class="switcher__link">Forward</a> </li> </ul> </div> </section> <section class="about container section"> <div class="about__img-wrap"> <picture> <source srcset=" ./images/about-1-des-1x.jpg 1x, ./images/about-1-des-2x.jpg 2x " type="image/jpg" media="(min-width:1200px)" /> <source srcset=" ./images/about-1-tab-1x.jpg 1x, ./images/about-1-tab-2x.jpg 2x " type="image/jpg" media="(min-width:768px)" /> <img srcset=" ./images/about-1-des-1x.jpg 1x, ./images/about-1-des-2x.jpg 2x " src="./images/about-1-des-1x.jpg" alt="about-1" /> </picture> <picture> <source srcset=" ./images/about-2-des-1x.jpg 1x, ./images/about-2-des-2x.jpg 2x " type="image/jpg" media="(min-width:1200px)" /> <source srcset=" ./images/about-2-tab-1x.jpg 1x, ./images/about-2-tab-2x.jpg 2x " type="image/jpg" media="(min-width:768px)" /> <img srcset=" ./images/about-2-des-1x.jpg 1x, ./images/about-2-des-2x.jpg 2x " src="./images/about-2-des-1x.jpg" alt="about-2" /> </picture> </div> <div class="about__text-wrap"> <p class="pre-title-slave about__pre-title-slave add-line">about</p> <h2 class="title-h2 title-h2--dark about__title-h2--dark"> Best Barbershop in <br /> your city </h2> <p class="about__invite"> If you want to add more confidence to your image, you should definitely visit us. </p> <p class="about__our-story"> We are a team that never stops at what has been achieved and are thirsty for changes. And when you fall into the hands of our master, you will never be the same again. We are a team that is always "on the same wave" with clients. Therefore, we are always ready to improve everyone who comes to us! </p> <button class="button about__button" data-modal-open> online-booking </button> </div> </section> <section class="prices"> <div class="container section"> <p class="pre-title-master prices__pre-title-master add-line"> Spend your time with the best masters </p> <h2 class="title-h2 title-h2--light prices__title-h2--light"> Services and prices </h2> <ul class="prices__list-common prices__list-all-in-one"> <li> <p>Men's haircut</p> <div></div> <p>from 300 uah.</p> </li> <li> <p>Beard trim</p> <div></div> <p>from 300 uah.</p> </li> <li> <p>Mustache trim</p> <div></div> <p>from 200 uah.</p> </li> <li> <p>Straight razor shave</p> <div></div> <p>from 200 uah.</p> </li> <li> <p>Trainee's haircut</p> <div></div> <p>from 50 uah.</p> </li> <li> <p>Haircut under the nozzle</p> <div></div> <p>from 200 uah.</p> </li> <li> <p>Children's haircut (0-12 y.o.)</p> <div></div> <p>from 300 uah.</p> </li> <li> <p>Camouflage of gray hair</p> <div></div> <p>from 200 uah.</p> </li> </ul> <div class="prices__list-in-two-parts"> <ul class="prices__list-common prices__first-half"> <li> <p>Men's haircut</p> <div></div> <p>from 300 uah.</p> </li> <li> <p>Beard trim</p> <div></div> <p>from 300 uah.</p> </li> <li> <p>Mustache trim</p> <div></div> <p>from 200 uah.</p> </li> <li> <p>Straight razor shave</p> <div></div> <p>from 200 uah.</p> </li> </ul> <ul class="prices__list-common prices__second-half"> <li> <p>Trainee's haircut</p> <div></div> <p>from 50 uah.</p> </li> <li> <p>Haircut under the nozzle</p> <div></div> <p>from 200 uah.</p> </li> <li> <p>Children's haircut (0-12 y.o.)</p> <div></div> <p>from 300 uah.</p> </li> <li> <p>Camouflage of gray hair</p> <div></div> <p>from 200 uah.</p> </li> </ul> </div> <button class="button button--on-dark prices__button"> online-booking </button> </div> </section> <section class="benefits container section"> <div class="replaceable-block"> <p class="pre-title-slave benefits__pre-title-slave add-line"> Old traditional school </p> <h2 class="title-h2 title-h2--dark benefits__title-h2--dark"> ¿Why people come to us? </h2> <h3 class="title-h3 benefits__title-h3"> Only good things are said about us. But it's better to see and feel 1 time than read 10 times. </h3> </div> <ul class="progress-list"> <li> <p>600</p> <p> Satisfied customers <br /> per day </p> </li> <li> <p>20</p> <p> Kyiv's best <br /> barbers </p> </li> <li> <p>50</p> <p> Awards for excellent <br /> service </p> </li> <li> <p>100</p> <p> Gifts for regular <br /> customers </p> </li> </ul> </section> <section class="masters container section"> <p class="pre-title-slave masters__pre-title-slave add-line"> For true enjoyers of the atmosphere </p> <h2 class="title-h2 title-h2--dark masters__title-h2--dark"> Our barbers </h2> <ul class="masters__list"> <li class="masters__item"> <article class="master"> <div class="master__thumb"> <picture> <source srcset=" ./images/john-Smith-des-1x.jpg 1x, ./images/john-Smith-des-2x.jpg 2x " type="image/jpg" media="(min-width:1200px)" /> <source srcset=" ./images/john-Smith-tab-1x.jpg 1x, ./images/john-Smith-tab-2x.jpg 2x " type="image/jpg" media="(min-width:768px)" /> <source srcset=" ./images/john-Smith-mob-1x.jpg 1x, ./images/john-Smith-mob-2x.jpg 2x " type="image/jpg" media="(max-width:767px)" /> <img srcset=" ./images/john-Smith-des-1x.jpg 1x, ./images/john-Smith-des-2x.jpg 2x " src="./images/john-Smith-des-1x.jpg" alt="John Smith" /> </picture> </div> <div class="master__info"> <p class="master__name">John Smith</p> <p class="master__position">Extreme Barber</p> <ul class="socials-list"> <li class="socials-list__item"> <a class="socials-list__link socials-list__link--gray" href="" rel="noopener noreferrer nofollow" > <svg class="socials-list__icon-instagram" height="20" width="20" > <use href="./images/sprite.svg#icon-instagram"></use> </svg> </a> </li> <li class="socials-list__item"> <a class="socials-list__link socials-list__link--gray" href="" rel="noopener noreferrer nofollow" > <svg class="socials-list__icon-twitter" height="20" width="20" > <use href="./images/sprite.svg#icon-twitter"></use> </svg> </a> </li> <li class="socials-list__item"> <a class="socials-list__link socials-list__link--gray" href="" rel="noopener noreferrer nofollow" > <svg class="socials-list__icon-facebook" height="20" width="20" > <use href="./images/sprite.svg#icon-facebook"></use> </svg> </a> </li> <li class="socials-list__item"> <a class="socials-list__link socials-list__link--gray" href="" rel="noopener noreferrer nofollow" > <svg class="socials-list__icon-linkedin" height="20" width="20" > <use href="./images/sprite.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </article> </li> <li class="masters__item"> <article class="master"> <div class="master__thumb"> <picture> <source srcset=" ./images/michele-doe-des-1x.jpg 1x, ./images/michele-doe-des-2x.jpg 2x " type="image/jpg" media="(min-width:1200px)" /> <source srcset=" ./images/michele-doe-tab-1x.jpg 1x, ./images/michele-doe-tab-2x.jpg 2x " type="image/jpg" media="(min-width:768px)" /> <source srcset=" ./images/michele-doe-mob-1x.jpg 1x, ./images/michele-doe-mob-2x.jpg 2x " type="image/jpg" media="(max-width:767px)" /> <img srcset=" ./images/michele-doe-des-1x.jpg 1x, ./images/michele-doe-des-2x.jpg 2x " src="./images/michele-doe-des-1x.jpg.jpg" alt="Michele Doe" /> </picture> </div> <div class="master__info"> <p class="master__name">Michele Doe</p> <p class="master__position">Extreme Barber</p> <ul class="socials-list"> <li class="socials-list__item"> <a class="socials-list__link socials-list__link--gray" href="" rel="noopener noreferrer nofollow" > <svg class="socials-list__icon-instagram" height="20" width="20" > <use href="./images/sprite.svg#icon-instagram"></use> </svg> </a> </li> <li class="socials-list__item"> <a class="socials-list__link socials-list__link--gray" href="" rel="noopener noreferrer nofollow" > <svg class="socials-list__icon-twitter" height="20" width="20" > <use href="./images/sprite.svg#icon-twitter"></use> </svg> </a> </li> <li class="socials-list__item"> <a class="socials-list__link socials-list__link--gray" href="" rel="noopener noreferrer nofollow" > <svg class="socials-list__icon-facebook" height="20" width="20" > <use href="./images/sprite.svg#icon-facebook"></use> </svg> </a> </li> <li class="socials-list__item"> <a class="socials-list__link socials-list__link--gray" href="" rel="noopener noreferrer nofollow" > <svg class="socials-list__icon-linkedin" height="20" width="20" > <use href="./images/sprite.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </article> </li> <li class="masters__item"> <article class="master"> <div class="master__thumb"> <picture> <source srcset=" ./images/alan-black-des-1x.jpg 1x, ./images/alan-black-des-2x.jpg 2x " type="image/jpg" media="(min-width:1200px)" /> <source srcset=" ./images/alan-black-tab-1x.jpg 1x, ./images/alan-black-tab-2x.jpg 2x " type="image/jpg" media="(min-width:768px)" /> <source srcset=" ./images/alan-black-mob-1x.jpg 1x, ./images/alan-black-mob-2x.jpg 2x " type="image/jpg" media="(max-width:767px)" /> <img srcset=" ./images/alan-black-des-1x.jpg 1x, ./images/alan-black-des-2x.jpg 2x " src="./images/alan-black-des-1x.jpg" alt="Alan Black" /> </picture> </div> <div class="master__info"> <p class="master__name">Alan Black</p> <p class="master__position">Extreme Barber</p> <ul class="socials-list"> <li class="socials-list__item"> <a class="socials-list__link socials-list__link--gray" href="" rel="noopener noreferrer nofollow" > <svg class="socials-list__icon-instagram" height="20" width="20" > <use href="./images/sprite.svg#icon-instagram"></use> </svg> </a> </li> <li class="socials-list__item"> <a class="socials-list__link socials-list__link--gray" href="" rel="noopener noreferrer nofollow" > <svg class="socials-list__icon-twitter" height="20" width="20" > <use href="./images/sprite.svg#icon-twitter"></use> </svg> </a> </li> <li class="socials-list__item"> <a class="socials-list__link socials-list__link--gray" href="" rel="noopener noreferrer nofollow" > <svg class="socials-list__icon-facebook" height="20" width="20" > <use href="./images/sprite.svg#icon-facebook"></use> </svg> </a> </li> <li class="socials-list__item"> <a class="socials-list__link socials-list__link--gray" href="" rel="noopener noreferrer nofollow" > <svg class="socials-list__icon-linkedin" height="20" width="20" > <use href="./images/sprite.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </article> </li> </ul> </section> <section class="history-note container section"> <h2 class="visually-hidden">historical fact</h2> <p class="pre-title-slave history-note__pre-title-slave add-line"> In Latin, "barba" means "beard" </p> <ul class="history-note__list"> <li class="history-note__item"> <div class="history-note__thumb"> <picture> <source srcset=" ./images/gallery-1-des-1x.jpg 1x, ./images/gallery-1-des-2x.jpg 2x " type="image/jpg" media="(min-width:1200px)" /> <source srcset=" ./images/gallery-1-tab-1x.jpg 1x, ./images/gallery-1-tab-2x.jpg 2x " type="image/jpg" media="(min-width:768px)" /> <source srcset=" ./images/gallery-1-mob-1x.jpg 1x, ./images/gallery-1-mob-2x.jpg 2x " type="image/jpg" media="(max-width:767px)" /> <img srcset=" ./images/gallery-1-des-1x.jpg 1x, ./images/gallery-1-des-2x.jpg 2x " src="./images/gallery-1-des-1x.jpg" alt="gallery-1" /> </picture> </div> </li> <li class="history-note__item"> <div class="history-note__thumb"> <picture> <source srcset=" ./images/gallery-2-des-1x.jpg 1x, ./images/gallery-2-des-2x.jpg 2x " type="image/jpg" media="(min-width:1200px)" /> <source srcset=" ./images/gallery-2-tab-1x.jpg 1x, ./images/gallery-2-tab-2x.jpg 2x " type="image/jpg" media="(min-width:768px)" /> <source srcset=" ./images/gallery-2-mob-1x.jpg 1x, ./images/gallery-2-mob-2x.jpg 2x " type="image/jpg" media="(max-width:767px)" /> <img srcset=" ./images/gallery-2-des-1x.jpg 1x, ./images/gallery-2-des-2x.jpg 2x " src="./images/gallery-2-des-1x.jpg" alt="gallery-2" /> </picture> </div> </li> <li class="history-note__item"> <div class="history-note__thumb"> <picture> <source srcset=" ./images/gallery-3-des-1x.jpg 1x, ./images/gallery-3-des-2x.jpg 2x " type="image/jpg" media="(min-width:1200px)" /> <source srcset=" ./images/gallery-3-tab-1x.jpg 1x, ./images/gallery-3-tab-2x.jpg 2x " type="image/jpg" media="(min-width:768px)" /> <source srcset=" ./images/gallery-3-mob-1x.jpg 1x, ./images/gallery-3-mob-2x.jpg 2x " type="image/jpg" media="(max-width:767px)" /> <img srcset=" ./images/gallery-3-des-1x.jpg 1x, ./images/gallery-3-des-2x.jpg 2x " src="./images/gallery-3-des-1x.jpg" alt="gallery-3" /> </picture> </div> </li> <li class="history-note__item"> <div class="history-note__thumb"> <picture> <source srcset=" ./images/gallery-4-des-1x.jpg 1x, ./images/gallery-4-des-2x.jpg 2x " type="image/jpg" media="(min-width:1200px)" /> <source srcset=" ./images/gallery-4-tab-1x.jpg 1x, ./images/gallery-4-tab-2x.jpg 2x " type="image/jpg" media="(min-width:768px)" /> <source srcset=" ./images/gallery-4-mob-1x.jpg 1x, ./images/gallery-4-mob-2x.jpg 2x " type="image/jpg" media="(max-width:767px)" /> <img srcset=" ./images/gallery-4-des-1x.jpg 1x, ./images/gallery-4-des-2x.jpg 2x " src="./images/gallery-4-des-1x.jpg" alt="gallery-4" /> </picture> </div> </li> </ul> </section> <section class="contacts"> <div class="form-thumb container section"> <h2 class="title-h2 title-h2--light form-thumb__title-h2--light"> Online-booking </h2> <form action="" class="contact-form"> <div class="form-fields"> <p> <input id="name" type="text" class="iput-name" placeholder="0" /> <label class="label-name" for="name">name*</label> </p> <p> <input id="phone" type="text" class="iput-phone" placeholder="0" /> <label class="label-phone" for="phone">phone*</label> </p> </div> <p> <input id="message" type="textarea" class="iput-message" rows="4" placeholder="0" /> <label class="label-message" for="message">message</label> </p> <button class="button form__button">send</button> </form> </div> <div class="contacts-thumb container section"> <h2 class="title-h2 title-h2--light contacts-thumb__title-h2--light"> Contacts </h2> <div class="address-worktime-container"> <address class="contacts__address"> <ul class="contacts__address-list"> <li class="contacts__address-item"> <a href="https://goo.gl/maps/cmzA5rGcQYwXvtrk7" class="contacts__address-link" > <svg class="socials-list__#icon-map-pin" height="20" width="18" > <use href="./images/sprite.svg#icon-map-pin"></use> </svg> st. Vasilkovaya, 7A <br class="divider" /> Kiev, 02000 </a> </li> <li class="contacts__address-item"> <a href="tel:+380441111111" class="contacts__address-link"> <svg class="socials-list__#icon-phone" height="20" width="18" > <use href="./images/sprite.svg#icon-phone"></use> </svg> +38 044 111 11 11 </a> </li> <li class="contacts__address-item"> <a href="email:barbershop@email.com" class="contacts__address-link" > <svg class="socials-list__#icon-mail" height="20" width="18" > <use href="./images/sprite.svg#icon-mail"></use> </svg> barbershop@email.com </a> </li> </ul> </address> <div class="working-time-wrap"> <p class="pre-title-master working-hours__pre-title-master add-line" > Working hours </p> <p class="working-hours__text">Every day from 9:00 to 22:00</p> </div> </div> </div> </section> </main> <footer class="container footer"> <p class="copyright">Ⓒ Copyright 2022</p> <ul class="footer__socials"> <li class="footer__socials-item"> <a href="" class="footer__socials-link">Instagram</a> </li> <li class="footer__socials-item"> <a href="" class="footer__socials-link">Youtube</a> </li> </ul> </footer> <div class="backdrop is-hidden" data-modal> <div class="modal"> <p class="title-h2 title-h2--dark modal__title-h2--dark"> We shell call <br /> You soon </p> <button class="modal__button" type="button" data-modal-close> <svg class="close-icon" height="36" width="36"> <use href="./images/sprite.svg#icon-close"></use> </svg> </button> </div> </div> <div class="js-menu-container"> <nav class="js-menu-container__navigation"> <ul> <li> <a href="">About</a> </li> <li><a href="">Services and prices</a></li> <li><a href="">Barbers</a></li> <li><a href="">Contacts</a></li> </ul> </nav> <div class="js-menu-container__contacts"> <a href="" class="js-menu-container__phone">+38 044 111 11 11</a> <button class="button js-menu-container__button">online-booking</button> </div> <ul class="js-menu-container__socials-list"> <li class="js-menu-container__socials-item"> <a href="" class="js-menu-container__socials-link">Instagram</a> </li> <li class="js-menu-container__socials-item"> <a href="" class="js-menu-container__socials-link">Youtube</a> </li> </ul> <button class="modal__button js-close-menu" type="button"> <svg class="close-icon" height="36" width="36"> <use href="./images/sprite.svg#icon-close"></use> </svg> </button> <div class="js-menu-container__backdrop"></div> </div> <script src="./js/modal.js"></script> <script src="./js/mob-menu.js"></script> </body> </html>
import { Controller, Post, Body, Put, Param, HttpStatus, HttpException, Get, UseGuards, Request, Query, HttpCode, Headers, Delete, } from '@nestjs/common'; import { ApiBearerAuth, ApiCreatedResponse, ApiTags } from '@nestjs/swagger'; import { AuthGuard } from '@nestjs/passport'; import { aggregationPipelineConfig } from 'src/modules/cart/schemas/cart.schema'; import { aggregationMan } from 'src/common/utils/aggregationMan.utils'; import { CartService } from '../services/cart.service'; import { CrudController } from 'src/common/crud/controllers/crud.controller'; import { AddItem } from '../interfaces/addItem.dto'; import { ObjectIdType } from 'src/common/utils/db.utils'; import { searchBody } from 'src/common/crud/interfaces/searchBody.dto'; import { clone, findIndex, get } from 'lodash' @ApiTags('Cart') @Controller('cart') @ApiBearerAuth('access-token') @UseGuards(AuthGuard('jwt')) export class CartController { constructor(public readonly cartService: CartService) { } @Get() @HttpCode(HttpStatus.OK) @ApiCreatedResponse({}) async getCart(@Request() req: any, @Headers() headers) { const body = { userId: new ObjectIdType(req.user.id), pharmacyId: new ObjectIdType(req.user.pharmacyId), checkedOut: false } const lang = (headers['accept-language'] == 'en' || headers['accept-language'] == 'ar' ? headers['accept-language'] : 'multiLang'); const pipelineConfig = aggregationPipelineConfig(lang) const pipeline = aggregationMan(pipelineConfig, body) return await this.cartService.aggregate(pipeline); } @Get('checked-out-transactions') @HttpCode(HttpStatus.OK) @ApiCreatedResponse({}) async getCheckedOutTransactions(@Request() req: any, @Headers() headers) { const body = { pharmacyId: req.user.pharmacyId, checkedOut: true } const lang = (headers['accept-language'] == 'en' || headers['accept-language'] == 'ar' ? headers['accept-language'] : 'multiLang'); const pipelineConfig = aggregationPipelineConfig(lang) const pipeline = aggregationMan(pipelineConfig, body) return await this.cartService.aggregate(pipeline); } @Post('add-item') @HttpCode(HttpStatus.OK) @ApiCreatedResponse({}) async addItemToCart(@Request() req: any, @Headers() headers, @Body() body: AddItem) { body["userId"] = req.user.id; body["pharmacyId"] = req.user.pharmacyId; body["checkedOut"] = false; const lang = (headers['accept-language'] == 'en' || headers['accept-language'] == 'ar' ? headers['accept-language'] : 'multiLang'); return await this.cartService.addItemToCart(body, lang) } @Post('checkout') @HttpCode(HttpStatus.OK) @ApiCreatedResponse({}) async checkout(@Request() req: any, @Headers() headers) { const { pharmacyId, id } = req.user; const lang = (headers['accept-language'] == 'en' || headers['accept-language'] == 'ar' ? headers['accept-language'] : 'multiLang'); return await this.cartService.checkout(pharmacyId, id, lang) } @Delete(':id') @HttpCode(HttpStatus.OK) @ApiCreatedResponse({}) async delete(@Param('id') id: string) { return await this.cartService.delete(id); } }
import argparse import logging import os import json import random import numpy as np import torch from transformers import BertConfig from models import ner_model from tool_utils import data_helper, train_helper, util logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) logger = logging.getLogger(__name__) # export CUDA_VISIBLE_DEVICES= def main(): parser = argparse.ArgumentParser() # 1. 训练和测试数据路径 parser.add_argument("--data_dir", default='./data/cluener', type=str, help="Path to data.") # 2. 预训练模型路径 parser.add_argument("--vocab_file", default="./data/pretrain/vocab.txt", type=str, help="Init vocab to resume training from.") parser.add_argument("--config_path", default="./data/pretrain/config.json", type=str, help="Init config to resume training from.") parser.add_argument("--init_checkpoint", default="./data/pretrain/pytorch_model.bin", type=str, help="Init checkpoint to resume training from.") # 3. 保存模型 parser.add_argument("--save_path", default="./check_points", type=str, help="Path to save checkpoints.") parser.add_argument("--load_path", default=None, type=str, help="Path to load checkpoints.") # 训练和测试参数 parser.add_argument("--do_train", default=True, type=bool, help="Whether to perform training.") parser.add_argument("--do_eval", default=True, type=bool, help="Whether to perform evaluation on test data set.") parser.add_argument("--do_test", default=False, type=bool, help="Whether to perform evaluation on test data set.") parser.add_argument("--do_adv", default=True, type=bool) parser.add_argument("--epochs", default=15, type=int, help="Number of epoches for fine-tuning.") parser.add_argument("--train_batch_size", default=16, type=int, help="Total examples' number in batch for training.") parser.add_argument("--eval_batch_size", default=64, type=int, help="Total examples' number in batch for eval.") parser.add_argument("--max_seq_len", default=256, type=int, help="Number of words of the longest seqence.") parser.add_argument("--learning_rate", default=1e-5, type=float, help="Learning rate used to train with warmup.") parser.add_argument("--crf_learning_rate", default=1e-5, type=float, help="Learning rate used to train with warmup.") parser.add_argument("--warmup_proportion", default=0.01, type=float, help="Proportion of training to perform linear learning rate warmup for. " "E.g., 0.1 = 10% of training.") parser.add_argument("--use_cuda", type=bool, default=True, help="whether to use cuda") parser.add_argument("--log_steps", type=int, default=20, help="The steps interval to print loss.") parser.add_argument("--eval_step", type=int, default=100, help="The steps interval to print loss.") parser.add_argument('--seed', type=int, default=42, help="random seed for initialization") args = parser.parse_args() if args.use_cuda: device = torch.device("cuda") n_gpu = torch.cuda.device_count() else: device = torch.device("cpu") n_gpu = 0 logger.info("device: {}, n_gpu: {}".format(device, n_gpu)) random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if n_gpu > 0: torch.cuda.manual_seed_all(args.seed) if not os.path.exists(args.save_path): os.mkdir(args.save_path) model_path_postfix = '' if args.do_adv: model_path_postfix += '_adv' args.save_path = os.path.join(args.save_path, 'ner' + model_path_postfix) if not os.path.exists(args.save_path): os.mkdir(args.save_path) bert_tokenizer = util.CNerTokenizer.from_pretrained(args.vocab_file) args.label2id = bert_tokenizer.get_label(args.data_dir) args.id2label = {v: k for k, v in args.label2id.items()} num_labels = len(args.label2id) bert_config = BertConfig.from_pretrained(args.config_path, num_labels=num_labels) # 获取数据 train_dataset = None eval_dataset = None test_dataset = None if args.do_train: logger.info("loading train dataset") train_dataset = data_helper.NER_dataset(os.path.join(args.data_dir, 'train.json'), bert_tokenizer, args.max_seq_len, args.label2id) if args.do_eval: logger.info("loading eval dataset") eval_dataset = data_helper.NER_dataset(os.path.join(args.data_dir, 'dev.json'), bert_tokenizer, args.max_seq_len, args.label2id, shuffle=False) if args.do_test: logger.info("loading test dataset") test_dataset = data_helper.NER_dataset(os.path.join(args.data_dir, 'test.json'), bert_tokenizer, args.max_seq_len, args.label2id, shuffle=False) if args.do_train: logging.info("Start training !") train_helper.train(bert_tokenizer, bert_config, args, train_dataset, eval_dataset) if not args.do_train and args.do_eval: logging.info("Start evaluating !") model = ner_model.BertCrfForNer(bert_config) model.load_state_dict(torch.load(args.load_path)) logging.info("Checkpoint: %s have been loaded!" % (args.load_path)) if args.use_cuda: model.cuda() train_helper.evaluate(args, eval_dataset, model) if args.do_test: logging.info("Start predicting !") model = ner_model.BertCrfForNer(bert_config) model.load_state_dict(torch.load(args.load_path)) logging.info("Checkpoint: %s have been loaded!" % (args.load_path)) if args.use_cuda: model.cuda() predict_res = train_helper.predict(args, test_dataset, model) if __name__ == "__main__": main()
import React, { useState } from 'react'; import { Container, Text, Paper, Group, Checkbox, Badge, Title, Button, TextInput, Flex, Modal, Center } from '@mantine/core'; import { useParams } from 'react-router-dom'; import { createTask, getListById, getTasks, removeList, removeTask, toggleTask } from '../api'; const TaskPage = () => { const { listId } = useParams(); const [tasks, setTasks] = useState([]); const [newTaskTitle, setNewTaskTitle] = useState(""); const [newTaskDescription, setNewTaskDescription] = useState(""); const [listName, setListName] = useState(""); const [selectedTask, setSelectedTask] = useState(null); const [showTaskModal, setShowTaskModal] = useState(false); const handleTitleChange = (event) => setNewTaskTitle(event.target.value); const handleDescriptionChange = (event) => setNewTaskDescription(event.target.value); React.useEffect(() => { async function fetchTasks() { document.title = "Tareas"; try { const tasksData = await getTasks(listId); const getList = await getListById(listId); setListName(getList.list.name) document.title = `Tareas - ${getList.list.name}`; setTasks(tasksData.tasks); } catch (error) { console.error('Error fetching tasks:', error); } } fetchTasks(); }, [listId]); const handleToggleTask = async (taskId) => { try { await toggleTask(taskId); const updatedTasks = tasks.map((task) => task._id === taskId ? { ...task, done: !task.done } : task ); setTasks(updatedTasks); } catch (error) { console.error('Error toggling task:', error); } }; const handleRemoveTask = async (taskId) => { try { await removeTask(taskId, listId); const updatedTasks = tasks.filter((task) => task._id !== taskId); setTasks(updatedTasks); } catch (error) { console.error('Error removing task:', error); } }; const handleAddTask = async () => { try { const data = { title: newTaskTitle, description: newTaskDescription, }; await createTask(listId, data); const tasksData = await getTasks(listId); setTasks(tasksData.tasks); } catch (error) { console.error('Error creating task: ', error); } }; const handleRemoveList = async (id) => { try { tasks.map(async (task) => await removeTask(task._id, id)); removeList(id).then((response)=>window.location.href="/mylists"); } catch (error) { console.error('Error deleting list: ', error); } }; const handleTaskClick = (task) => { setSelectedTask(task); }; const handlePaperClick = () => { setShowTaskModal(true); } return ( <Container miw={"100vw"} justify='center' align='center'> <Group maw={"60vw"} justify="center" align="center" wrap='nowrap'> <Button onClick={() => handleRemoveList(listId)} w="15%" color="red" variant="outline"> Eliminar lista </Button> <Title order={1} pl={16} w="85%" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}> Lista: {listName} </Title> </Group> <Group justify='center' align='center' maw={"60vw"}> <Group wrap="nowrap" miw={'100%'} display={'flex'} align='flex-end'> <TextInput label="Tarea" value={newTaskTitle} onChange={handleTitleChange} miw={"20vw"}/> <TextInput label="Descripción" value={newTaskDescription} onChange={handleDescriptionChange} miw={"20vw"}/> <Button onClick={handleAddTask} variant="outline" miw={"18vw"}> Agregar Tarea </Button> </Group> {tasks.map((task, index) => ( <Group key={index} align="center" mb={24} miw={"100%"} maw='60vw' wrap={'nowrap'} onClick={() => handleTaskClick(task)}> <Checkbox checked={task.done} onChange={() => handleToggleTask(task._id)} color="teal" maw={"15%"} /> <Badge color={task.done ? 'teal' : 'gray'} style={{ minWidth: 100, marginLeft: 16, flexShrink: 0 }}> {task.done ? 'Completado' : 'Pendiente'} </Badge> <Paper shadow="lg" onClick={()=> handlePaperClick()} style={{ background: task.done ? "#228be6" : "white", border: "#228be6 solid 1px", marginLeft: 16, flex: 1, minWidth: 0 }}> <Flex direction="column" gap={8} px={10} py={5}> <Text ta={'left'} truncate fw={700} style={{ color: task.done ? 'white' : 'black' }}> {task.title} </Text> <Text ta={'left'} truncate style={{ color: task.done ? 'white' : 'black' }}> {task.description} </Text> </Flex> </Paper> <Button onClick={() => handleRemoveTask(task._id)} ml={16} maw='10%' color="red" variant="outline" style={{ flexShrink: 0 }}> Eliminar </Button> </Group> ))} </Group> <Modal opened={showTaskModal} onClose={() => setShowTaskModal(false)} size="md" title="Detalles"> <Center style={{ maxHeight: '70vh', overflowY: 'auto' }}> <Flex direction="column" justify={'center'} align={"center"} style={{ maxWidth: '80vw' }}> <Text fw={700} ta={'left'} style={{ wordBreak: 'break-word' }}>{selectedTask && selectedTask.title}</Text> <Text ta={"left"} style={{ wordBreak: 'break-word' }}>{selectedTask && selectedTask.description}</Text> </Flex> </Center> </Modal> </Container> ); }; export default TaskPage;
import torch import torch.nn.functional as F import torch.nn as nn import numpy as np class GRU_Cell(nn.Module): def __init__(self, dim_in, dim_hidden, dim_meta): super(GRU_Cell, self).__init__() self.dim_in = dim_in self.dim_hidden = dim_hidden self.dim_meta = dim_meta def forward(self, x, state, Wx, Wh, b): ''' :param x: graph feature/signal - [B, N, C] or [B, B, H, H] :param state: previous hidden state - [B, N, H] :param Wx: weights - [B, N, C, 3*H] :param Wh: weights - [B, N, H, 3*H] :param b: weights - [B, N, 1, 3*H] :return h: current hidden state - [B, N, H] ''' # print('x shape:', x.shape, state.shape, Wx.shape, Wh.shape, b.shape) if len(x.shape) == 3: x = torch.unsqueeze(x, -2) # B N 1 C # print('x shape:', x.shape) Wrx, Wzx, Wcx = torch.split(Wx, self.dim_hidden, dim=-1) Wrh, Wzh, Wch = torch.split(Wh, self.dim_hidden, dim=-1) br, bz, bc = torch.split(b, self.dim_hidden, dim=-1) h = state.to(x.device) r = torch.sigmoid(x @ Wrx + h @ Wrh + br) # B N 1 H z = torch.sigmoid(x @ Wzx + h @ Wzh + bz) # B N 1 H hc = torch.tanh(x @ Wcx + (r*h) @ Wch + bc) # B N 1 H h = (1-z) * h + z * hc # B N 1 H return h def init_hidden(self, batch_size: int, num_nodes): return torch.zeros(batch_size, num_nodes, 1, self.dim_hidden) class Encoder(nn.Module): def __init__(self, num_nodes, dim_in, dim_hidden, dim_meta, num_layers=1): super(Encoder, self).__init__() self.num_nodes = num_nodes self.dim_in = dim_in self.dim_hidden = self._extend_for_multilayer(dim_hidden, num_layers) self.dim_meta = dim_meta # self.dim self.num_layers = num_layers self.cell_list = nn.ModuleList() for i in range(self.num_layers): cur_input_dim = self.dim_in if i == 0 else self.dim_hidden[i - 1] self.cell_list.append(GRU_Cell(dim_in=cur_input_dim, dim_hidden=self.dim_hidden[i], dim_meta=self.dim_meta)) def forward(self, x_seq, init_h, Wx, Wh, b): ''' :param x_seq: graph feature/signal - [B, T, N, C] :param init_h: init hidden state - [B, N, H]*num_layers :param x_meta: meta - [B, N, H_M] :return output_h: the last hidden state - [B, N, H]*num_layers ''' batch_size, seq_len = x_seq.shape[:2] if init_h is None: init_h = self._init_hidden(batch_size) current_inputs = x_seq output_h = [] for i in range(self.num_layers): h = init_h[i] h_lst= [] for t in range(seq_len): h = self.cell_list[i](current_inputs[:, t, :, :], h, Wx, Wh, b) # B N H h_lst.append(h) output_h.append(h) current_inputs = torch.stack(h_lst, dim=1) # [B, T, N, H] return output_h def _init_hidden(self, batch_size: int): h_l = [] for i in range(self.num_layers): h = self.cell_list[i].init_hidden(batch_size, self.num_nodes) h_l.append(h) return h_l @staticmethod def _extend_for_multilayer(param, num_layers): if not isinstance(param, list): param = [param] * num_layers return param class Decoder(nn.Module): def __init__(self, num_nodes, dim_out, dim_hidden, dim_meta, num_layers=1): super(Decoder, self).__init__() self.num_nodes = num_nodes self.dim_out = dim_out self.dim_hidden = self._extend_for_multilayer(dim_hidden, num_layers) self.dim_meta = dim_meta self.num_layers = num_layers self.cell_list = nn.ModuleList() for i in range(self.num_layers): cur_input_dim = self.dim_out if i == 0 else self.dim_hidden[i - 1] self.cell_list.append(GRU_Cell(dim_in=cur_input_dim, dim_hidden=self.dim_hidden[i], dim_meta=self.dim_meta)) def forward(self, x_t, h, Wx, Wh, b): ''' :param x_t: graph feature/signal - [B, N, C] :param h: previous hidden state from the last encoder cell - [B, N, H]*num_layers :param x_meta: meta - [B, N, H_M] :return output: the last hidden state - [B, N, C] :return h_lst: hidden state of each layer - [B, N, H]*num_layers ''' current_inputs = x_t # B N C h_lst= [] for i in range(self.num_layers): h_t = self.cell_list[i](current_inputs, h[i], Wx, Wh, b) h_lst.append(h_t) current_inputs = h_t output = current_inputs return output, h_lst @staticmethod def _extend_for_multilayer(param, num_layers): if not isinstance(param, list): param = [param] * num_layers return param class MetaGRU(nn.Module): def __init__(self, device, num_nodes, input_dim, output_dim, learner_hidden_dim, meta_dim, horizon, rnn_units, num_layers=1, cl_decay_steps=2000, use_curriculum_learning=True): super(MetaGRU, self).__init__() self.device = device self.num_nodes = num_nodes self.input_dim = input_dim self.output_dim = output_dim self.meta_dim = meta_dim self.horizon = horizon self.num_layers = num_layers self.rnn_units = rnn_units self.num_layers = num_layers self.decoder_dim = self.rnn_units self.cl_decay_steps = cl_decay_steps self.use_curriculum_learning = use_curriculum_learning self.learner_wx = nn.Sequential( nn.Linear(self.meta_dim, learner_hidden_dim), nn.ReLU(inplace=True), nn.Linear(learner_hidden_dim, 3 * input_dim * rnn_units), ) self.learner_wh = nn.Sequential( nn.Linear(self.meta_dim, learner_hidden_dim), nn.ReLU(inplace=True), nn.Linear(learner_hidden_dim, 3 * rnn_units * rnn_units), ) self.learner_b = nn.Sequential( nn.Linear(self.meta_dim, learner_hidden_dim), nn.ReLU(inplace=True), nn.Linear(learner_hidden_dim, 3 * rnn_units), ) self.encoder = Encoder(num_nodes=self.num_nodes, dim_in=self.input_dim, dim_hidden=self.rnn_units, dim_meta= self.meta_dim, num_layers=self.num_layers) self.decoder = Decoder(num_nodes=self.num_nodes, dim_out=self.input_dim, dim_hidden=self.decoder_dim, dim_meta= self.meta_dim, num_layers=self.num_layers) self.proj = nn.Sequential(nn.Linear(self.decoder_dim, self.output_dim)) def compute_sampling_threshold(self, batches_seen): return self.cl_decay_steps / (self.cl_decay_steps + np.exp(batches_seen / self.cl_decay_steps)) def forward(self, x, x_meta, labels=None, batches_seen=None): # x - [B, T, N, C] x_meta - [N, H_M] batch_size = x.shape[0] x_meta = x_meta.expand(batch_size,self.num_nodes, self.meta_dim) # B N H_M Wx = self.learner_wx(x_meta).view( batch_size, self.num_nodes, self.input_dim, 3 * self.rnn_units ) Wh = self.learner_wh(x_meta).view( batch_size, self.num_nodes, self.rnn_units, 3 * self.rnn_units ) b = self.learner_b(x_meta).view( batch_size, self.num_nodes, 1, 3 * self.rnn_units ) init_h = None h_lst = self.encoder(x, init_h, Wx, Wh, b) go = torch.zeros((x.shape[0], x.shape[2], x.shape[3]), device=x.device) # original initialization [B N C] out = list() for t in range(self.horizon): h_de, h_lst = self.decoder(go, h_lst, Wx, Wh, b) go = self.proj(torch.squeeze(h_de)) # 当Batchsize为 1 时 会将那当Batchsize那一维去掉,需要手动加回 if batch_size == 1: go = torch.unsqueeze(go, 0) # B N 1 C out.append(go) if self.training and self.use_curriculum_learning: c = np.random.uniform(0, 1) if c < self.compute_sampling_threshold(batches_seen): go = labels[:, t, ...] # out: T*(B N C) outputs = torch.stack(out, dim=1) # B,T,N,C return outputs # model = MetaGRU(device=torch.device('cpu'), num_nodes=207, input_dim=1, output_dim=1, meta_dim=32, horizon=12, rnn_units=64) # from torchsummary import summary # summary(model,[(64,12,207,1),(207,32)])
<!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>Mafaz || Portfolio</title> <link rel="shortcut icon" href="Asset/Image/Fav-Icon.jpg" type="image/x-icon"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script> <link rel="stylesheet" href="Asset/CSS/style.css"> <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet"> <script src="https://kit.fontawesome.com/f61b217d65.js" crossorigin="anonymous"></script> </head> <body> <nav class="navbar navbar-expand-sm"> <div class="container-fluid"> <a class="navbar-brand fw-bold ms-md-5 fs-2 black" href="index.html"><span class="logo ps-1 pe-1 rounded-circle">M</span> Mafaz Malik</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-end pe-5" id="collapsibleNavbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link black borderLeft" href="resume.html">Resume</a> </li> <li class="nav-item"> <a class="nav-link black" href="project.html">Projects</a> </li> </ul> </div> </div> </nav> <section class="container"> <div class="row"> <div class="col-6" data-aos="fade-up" data-aos-duration="1000"> <h1 class="py-4 my-4">Projects</h1> </div> <div class="row py-3" data-aos="fade-up" data-aos-duration="1000"> <div class="col-12 col-md-6" data-aos="fade-right" data-aos-duration="1500"> <h4>LMS-Student Portal</h4> <p class="pt-3 text-justify">Designing various pages from the admin and student modules of the LMS platform and adding form validation to all the forms of these two modules. Along with Designing and validating forms also performed API integration using HTTP-Client Service. For enhancing the loading time performance, used the lazy loading concept.</p> <p>Tech Used: Angular 14, HTML, CSS, Bootstrap.</p> </div> <div class="col-12 col-md-6" data-aos="fade-left" data-aos-duration="1500"> <a href="https://rexcoders.in/home"> <img src="./Asset/Image/Rex_Portal.png" alt="Rex_Portal" height="100%" width="100%"> </a> </div> </div> <div class="row py-3" data-aos="fade-up" data-aos-duration="1000"> <div class="col-12 col-md-6" data-aos="fade-right" data-aos-duration="1500"> <h4>CMS-Content Management System</h4> <p class="pt-3 text-justify">Designing various pages from the admin modules of the CMS platform and adding form validation to all the forms of these modules. Along with Designing and validating forms also performed API integration using HTTP-Client Service. For enhancing the loading time performance, used the lazy loading concept.</p> <p>Tech Used: Angular 14, HTML, CSS, Bootstrap.</p> </div> <div class="col-12 col-md-6" data-aos="fade-left" data-aos-duration="1500"> <a href="https://github.com/RexKnar/Rex-CMS"> <img src="./Asset/Image/CMS.png" alt="CMS" height="100%" width="100%"> </a> </div> </div> <div class="row py-3" data-aos="fade-up" data-aos-duration="1000"> <div class="col-12 col-md-6" data-aos="fade-right" data-aos-duration="1500"> <h4>Office Republic</h4> <p class="pt-3 text-justify">Designed a various pages with responsive from starch using HTML, CSS, and Bootstrap for designing.</p> <p>Tech Used: HTML, CSS, Bootstrap.</p> </div> <div class="col-12 col-md-6" data-aos="fade-left" data-aos-duration="1500"> <a href="https://mafazmalik.github.io/officeRepublic/"> <img src="./Asset/Image/Office_Republic.png" alt="officeRepublic" height="100%" width="100%"> </a> </div> </div> <div class="row py-3" data-aos="fade-up" data-aos-duration="1000"> <div class="col-12 col-md-6" data-aos="fade-right" data-aos-duration="1500"> <h4>Lawyer</h4> <p class="pt-3 text-justify">Designed a various pages using templates for designing.</p> <p>Tech Used: HTML, CSS, Bootstrap.</p> </div> <div class="col-12 col-md-6" data-aos="fade-left" data-aos-duration="1500"> <a href="https://mafazmalik.github.io/Lawyer/"> <img src="./Asset/Image/Lawyer.png" alt="Lawyer" height="100%" width="100%"> </a> </div> </div> <div class="row py-3" data-aos="fade-up" data-aos-duration="1000"> <div class="col-12 col-md-6" data-aos="fade-right" data-aos-duration="1500"> <h4>Pagenation</h4> <p class="pt-3 text-justify">Designed a two pages with responsive and pagenation concept from starch using HTML, CSS, and Bootstrap for designing.</p> <p>Tech Used: HTML, CSS, Bootstrap.</p> </div> <div class="col-12 col-md-6" data-aos="fade-left" data-aos-duration="1500"> <a href="https://mafazmalik.github.io/Pagenation/"> <img src="./Asset/Image/Pagenation.png" alt="Pagenation" height="100%" width="100%"> </a> </div> </div> <div class="row py-3" data-aos="fade-up" data-aos-duration="1000"> <div class="col-12 col-md-6" data-aos="fade-right" data-aos-duration="1500"> <h4>Portfolio</h4> <p class="pt-3 text-justify">Designed a single page static webpage with responsive from starch using HTML and CSS for designing.</p> <p>Tech Used: HTML & CSS.</p> </div> <div class="col-12 col-md-6" data-aos="fade-left" data-aos-duration="1500"> <a href="https://mafazmalik.github.io/Portfolio_css/"> <img src="./Asset/Image/Personal.png" alt="My Personal" height="100%" width="100%"> </a> </div> </div> </div> </section> <footer class="container border-top border-1 border-secondary pt-3 pb-5"> <div class="row"> <div class="col-12 col-sm-6 col-lg-3 p-3" data-aos="fade-up" data-aos-duration="400"> <h4>Phone</h4> <a href="tel:+91 8925363228" class="myContact">+91 8925363228</a> </div> <div class="col-12 col-sm-6 col-lg-3 p-3" data-aos="fade-up" data-aos-duration="800"> <h4>Email</h4> <a href="mailto:mafazmafs0206@gmail.com" class="myContact">mafazmafs0206@gmail.com</a> </div> <div class="col-12 col-sm-6 col-lg-3 p-3" data-aos="fade-up" data-aos-duration="1200"> <h4>Follow Me</h4> <a href="https://github.com/MafazMalik" class="github iconFontSize"><i class="fa-brands fa-square-github"></i></a> <a href="https://www.linkedin.com/in/mafaz-malik-s-28967b238/" class="linkedIn iconFontSize"><i class="fa-brands fa-linkedin"></i></a> <a href="https://twitter.com/MFZMF1" class="twitter iconFontSize"><i class="fa-brands fa-square-twitter"></i></a> <a href="https://www.instagram.com/mafaz_mafs/" class="instagram iconFontSize"><i class="fa-brands fa-square-instagram"></i></a> <a href="https://www.facebook.com/mafaz.mafs" class="facebook iconFontSize"><i class="fa-brands fa-square-facebook"></i></a> </div> <div class="col-12 col-sm-6 col-lg-3 p-3" data-aos="fade-up" data-aos-duration="1600"> <p>© 2023 By Mafaz | All Rights Reserved</p> </div> </div> </footer> <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script> <script> AOS.init(); </script> </body> </html>
#include <shg/mathprog.h> #include "tests.h" namespace TESTS { BOOST_AUTO_TEST_SUITE(mathprog_test) using SHG::Simplex; using SHG::Matdouble; using SHG::Vecdouble; using SHG::Vecint; using SHG::faeq; BOOST_AUTO_TEST_CASE(simplex_gass_76) { Matdouble const A{3, 4, {1.0, 2.0, 3.0, 0.0, 2.0, 1.0, 5.0, 0.0, 1.0, 2.0, 1.0, 1.0}}; Vecdouble const b{15.0, 20.0, 10.0}; Vecdouble const c{-1.0, -2.0, -3.0, 1.0}; Simplex::Vecequality const e{Simplex::eq, Simplex::eq, Simplex::eq}; Simplex::Direction const d = Simplex::min; double const eps = 1e-9; Simplex s(A.nrows(), A.ncols(), A, b, c, e, d, eps); BOOST_REQUIRE(s.status == 0); BOOST_CHECK(faeq(s.f, -15.0, eps)); BOOST_CHECK(faeq(s.x(0), 2.5, eps)); BOOST_CHECK(faeq(s.x(1), 2.5, eps)); BOOST_CHECK(faeq(s.x(2), 2.5, eps)); BOOST_CHECK(faeq(s.x(3), 0.0, eps)); } BOOST_AUTO_TEST_CASE(simplex_gass_82e) { Matdouble const A{4, 5, {0.0, 2.0, -1.0, -1.0, 1.0, -2.0, 0.0, 2.0, -1.0, 1.0, 1.0, -2.0, 0.0, -1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0}}; Vecdouble const b{0.0, 0.0, 0.0, 1.0}; Vecdouble const c{0.0, 0.0, 0.0, 1.0, -1.0}; Simplex::Vecequality const e{Simplex::ge, Simplex::ge, Simplex::ge, Simplex::eq}; Simplex::Direction const d = Simplex::max; double const eps = 1e-9; Simplex s(A.nrows(), A.ncols(), A, b, c, e, d, eps); BOOST_CHECK(s.status == 0); BOOST_CHECK(faeq(s.f, 0.0, eps)); BOOST_CHECK(faeq(s.x(0), 0.4, eps)); BOOST_CHECK(faeq(s.x(1), 0.2, eps)); BOOST_CHECK(faeq(s.x(2), 0.4, eps)); BOOST_CHECK(faeq(s.x(3), 0.0, eps)); BOOST_CHECK(faeq(s.x(4), 0.0, eps)); } BOOST_AUTO_TEST_CASE(simplex_gass_82g) { Matdouble const A{2, 3, {-2.0, 1.0, 3.0, 2.0, 3.0, 4.0}}; Vecdouble const b{2.0, 1.0}; Vecdouble const c{1.0, -2.0, 3.0}; Simplex::Vecequality const e{Simplex::eq, Simplex::eq}; Simplex::Direction const d = Simplex::min; double const eps = 1e-9; Simplex s(A.nrows(), A.ncols(), A, b, c, e, d, eps); BOOST_CHECK(s.status == 2); } /** * \todo Explain why "using SHG::wolfe" is not required. */ /* * Solves the problem * * minimize * -6x_1 + 2x_1^2 - 2x_1x_2 + 2x_2^2 * subject to * x_1 + x_2 <= 2 * x_j >= 0 * * Cf. wolfe_grabowski_256 */ BOOST_AUTO_TEST_CASE(wolfe_example) { Vecdouble const p{-6.0, 0.0, 0.0}, C{2.0, -1.0, 0.0, 2.0, 0.0, 0.0}, b{2.0}; Vecdouble x(3); Matdouble const A(1, 3, {1.0, 1.0, 0.0}); double f; int const st = wolfe(p, C, A, b, x, f); BOOST_CHECK(st == 0); BOOST_CHECK(faeq(f, -5.5, 1e-16)); BOOST_CHECK(faeq(x[0], 1.5, 1e-16)); BOOST_CHECK(faeq(x[1], 0.5, 1e-16)); BOOST_CHECK(faeq(x[2], 0.0, 1e-16)); } BOOST_AUTO_TEST_CASE(wolfe_grabowski_247) { int const m = 2, n = 4; Vecdouble p(n, 0.0); Vecdouble C(n * (n + 1) / 2, 0.0); Vecdouble b(m, 0.0); Vecdouble x(n, 0.0); Vecdouble x0(n, 0.0); Matdouble A(m, n, 0.0); double f; double f0 = -100.0; p[0] = -10.0; p[1] = -25.0; C[0] = 10.0; C[1] = 2.0; C[4] = 1.0; A[0][0] = 1.0; A[0][1] = 2.0; A[0][2] = 1.0; A[1][0] = 1.0; A[1][1] = 1.0; A[1][3] = 1.0; b[0] = 10.0; b[1] = 9.0; x0[1] = 5.0; x0[3] = 4.0; int const st = wolfe(p, C, A, b, x, f); BOOST_REQUIRE(st == 0); BOOST_CHECK(faeq(f, f0, 1e-16)); for (int i = 0; i < n; i++) BOOST_CHECK(faeq(x[i], x0[i], 1e-16)); } BOOST_AUTO_TEST_CASE(wolfe_grabowski_256) { int const m = 1, n = 3; Vecdouble p(n, 0.0); Vecdouble C(n * (n + 1) / 2, 0.0); Vecdouble b(m, 0.0); Vecdouble x(n, 0.0); Vecdouble x0(n, 0.0); Matdouble A(m, n, 0.0); double f; double f0 = -5.5; p(0) = -6.0; C(0) = C(3) = 2.0; C(1) = -1.0; A(0, 0) = A(0, 1) = A(0, 2) = 1.0; b(0) = 2.0; x0(0) = 1.5; x0(1) = 0.5; int const st = wolfe(p, C, A, b, x, f); BOOST_REQUIRE(st == 0); BOOST_CHECK(faeq(f, f0, 1e-16)); for (int i = 0; i < n; i++) BOOST_CHECK(faeq(x[i], x0[i], 1e-16)); } /** * Quadratic programming problem. The problem \f{align*} * \mbox{minimize} & \quad -6x_1 + 2x_1^2 - 2x_1x_2 + 2x_2^2 \\ * \mbox{subject to} & \quad x_1 + x_2 \leq 2, \\ & \quad x_j \geq 0 * \f} (\cite gass-1980, p. 285). \f$C\f$ is not positive definite. */ BOOST_AUTO_TEST_CASE(wolfe_gass_285) { int const m = 2, n = 4; Vecdouble p(n, 0.0); Vecdouble C(n * (n + 1) / 2, 0.0); Vecdouble b(m, 0.0); Vecdouble x(n, 0.0); Vecdouble x0(n, 0.0); Matdouble A(m, n, 0.0); double f; double f0 = -22.0 / 9.0; p(0) = -2.0; p(1) = -1.0; C(0) = 1.0; A(0, 0) = 2.0; A(0, 1) = 3.0; A(0, 2) = 1.0; A(1, 0) = 2.0; A(1, 1) = 1.0; A(1, 3) = 1.0; b(0) = 6.0; b(1) = 4.0; x0(0) = 2.0 / 3.0; x0(1) = 14.0 / 9.0; x0(3) = 10.0 / 9.0; int const st = wolfe(p, C, A, b, x, f); BOOST_REQUIRE(st == 0); BOOST_CHECK(faeq(f, f0, 5e-16)); for (int i = 0; i < n; i++) BOOST_CHECK(faeq(x[i], x0[i], 5e-16)); } /* * \sum_{i = 1}^n (alpha[i] * x[i] - beta[i])^2, n big, alpha[i], * beta[i] >= 0 minimizes to zero at x[i] = beta[i] / alpha[i]. */ BOOST_DATA_TEST_CASE(wolfe_simple, bdata::xrange(2) * bdata::xrange(8), xr1, xr2) { Vecint const mm{1, 3}; Vecint const nn{1, 5, 10, 20, 50, 100, 200, 500}; int const m = mm(xr1); int const n = nn(xr2); Vecdouble p(n, 0.0); Vecdouble C(n * (n + 1) / 2, 0.0); Vecdouble b(m, 0.0); Vecdouble x(n, 0.0); Vecdouble x0(n, 0.0); Matdouble A(m, n, 0.0); double f, f0; int i, j, k; Vecdouble alpha(n), beta(n); for (i = 0; i < n; i++) { alpha(i) = i + 1; beta(i) = (i + 1) * (i + 1); } j = n; k = 0; for (i = 0; i < n; i++) { p(i) = -2.0 * alpha(i) * beta(i); x0(i) = beta(i) / alpha(i); C(k) = alpha(i) * alpha(i); k += j--; } for (i = 0; i < m; i++) { for (j = 0; j < n; j++) A(i, j) = 1; f = 0.0; for (j = 0; j < n; j++) f += beta(j) / alpha(j); b(i) = f; } f0 = 0.0; for (i = 0; i < n; i++) f0 -= beta(i) * beta(i); int const st = wolfe(p, C, A, b, x, f); BOOST_REQUIRE(st == 0); BOOST_CHECK(faeq(f, f0, 1e-16)); for (int i = 0; i < n; i++) BOOST_CHECK(faeq(x[i], x0[i], 1e-16)); } /* * The test data are generated in the following way. For a positive * definite symmetric matrix H and such matrix U, vector v and vector * z >= 0 that Uz = v, the form (Ux - v)^(T)H(Ux - v) has a minimum 0 * at x = z. Thus the form p^(T)x + x^(T)C x, where C = U^(T)HU, p = * -2v^(T)HU, has a minimum -v^(T)Hv at the same point. As a set of * linear equality restrictions, a subset of the first m equalities * from Ux = v may be taken. If U is a square invertible matrix, the * minimum is unique. * * Here we take a Hilbert matrix as H, that is H(i, j) = 1 / (i + j + * 1), i, j = 0, 1, ..., n - 1, and an upper triangle matrix of the * form u[i][j] = 0 for i > j, u[i][j] = w^(j - i) for i <= j, i, j = * 0, 1, ..., n - 1, w = 1.01, as U. We also take z = (1 1 ... 1)^(T). */ BOOST_DATA_TEST_CASE(wolfe_complex, bdata::xrange(2) * bdata::xrange(5), xr1, xr2) { Vecint const mm{1, 3}; Vecint const nn{1, 5, 10, 20, 50}; Matdouble const eps{2, 5, {1e-16, 1.5e-9, 1.3, 3.4, 9.8, 1e-16, 1.5e-11, 1.1, 2.9, 7.5}}; int const m = mm(xr1); int const n = nn(xr2); double const w = 1.01; Vecdouble p(n, 0.0); Vecdouble C(n * (n + 1) / 2, 0.0); Vecdouble b(m, 0.0); Vecdouble x(n, 0.0); Vecdouble x0(n, 0.0); Matdouble A(m, n, 0.0); Matdouble CC(n, n, 0.0); // auxiliary, analogous to C double f, f0; double s, d; int i, j, k; Vecdouble& v = x; // v will be kept in x // The first m rows of A and b. for (i = 0; i < m; i++) { s = 0.0; d = 1.0; for (j = i; j < n; j++) { A(i, j) = d; s += d; d *= w; } b(i) = s; } // Calculate v = Uz = U * (1 1 ... 1). for (i = 0; i < n; i++) { s = 0.0; d = 1.0; for (j = i; j < n; j++) { s += d; d *= w; } v(i) = s; } // C <-- HU for (i = 0; i < n; i++) for (j = 0; j < n; j++) { s = 0.0; d = 1.0; for (k = j; k >= 0; k--) { s += d / (i + k + 1); d *= w; } CC(i, j) = s; } // p <-- -2v^(T)C for (j = 0; j < n; j++) { s = 0.0; for (i = 0; i < n; i++) s -= v(i) * CC(i, j); p(j) = 2.0 * s; } // Calculate f = -v^(T)Hv. f0 = 0.0; for (i = 0; i < n; i++) { s = 0.0; for (j = i + 1; j < n; j++) s += v(j) / (i + j + 1); s = 2.0 * s + v(i) / (2.0 * i + 1); f0 -= s * v(i); } // C <-- H^(T)C for (i = 1; i < n; i++) for (j = 0; j < n; j++) CC(i, j) += CC(i - 1, j) * w; for (i = 0; i < n; i++) x0(i) = 1.0; k = 0; for (i = 0; i < n; i++) for (j = i; j < n; j++) C(k++) = CC(i, j); int const st = wolfe(p, C, A, b, x, f); BOOST_REQUIRE(st == 0); BOOST_CHECK(faeq(f, f0, 3e-11)); for (int i = 0; i < n; i++) BOOST_CHECK(faeq(x[i], x0[i], eps[xr1][xr2])); } BOOST_AUTO_TEST_SUITE_END() } // namespace TESTS
import { createSlice } from '@reduxjs/toolkit' import type { PayloadAction } from '@reduxjs/toolkit' import type { RootState } from '..' interface employeeState { employeeList: { key: number, prefix: string, firstName: string, lastName: string, birthDate: Date, nationality: string, idCardNumber: string, gender: string, phoneNumber: { code: string, number: number }, passportNumber: number | null, wishSalary: number }[], empInfo: { key: number, prefix: string, firstName: string, lastName: string, birthDate: Date, nationality: string, idCardNumber: string, gender: string, phoneNumber: { code: string, number: number }, passportNumber: number | null, wishSalary: number } | null } const initialState: employeeState = { employeeList: [], empInfo: null } export const employeeSlice = createSlice({ name: 'employee', initialState, reducers: { loadEmployeeFromLocalStorage: (state) => { const employeeListFromlocalStorage: any = localStorage.getItem("employeeList") if (employeeListFromlocalStorage !== null) { state.employeeList = JSON.parse(employeeListFromlocalStorage) } }, addEmployee: (state, action) => { const { formData, idCardNumber } = action.payload if (state.employeeList.length === 0) { state.employeeList = [...state.employeeList, { key: 0, ...formData, idCardNumber }] } else { const lastKey = Math.max(...state.employeeList.map(obj => obj.key)) state.employeeList = [...state.employeeList, { key: lastKey + 1, ...formData, idCardNumber }] } localStorage.setItem("employeeList", JSON.stringify(state.employeeList)) }, getEmployeeInfo: (state, action) => { state.empInfo = state.employeeList.filter((emp) => (emp.key === action.payload))[0] }, editEmployeeInfo: (state, action) => { const { editKey, formData, idCardNumber } = action.payload const editState = state.employeeList.map((emp) => { if (emp.key === editKey) { return { key: editKey, ...formData, idCardNumber } } else { return emp } }) state.employeeList = editState localStorage.setItem("employeeList", JSON.stringify(state.employeeList)) }, deleteAllEmployeeSelect: (state, action) => { const keyArr: number[] = action.payload let stateUpdate = state.employeeList keyArr.map((key) => { stateUpdate = stateUpdate.filter((data) => (data.key !== key)) }) state.employeeList = stateUpdate localStorage.setItem("employeeList", JSON.stringify(state.employeeList)) }, clearEmployeeInfo: (state) => { state.empInfo = null }, clearEmployeeFromLocalStorage: (state) => { localStorage.removeItem("employeeList") } }, }) export const { loadEmployeeFromLocalStorage, clearEmployeeFromLocalStorage, addEmployee, getEmployeeInfo, editEmployeeInfo, clearEmployeeInfo, deleteAllEmployeeSelect } = employeeSlice.actions export default employeeSlice.reducer
import { createRoot } from 'react-dom/client'; /** @jsxImportSource @emotion/react */ import { css } from "@emotion/react"; import { useEffect, useState } from 'react'; import { Autocomplete, Button, TextField } from '@mui/material'; import { v4 as uuid } from "uuid"; import toast, { Toaster } from 'react-hot-toast'; const Script = () => { const [selectedText, setSelectedText] = useState(''); const [description, setDescription] = useState(''); const [showPopup, setShowPopup] = useState(false); const [currentUrl, setCurrentUrl] = useState(''); const [category, setCategory] = useState(''); const [categoryList, setCategoryList] = useState([]); const isClient = typeof window === 'object'; useEffect(() => { if (!isClient) { return; } const handleMouseUp = () => { const text = window.getSelection()?.toString(); if (text) { setSelectedText(text); } }; const handleKeyUp = (e) => { if (e.key === 'Tab' && selectedText) { e.preventDefault(); // デフォルトのTab挙動を防ぐ setShowPopup(true); } }; document.addEventListener('mouseup', handleMouseUp); document.addEventListener('keyup', handleKeyUp); return () => { document.removeEventListener('mouseup', handleMouseUp); document.removeEventListener('keyup', handleKeyUp); }; }, [isClient, selectedText]); useEffect(() => { setCurrentUrl(window.location.href); chrome.storage.local.get(['category'], function (result) { if (result.category && result.category.length > 0) { const filteredCategories = result.category.filter(cat => cat && cat !== 'all'); setCategoryList(filteredCategories); } }); }, []) const overlayStyle = css({ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', backgroundColor: 'rgba(0, 0, 0, 0.5)', // 薄暗い背景 display: showPopup ? 'block' : 'none', zIndex: 1000, }); const popupStyle = css({ position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', backgroundColor: 'white', padding: '50px', borderRadius: '10px', display: showPopup ? 'block' : 'none', zIndex: 1001, }); const closeButtonStyle = css({ position: 'absolute', top: '10px', right: '10px', cursor: 'pointer', zIndex: 1002, }); const textFieldListStyle = css({ display: 'flex', flexDirection: 'column', gap: '20px', }) const handleSubmit = (e) => { e.preventDefault(); const toastId = toast.loading('送信中...'); // Chrome Storageからデータを取得 chrome.storage.local.get(['myData', 'category'], function (result) { const existingWordList = result.myData || []; const existingCategoryList = result.category || ['all']; console.log(existingWordList); // 新しいオブジェクトを配列に追加 const wordList = [{ title: selectedText, url: currentUrl, category: category, description: description, id: uuid() }, ...existingWordList]; let categoryList = existingCategoryList; if (!existingCategoryList.includes(category)) { categoryList = [...existingCategoryList, category]; } console.log('送信されました'); // Chrome Storageにデータを保存 chrome.storage.local.set({ 'myData': wordList, 'category': categoryList }); // 'myData' キーを使用 toast.success('送信成功', { id: toastId }); setSelectedText(''); setDescription(''); setCategory(''); setCurrentUrl(''); setDescription(''); }); } return ( <div> {isClient && showPopup && <div css={overlayStyle} />} {isClient && ( <div css={popupStyle}> <Toaster /> <div css={closeButtonStyle} onClick={() => setShowPopup(false)}>✖</div> <form onSubmit={handleSubmit}> <div css={textFieldListStyle}> <TextField id="outlined-basic" label="word" variant="outlined" value={selectedText} onChange={(e) => setSelectedText(e.target.value)} sx={{ width: '400px' }} required /> <TextField id="outlined-basic" label="URL" variant="outlined" value={currentUrl} sx={{ width: '400px' }} onChange={(e) => setCurrentUrl(e.target.value)} required /> <Autocomplete freeSolo id="category-autocomplete" options={categoryList} value={category} onChange={(event, newValue) => { setCategory(newValue); }} getOptionLabel={(option) => option ? option : ''} renderInput={(params) => ( <TextField {...params} label="Category" variant="outlined" value={category} onChange={(e) => setCategory(e.target.value)} required /> )} /> <TextField id="outlined-multiline-static" label="description" multiline rows={4} value={description} onChange={(e) => setDescription(e.target.value)} required /> <Button variant="outlined" type='submit'>Submit</Button> </div> </form> </div> ) } </div > ); }; // ページ上に新しい要素を作成 const app = document.createElement('div'); app.id = "my-extension-root"; // 新しい要素をbodyの最初の子として挿入 document.body.insertBefore(app, document.body.firstChild); // 新しいAPIを使用してReactコンポーネントをレンダリング const root = createRoot(app); root.render(<Script />);
package com.example.myapplication; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MusicPlayerActivity extends AppCompatActivity { private MediaPlayer mediaPlayer; private Music[] musicList; private int currentMusicIndex; private SeekBar progressBar; private Handler handler; private Runnable updateProgressRunnable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_music_player); // Retrieve the music list from MainActivity musicList = MainActivity.musicList; Button b = (Button)findViewById(R.id.btnBack); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); Button btnPlayPause = findViewById(R.id.btnPlayPause); btnPlayPause.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mediaPlayer != null) { if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); //btnPlayPause.setText("Play"); } else { mediaPlayer.start(); //btnPlayPause.setText("Pause"); } } } }); // Set up a handler to update the progress bar handler = new Handler(); updateProgressRunnable = new Runnable() { @Override public void run() { if (mediaPlayer != null) { int currentPosition = mediaPlayer.getCurrentPosition(); progressBar.setProgress(currentPosition); } // Schedule the update every 100 milliseconds (adjust as needed) handler.postDelayed(this, 100); } }; // Retrieve the music title from the intent Intent intent = getIntent(); String selectedMusicTitle = intent.getStringExtra("selectedMusicTitle"); // Find the index of the selected music title in the musicList for (int i = 0; i < musicList.length; i++) { if (musicList[i].getTitle().equals(selectedMusicTitle)) { currentMusicIndex = i; break; } } startMusicPlayback(); } private void initUI() { // Initialize UI elements here (e.g., set text for TextViews) TextView titleTextView = findViewById(R.id.textTitle); TextView singerTextView = findViewById(R.id.textSinger); ImageView albumCoverImageView = findViewById(R.id.imageAlbumCover); // Update UI with the current music information titleTextView.setText(musicList[currentMusicIndex].getTitle()); singerTextView.setText(musicList[currentMusicIndex].getSinger()); albumCoverImageView.setImageResource(musicList[currentMusicIndex].getAlbumCover()); // Set up click listeners for next and previous buttons Button btnNext = findViewById(R.id.btnNext); btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playNextMusic(); } }); Button btnPrevious = findViewById(R.id.btnPrevious); btnPrevious.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playPreviousMusic(); } }); progressBar = findViewById(R.id.progressBar); // Set up the progress bar max value (duration of the music in milliseconds) progressBar.setMax(mediaPlayer.getDuration()); // Set up a listener for changes in the progress bar progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser && mediaPlayer != null) { mediaPlayer.seekTo(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { // Do nothing } @Override public void onStopTrackingTouch(SeekBar seekBar) { // Do nothing } }); } private void startMusicPlayback() { // Initialize MediaPlayer and load the music file mediaPlayer = MediaPlayer.create(this, musicList[currentMusicIndex].getResourceId()); mediaPlayer.start(); // Set up a completion listener to automatically play the next music when the current one finishes mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { playNextMusic(); } }); // Initialize UI elements and start music playback initUI(); // Start the progress bar update runnable handler.post(updateProgressRunnable); } private void playNextMusic() { // Increment the current music index currentMusicIndex = (currentMusicIndex + 1) % musicList.length; // Stop the current music and release resources if (mediaPlayer != null) { mediaPlayer.release(); } // Start playback for the next music startMusicPlayback(); } private void playPreviousMusic() { // Decrement the current music index currentMusicIndex = (currentMusicIndex - 1 + musicList.length) % musicList.length; // Stop the current music and release resources if (mediaPlayer != null) { mediaPlayer.release(); } // Start playback for the previous music startMusicPlayback(); } @Override protected void onDestroy() { super.onDestroy(); if (mediaPlayer != null) { handler.removeCallbacks(updateProgressRunnable); mediaPlayer.release(); mediaPlayer = null; } } @Override public void onBackPressed() { // Pass the current music index back to MainActivity Intent intent = new Intent(); intent.putExtra("currentMusicIndex", currentMusicIndex); setResult(RESULT_OK, intent); super.onBackPressed(); } }
<?php // Settings page callback function woocommerce_sales_insights_settings() { // Get the site's timezone from WordPress settings $site_timezone = get_option('timezone_string'); // Set the timezone if ($site_timezone) { date_default_timezone_set($site_timezone); } // Save the settings if form is submitted if (isset($_POST['woocommerce_sales_insights_submit'])) { // Retrieve and sanitize the email addresses $email_addresses = isset($_POST['email_addresses']) ? sanitize_text_field($_POST['email_addresses']) : ''; $email_addresses = preg_replace('/\s+/', '', $email_addresses); // Remove whitespace // Split the email addresses by comma $email_addresses = array_map('trim', explode(',', $email_addresses)); // Filter out empty values $email_addresses = array_filter($email_addresses); // Convert the array of email addresses into a comma-separated string $email_string = implode(',', $email_addresses); $send_time = isset($_POST['send_time']) ? sanitize_text_field($_POST['send_time']) : ''; // Update the option with the array of email addresses update_option('woocommerce_sales_insights_email_addresses', $email_string); update_option('woocommerce_sales_insights_send_time', $send_time); // Calculate the next send time $next_send_time = strtotime('first day of +1 month', strtotime('today ' . $send_time . ' ' . $site_timezone)); $current_time = strtotime(current_time('Y-m-d H:i:s')); // Check if the next send time is in the past if ($next_send_time < $current_time) { // Add one day to the current date $next_send_time = strtotime('first day of +1 month', $current_time); // Set the time for the next send time $next_send_time = strtotime($send_time, $next_send_time); // Validate if the time was successfully set if ($next_send_time === false) { // Time format is invalid, handle the error $error_message = 'Invalid time format. Please enter a valid time.'; woocommerce_sales_insights_log_event($error_message); echo '<div class="error notice"><p>' . $error_message . '</p></div>'; return; } } // Check if the next send time is valid if ($next_send_time === false) { // Date or timezone is invalid, handle the error $error_message = 'Invalid date or timezone. Please check your settings.'; woocommerce_sales_insights_log_event($error_message); echo '<div class="error notice"><p>' . $error_message . '</p></div>'; return; } // Unschedule the existing event wp_clear_scheduled_hook('send_sales_email'); // Schedule the event with the new send time wp_schedule_event($next_send_time, 'monthly', 'send_sales_email'); // Format the next scheduled time $next_scheduled_time = wp_date(get_option('date_format') . ' ' . get_option('time_format'), $next_send_time); // Display success message $success_message = sprintf('Settings saved. Next scheduled email: %s', $next_scheduled_time); woocommerce_sales_insights_log_event($success_message); echo '<div class="updated notice"><p>' . $success_message . '</p></div>'; } // Retrieve saved settings $email_addresses = get_option('woocommerce_sales_insights_email_addresses', ''); $send_time = get_option('woocommerce_sales_insights_send_time', '12:00 am'); $next_send_time = wp_next_scheduled('send_sales_email'); $next_scheduled_time = $next_send_time ? wp_date(get_option('date_format') . ' ' . get_option('time_format'), $next_send_time) : ''; // Display the settings page ?> <div class="wrap"> <h1>WooCommerce Sales Insights</h1> <form method="post"> <table class="form-table"> <tr> <th scope="row">Email addresses you want reply to be sent to</th> <td> <input type="text" name="email_addresses" value="<?php echo esc_attr($email_addresses); ?>" class="regular-text"> <p class="description">Enter comma-separated email addresses.</p> </td> </tr> <tr> <th scope="row">Receive the report at (monthly)</th> <td> <input type="time" name="send_time" value="<?php echo esc_attr($send_time); ?>" class="regular-text"> <p class="description">Enter the preferred time to receive the sales report.</p> </td> </tr> <tr> <th scope="row">The next email will be sent at</th> <td> <p><?php echo esc_html($next_scheduled_time); ?></p> </td> </tr> <tr> <th scope="row">Your website's current date and time is</th> <td> <p><?php echo wp_date('F j, Y g:i A'); ?></p> </td> </tr> </table> <p class="submit"><input type="submit" name="woocommerce_sales_insights_submit" class="button-primary" value="Save Settings"></p> </form> </div> <?php }
@extends('layouts.master') @section('content') <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-header align-items-center d-flex"> <h4 class="card-title mb-0 flex-grow-1">Add Inventory</h4> </div> <div class="card-body"> <form class="row needs-validation" action="{{ route('inventories.store') }}" method="POST" novalidate> @csrf <div class="col-md-6"> <div class="form-label-group in-border"> <label for="user_id" class="form-label">Products</label> <select id="myselect" class="form-select form-control mb-3 @if ($errors->has('product_id')) is-invalid @endif" name="product_id" required> <option value="" @if (old('product_id') == '') {{ 'selected' }} @endif selected disabled> Select One </option> @foreach ($products as $product) <option value="{{ $product->id }}" @if (old('product_id') == $product->id) {{ 'selected' }} @endif> {{ $product->name }} </option> @endforeach </select> <div class="invalid-tooltip">{{ $errors->first('product_id') }}</div> </div> </div> <div class="col-md-6 mb-3"> <div class="form-label-group in-border"> <label for="user_id" class="form-label">Units</label> <input type="number" class="form-control @if ($errors->has('units')) is-invalid @endif" id="units" name="units" placeholder="Units" value="{{ old('units') }}"> <div class="invalid-tooltip"> {{ $errors->first('units') }} </div> </div> </div> <div class="col-12 text-end"> <button class="btn btn-primary" type="submit">Save Changes</button> <a href="{{ route('inventories.index') }}" type="button" class="btn btn-light bg-gradient waves-effect waves-light">Cancel</a> </div> </form> </div> </div> </div> </div> @endsection
import 'package:flutter/material.dart'; import '../../../styles/app_color.dart'; import '../../../styles/app_icon.dart'; class CustomAppbar extends StatelessWidget { const CustomAppbar({super.key, required this.n}); final int n; @override Widget build(BuildContext context) { return Stack( children: [ Container( height: 400, width: double.infinity, decoration: const BoxDecoration( color: AppColor.customPink, borderRadius: BorderRadius.only( bottomLeft: Radius.circular(35), bottomRight: Radius.circular(35), ), ), child: Align( alignment: Alignment.topLeft, child: IconButton( onPressed: () => Navigator.pop(context), icon: const Icon( Icons.arrow_back_outlined, color: AppColor.white, size: 40, ), ), ), ), Container( margin: const EdgeInsets.only(top: 330, left: 40), height: 130, width: 300, decoration: const BoxDecoration( color: AppColor.white, borderRadius: BorderRadius.all( Radius.circular(15), ), boxShadow: [ BoxShadow( color: AppColor.shadowWhite, blurRadius: 4, ) ], ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Row( children: [ const Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image( height: 15, width: 15, image: AssetImage(AppIcon.trueIc), ), SizedBox( height: 30, ), ], ), const SizedBox( width: 10, ), Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "$n", style: const TextStyle( fontWeight: FontWeight.w500, color: AppColor.green, fontSize: 20, ), ), const Text( "Correct", style: TextStyle( fontWeight: FontWeight.w500, color: AppColor.black, fontSize: 21, ), ), ], ), ], ), Row( children: [ const Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image( height: 15, width: 15, image: AssetImage(AppIcon.falseIc), ), SizedBox( height: 30, ), ], ), const SizedBox( width: 10, ), Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "${10 - n}", style: const TextStyle( fontWeight: FontWeight.w500, color: AppColor.red, fontSize: 20, ), ), const Text( "Wrong", style: TextStyle( fontWeight: FontWeight.w500, color: AppColor.black, fontSize: 21, ), ), ], ), ], ), ], ), ), Center( child: Container( margin: const EdgeInsets.only(top: 80), height: 180, width: 180, decoration: const BoxDecoration( shape: BoxShape.circle, color: AppColor.white45, ), child: Container( margin: const EdgeInsets.all(15), decoration: const BoxDecoration( shape: BoxShape.circle, color: AppColor.white45, ), child: Container( margin: const EdgeInsets.all(15), decoration: const BoxDecoration( color: AppColor.white, shape: BoxShape.circle, boxShadow: [ BoxShadow( color: AppColor.shadowWhite, blurRadius: 4, ), ], ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "Your score", style: TextStyle( fontWeight: FontWeight.w500, fontSize: 20, color: AppColor.customPinkText, ), ), Text( "${n * 10} ", style: const TextStyle( fontWeight: FontWeight.w700, fontSize: 20, color: AppColor.customPinkText, ), ), ], ), ), ), ), ), ], ); } }
import { formatDuration } from 'date-fns'; import React, { PureComponent } from 'react'; import { SelectableValue, parseDuration } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { t } from '../../utils/i18n'; import { ButtonGroup } from '../Button'; import { ButtonSelect } from '../Dropdown/ButtonSelect'; import { ToolbarButtonVariant, ToolbarButton } from '../ToolbarButton'; // Default intervals used in the refresh picker component export const defaultIntervals = ['5s', '10s', '30s', '1m', '5m', '15m', '30m', '1h', '2h', '1d']; export interface Props { intervals?: string[]; onRefresh?: () => void; onIntervalChanged: (interval: string) => void; value?: string; tooltip?: string; isLoading?: boolean; isLive?: boolean; text?: string; noIntervalPicker?: boolean; showAutoInterval?: boolean; width?: string; primary?: boolean; isOnCanvas?: boolean; } export class RefreshPicker extends PureComponent<Props> { static offOption = { label: 'Off', value: '', ariaLabel: 'Turn off auto refresh', }; static liveOption = { label: 'Live', value: 'LIVE', ariaLabel: 'Turn on live streaming', }; static autoOption = { label: 'Auto', value: 'auto', ariaLabel: 'Select refresh from the query range', }; static isLive = (refreshInterval?: string): boolean => refreshInterval === RefreshPicker.liveOption.value; constructor(props: Props) { super(props); } onChangeSelect = (item: SelectableValue<string>) => { const { onIntervalChanged } = this.props; if (onIntervalChanged && item.value != null) { onIntervalChanged(item.value); } }; getVariant(): ToolbarButtonVariant { if (this.props.isLive) { return 'primary'; } if (this.props.primary) { return 'primary'; } return this.props.isOnCanvas ? 'canvas' : 'default'; } render() { const { onRefresh, intervals, tooltip, value, text, isLoading, noIntervalPicker, width, showAutoInterval } = this.props; const currentValue = value || ''; const variant = this.getVariant(); const options = intervalsToOptions({ intervals, showAutoInterval }); const option = options.find(({ value }) => value === currentValue); const translatedOffOption = translateOption(RefreshPicker.offOption.value); let selectedValue = option || translatedOffOption; if (selectedValue.label === translatedOffOption.label) { selectedValue = { value: '' }; } const durationAriaLabel = selectedValue.ariaLabel; const ariaLabelDurationSelectedMessage = t( 'refresh-picker.aria-label.duration-selected', 'Choose refresh time interval with current interval {{durationAriaLabel}} selected', { durationAriaLabel } ); const ariaLabelChooseIntervalMessage = t( 'refresh-picker.aria-label.choose-interval', 'Auto refresh turned off. Choose refresh time interval' ); const ariaLabel = selectedValue.value === '' ? ariaLabelChooseIntervalMessage : ariaLabelDurationSelectedMessage; const tooltipIntervalSelected = t('refresh-picker.tooltip.interval-selected', 'Set auto refresh interval'); const tooltipAutoRefreshOff = t('refresh-picker.tooltip.turned-off', 'Auto refresh off'); const tooltipAutoRefresh = selectedValue.value === '' ? tooltipAutoRefreshOff : tooltipIntervalSelected; return ( <ButtonGroup className="refresh-picker"> <ToolbarButton aria-label={text} tooltip={tooltip} onClick={onRefresh} variant={variant} icon={isLoading ? 'spinner' : 'sync'} style={width ? { width } : undefined} data-testid={selectors.components.RefreshPicker.runButtonV2} > {text} </ToolbarButton> {!noIntervalPicker && ( <ButtonSelect value={selectedValue} options={options} onChange={this.onChangeSelect} variant={variant} data-testid={selectors.components.RefreshPicker.intervalButtonV2} aria-label={ariaLabel} tooltip={tooltipAutoRefresh} /> )} </ButtonGroup> ); } } export function translateOption(option: string) { switch (option) { case RefreshPicker.liveOption.value: return { label: t('refresh-picker.live-option.label', 'Live'), value: option, ariaLabel: t('refresh-picker.live-option.aria-label', 'Turn on live streaming'), }; case RefreshPicker.offOption.value: return { label: t('refresh-picker.off-option.label', 'Off'), value: option, ariaLabel: t('refresh-picker.off-option.aria-label', 'Turn off auto refresh'), }; case RefreshPicker.autoOption.value: return { label: t('refresh-picker.auto-option.label', RefreshPicker.autoOption.label), value: option, ariaLabel: t('refresh-picker.auto-option.aria-label', RefreshPicker.autoOption.ariaLabel), }; } return { label: option, value: option, }; } export function intervalsToOptions({ intervals = defaultIntervals, showAutoInterval = false, }: { intervals?: string[]; showAutoInterval?: boolean } = {}): Array<SelectableValue<string>> { const options: Array<SelectableValue<string>> = intervals.map((interval) => { const duration = parseDuration(interval); const ariaLabel = formatDuration(duration); return { label: interval, value: interval, ariaLabel: ariaLabel, }; }); if (showAutoInterval) { options.unshift(translateOption(RefreshPicker.autoOption.value)); } options.unshift(translateOption(RefreshPicker.offOption.value)); return options; }
import { Body, Controller, Delete, HttpCode, Optional, Param, Post, Req, UploadedFile, UseGuards, UseInterceptors, } from '@nestjs/common'; import { CreatePlaylistDto } from './dto/create-playlist.dto'; import { PlaylistsService } from './playlists.service'; import { FileInterceptor } from '@nestjs/platform-express'; import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'; import { Roles } from '../auth/roles-auth.decorator'; import { RolesGuard } from '../auth/roles.guard'; import { Playlist } from './playlists.model'; import { AddSongToPlaylistDto } from './dto/add-song-to-playlist.dto'; import { Song } from '../songs/songs.model'; @ApiTags('Плейлисты') @Controller('playlists') export class PlaylistsController { constructor(private playlistService: PlaylistsService) {} @ApiOperation({ summary: 'Создание плейлиста' }) @ApiResponse({ status: 200, type: Playlist }) @Roles('USER') @UseGuards(RolesGuard) @Post() @UseInterceptors(FileInterceptor('image')) createPlaylist( @Body() dto: CreatePlaylistDto, @UploadedFile() @Optional() image, @Req() request, ): Promise<Playlist> { return this.playlistService.create(dto, image, request.user.id); } @ApiOperation({ summary: 'Добавление песни в плейлист' }) @ApiResponse({ status: 200, type: Song }) @Roles('USER') @UseGuards(RolesGuard) @Post('/adding') addSongToPlaylist(@Body() dto: AddSongToPlaylistDto): Promise<Song> { return this.playlistService.addSongToPlaylist(dto); } @ApiOperation({ summary: 'Удаление плейлиста' }) @ApiResponse({ status: 204 }) @Roles('USER') @UseGuards(RolesGuard) @Delete('/:value') @HttpCode(204) deletePlaylist(@Param('value') value: number, @Req() request): Promise<void> { return this.playlistService.delete(value, request.user.id); } }
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Hermes2018.Attributes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public class DependienteAttribute : ValidationAttribute, IClientModelValidator { private string _dependencia; private string[] _condicional; public DependienteAttribute(string dependencia, string[] condicional) { _dependencia = dependencia; _condicional = condicional; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var contenedorContexto = validationContext.ObjectInstance.GetType(); var campoDependiente = contenedorContexto.GetProperty(_dependencia); if (campoDependiente != null) { var valorDependiente = campoDependiente.GetValue(validationContext.ObjectInstance, null); if (_condicional.Contains(Convert.ToString(valorDependiente))) { if (string.IsNullOrEmpty(Convert.ToString(value))) { return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); } } } return ValidationResult.Success; } public void AddValidation(ClientModelValidationContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-dependiente", FormatErrorMessage(context.ModelMetadata.GetDisplayName())); MergeAttribute(context.Attributes, "data-val-dependiente-dependencia", _dependencia); } private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value) { if (attributes.ContainsKey(key)) { return false; } attributes.Add(key, value); return true; } } }
import React, { useEffect, useState } from 'react'; import { useAuth } from '../context/AuthContext'; import { useNavigate, Link } from 'react-router-dom'; import { Box, Button, chakra, Container, FormControl, FormLabel, HStack, Input, Stack, useToast, Image, Flex } from '@chakra-ui/react' import { FaGoogle } from 'react-icons/fa'; import DividerWithText from '../components/DividerWithText'; import Card from '../components/Card'; import useMounted from '../hooks/useMounted'; import Loading from '../components/Loading'; import { useStore } from '../hooks/useGlobalStore'; import Logo from '../assets/logo.png'; const Login: React.FC = () => { const navigate = useNavigate(); const toast = useToast() const mounted = useMounted() const { signInWithGoogle, login } = useAuth() const [email, setEmail] = useState<string>('') const [password, setPassword] = useState<string>('') const [isSubmitting, setIsSubmitting] = useState<boolean>(false) const { currentUser } = useStore(); useEffect(() => { goToPage(); }, []) useEffect(() => { goToPage(); }, [currentUser]) const goToPage = () => { if (currentUser?.uid && currentUser?.role) { navigate(`/`, { replace: false }) } } const submit = async (e: any) => { e.preventDefault() if (!email || !password) { return } setIsSubmitting(true) login(email, password) .catch(() => errorToast()) .finally(() => { mounted.current && setIsSubmitting(false) }) } const loginWithGoogle = () => { signInWithGoogle() .finally(() => { mounted.current && setIsSubmitting(false) }); } const errorToast = () => { toast({ description: "Nombre de usuario o contraseña incorrectos, por favor verifica e intenta nuevamente.", status: 'error', duration: 9000, isClosable: true, }) } return ( <> { isSubmitting ? ( <Loading /> ) : !currentUser.uid ? ( <Box mb={16} h={'80vh'}> <Container centerContent maxWidth={'440px'} w={'100%'} h={'100%'} > <Card mx='auto' my={'auto'} > <Container centerContent pt={'10px'} pb={'60px'} > <Image src={Logo} minW="188px" /> </Container> <chakra.form onSubmit={submit} > <Stack spacing='6'> <FormControl id='email'> <HStack> <FormLabel minW={85}>Email</FormLabel> <Input name='email' type='email' autoComplete='email' required value={email} onChange={e => setEmail(e.target.value)} w={210} /> </HStack> </FormControl> <FormControl id='password' minW={85}> <HStack> <FormLabel>Contraseña</FormLabel> <Input name='password' type='password' autoComplete='password' value={password} required onChange={e => setPassword(e.target.value)} w={210} /> </HStack> </FormControl> <Button type='submit' colorScheme='blue' bg='blue.700' size='lg' fontSize='md' isLoading={isSubmitting} > Ingresar </Button> </Stack> </chakra.form> <Flex my={4} justifyContent={'space-between'}> <Button variant='link'> <Link to='/forgot-password'>¿Olvidó su contraseña?</Link> </Button> <Button variant='link' onClick={() => navigate('/register')}> Registrarse </Button> </Flex> <DividerWithText my={6}>ó</DividerWithText> <Button variant='outline' width='100%' colorScheme='red' leftIcon={<FaGoogle />} onClick={loginWithGoogle} > Ingresar con Google </Button> </Card> </Container> </Box> ) : (<> </>) } </>) }; export default Login;
$("#image-selector").change(function () { let reader = new FileReader(); reader.onload = function () { let dataURL = reader.result; $("#selected-image").attr("src", dataURL); $("#prediction-list").empty(); }; let file = $("#image-selector").prop("files")[0]; reader.readAsDataURL(file); }); let model; $(document).ready(async function () { $(".progress-bar").show(); console.log("Loading model..."); model = await tf.loadLayersModel("model/model.json"); console.log("Model loaded."); $(".progress-bar").hide(); }); $("#predict-button").click(async function () { let image = $("#selected-image").get(0); // Pre-procesamos la imagen let tensor = tf.browser .fromPixels(image) .resizeNearestNeighbor([96, 96]) // cambiamos las dismensiones .toFloat() .div(tf.scalar(255.0)) .expandDims(); let predictions = await model.predict(tensor).data(); let top5 = Array.from(predictions) .map(function (p, i) { return { probability: p, className: TARGET_CLASSES[i], // seleccionamos el valor del objeto }; }) .sort(function (a, b) { return b.probability - a.probability; }) .slice(0, 5); $("#prediction-list").empty(); top5.forEach(function (p) { $("#prediction-list").append( `<li>${p.className}: ${p.probability.toFixed(6)}</li>` ); }); });
(function e(t, n, r) { function s(o, u) { if (!n[o]) { if (!t[o]) { var a = typeof require == 'function' && require; if (!u && a) return a(o, !0); if (i) return i(o, !0); var f = new Error("Cannot find module '" + o + "'"); throw ((f.code = 'MODULE_NOT_FOUND'), f); } var l = (n[o] = { exports: {} }); t[o][0].call( l.exports, function(e) { var n = t[o][1][e]; return s(n ? n : e); }, l, l.exports, e, t, n, r ); } return n[o].exports; } var i = typeof require == 'function' && require; for (var o = 0; o < r.length; o++) s(r[o]); return s; })( { 1: [ function(require, module, exports) { const bodyScrollLock = require('../../lib/bodyScrollLock.js'); const disableBodyScrollButton = document.querySelector('.disableBodyScroll'); const enableBodyScrollButton = document.querySelector('.enableBodyScroll'); const statusElement = document.querySelector('.bodyScrollLockStatus'); disableBodyScrollButton.onclick = function() { console.info('disableBodyScrollButton'); bodyScrollLock.disableBodyScroll(document.querySelector('.scrollTarget')); statusElement.innerHTML = ' &mdash; Scroll Locked'; statusElement.style.color = 'red'; }; enableBodyScrollButton.onclick = function() { console.info('enableBodyScrollButton'); bodyScrollLock.enableBodyScroll(document.querySelector('.scrollTarget')); statusElement.innerHTML = ' &mdash; Scroll Unlocked'; statusElement.style.color = ''; }; }, { '../../lib/bodyScrollLock.js': 2 }, ], 2: [ function(require, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true, }); var _slicedToArray = (function() { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); // Adopted and modified solution from Bohdan Didukh (2017) // https://stackoverflow.com/questions/41594997/ios-10-safari-prevent-scrolling-behind-a-fixed-overlay-and-maintain-scroll-posi var isIosDevice = typeof window !== 'undefined' && window.navigator && window.navigator.platform && /iPad|iPhone|iPod|(iPad Simulator)|(iPhone Simulator)|(iPod Simulator)/.test(window.navigator.platform); var firstTargetElement = null; var allTargetElements = {}; var initialClientY = -1; var previousBodyOverflowSetting = ''; var previousDocumentElementOverflowSetting = ''; var preventDefault = function preventDefault(rawEvent) { var e = rawEvent || window.event; if (e.preventDefault) e.preventDefault(); return false; }; var setOverflowHidden = function setOverflowHidden() { // Setting overflow on body/documentElement synchronously in Desktop Safari slows down // the responsiveness for some reason. Setting within a setTimeout fixes this. setTimeout(function() { previousBodyOverflowSetting = document.body.style.overflow; previousDocumentElementOverflowSetting = document.documentElement.style.overflow; document.body.style.overflow = 'hidden'; document.documentElement.style.overflow = 'hidden'; }); }; var setOverflowAuto = function setOverflowAuto() { // Setting overflow on body/documentElement synchronously in Desktop Safari slows down // the responsiveness for some reason. Setting within a setTimeout fixes this. setTimeout(function() { document.body.style.overflow = previousBodyOverflowSetting; document.documentElement.style.overflow = previousDocumentElementOverflowSetting; }); }; // https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Problems_and_solutions var isTargetElementTotallyScrolled = function isTargetElementTotallyScrolled(targetElement) { return targetElement ? targetElement.scrollHeight - targetElement.scrollTop <= targetElement.clientHeight : false; }; var handleScroll = function handleScroll(event, targetElement) { var clientY = event.targetTouches[0].clientY - initialClientY; if (targetElement && targetElement.scrollTop === 0 && clientY > 0) { // element is at the top of its scroll return preventDefault(event); } if (isTargetElementTotallyScrolled(targetElement) && clientY < 0) { // element is at the top of its scroll return preventDefault(event); } return true; }; var disableBodyScroll = (exports.disableBodyScroll = function disableBodyScroll(targetElement) { if (isIosDevice) { if (targetElement) { allTargetElements[targetElement] = targetElement; targetElement.ontouchstart = function(event) { if (event.targetTouches.length === 1) { // detect single touch initialClientY = event.targetTouches[0].clientY; } }; targetElement.ontouchmove = function(event) { if (event.targetTouches.length === 1) { // detect single touch handleScroll(event, targetElement); } }; } } else { setOverflowHidden(); } if (!firstTargetElement) firstTargetElement = targetElement; }); var clearAllBodyScrollLocks = (exports.clearAllBodyScrollLocks = function clearAllBodyScrollLocks() { if (isIosDevice) { // Clear all allTargetElements ontouchstart/ontouchmove handlers, and the references Object.entries(allTargetElements).forEach(function(_ref) { var _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], targetElement = _ref2[1]; targetElement.ontouchstart = null; targetElement.ontouchmove = null; delete allTargetElements[key]; }); // Reset initial clientY initialClientY = -1; } else { setOverflowAuto(); firstTargetElement = null; } }); var enableBodyScroll = (exports.enableBodyScroll = function enableBodyScroll(targetElement) { if (isIosDevice) { targetElement.ontouchstart = null; targetElement.ontouchmove = null; } else if (firstTargetElement === targetElement) { setOverflowAuto(); firstTargetElement = null; } }); }, {}, ], }, {}, [1] );
import { useState, useEffect } from 'react'; import BadHabit from './BadHabit'; const API = import.meta.env.VITE_API_URL; const BadHabits = () => { const [badHabits, setBadHabits] = useState([]); useEffect(() => { fetch(`${API}/badHabits`) .then((response) => response.json()) .then((responseJSON) => { console.log(responseJSON); setBadHabits(responseJSON.data.payload); }) .catch((error) => console.log(error)); }, []); return ( <div className='bad-habits'> <h1>My Bad Habits</h1> <ul className='bad-habits-list'> {badHabits.map((badHabit) => ( <BadHabit key={badHabit.id} badHabit={badHabit} /> ))} </ul> </div> ); }; export default BadHabits;
import Image from 'next/image'; import karta from '../../public/images/karta.jpg'; import Link from 'next/link'; import { calcSumFromBudget } from '@/lib/calc-sum-from-budget'; export default function RequestItem(props) { if (!props.request) { return; } return ( <> <Link href={`/management/supplier/supplier-requests/${props.groupId}`} shallow > <div className="bg-orange rounded-2xl w-fit h-full p-5 shadow-lg shadow-gray-200 border-2 border-gray-200 transition ease-in-out delay-150 hover:-translate-y-1 hover:scale-110 duration-300"> <h2 className="text-xl font-bold flex justify-center"> {props.request.request_metadata?.marking} </h2> <div className="bg-white w-40 h-20 my-3 flex justify-center rounded-lg"> <Image src={karta} alt="Map"></Image> </div> <p className="text-sm"> <span className="font-semibold"> {props.request.request_items.length} </span>{' '} {props.request.request_items.length > 1 ? 'Artiklar' : 'Artikel'} </p> <p className="text-sm"> Ordervärde: {calcSumFromBudget(props.request.request_items)} SEK </p> <div className="mt-5"> <u className="no-underline text-xs text-zinc-700"> <li>{props.request.delivery[0].city}</li> <li>{props.request.delivery[0].deliveryType}</li> <li>EF 1-5 anställda</li> </u> </div> </div> </Link> </> ); }
<script lang="ts" setup> import DateDisplay from './DateDisplay.vue' import UseEmojis from '@/composables/UseEmojis' import type Entry from '@/types/Entry' import { userInjectionKey } from '@/injectionKeys' import { inject } from 'vue' defineProps<{ entry: Entry }>() const user = inject(userInjectionKey) const { findEmoji } = UseEmojis() </script> <template> <div class="entry-card"> <div class="entry-card-body"> <component width="75" :is="findEmoji(entry.emoji)"></component> <div class="entry-text">{{ entry.body }}</div> </div> <div class="entry-footer"> <DateDisplay :date="entry.createdAt" class="mr-2" /> | <span class="ml-2">{{ user?.username || 'anonymous' }}</span> </div> </div> </template>
/******************************************************************************* * Copyright 2018 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package group import ( groupsSearchmocks "controller/search/group/mocks" "encoding/json" "github.com/golang/mock/gomock" "net/http" "net/http/httptest" "strings" "testing" ) var Handler Command func init() { Handler = RequestHandler{} } func TestSearchGroupsHandleWithInvalidMethod_ExpectReturnInvalidMethodMsg(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() searchMockObj := groupsSearchmocks.NewMockCommand(ctrl) w := httptest.NewRecorder() req, _ := http.NewRequest("POST", "/api/v1/search/groups", nil) // pass mockObj to a real object. searchExecutor = searchMockObj Handler.Handle(w, req) msg := make(map[string]interface{}) err := json.Unmarshal(w.Body.Bytes(), &msg) if err != nil { t.Error("Expected results : invalid method msg, Actual err : json unmarshal failed.") } if !strings.Contains(msg["message"].(string), "invalid method") { t.Errorf("Expected results : invalid method msg, Actual err : %s.", msg["message"]) } w = httptest.NewRecorder() req, _ = http.NewRequest("DELETE", "/api/v1/search/groups", nil) // pass mockObj to a real object. searchExecutor = searchMockObj Handler.Handle(w, req) msg = make(map[string]interface{}) err = json.Unmarshal(w.Body.Bytes(), &msg) if err != nil { t.Error("Expected results : invalid method msg, Actual err : json unmarshal failed.") } if !strings.Contains(msg["message"].(string), "invalid method") { t.Errorf("Expected results : invalid method msg, Actual err : %s.", msg["message"]) } } func TestSearchGroupsHandleWithValidGroupsSearchRequest_ExpectCalledGroupsSearchController(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() searchMockObj := groupsSearchmocks.NewMockCommand(ctrl) gomock.InOrder( searchMockObj.EXPECT().SearchGroups(gomock.Any()), ) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/search/groups", nil) // pass mockObj to a real object. searchExecutor = searchMockObj Handler.Handle(w, req) }
<script setup> import { useUsersStore } from "./stores/users"; const usersStore = useUsersStore(); </script> <template> <div v-if="user_id > 0"> <router-view /> </div> <div v-else> <div class="all_user" v-for="(user, index) in usersStore.users" :key="index" > <router-link @click="user_id = Number(user.id)" :to="{ name: 'user_page', params: { id: user.id } }" > <form class="user_card" onclick=" window.scrollTo(0, 0);"> <img id="cat_img" style="border-radius: 50%; border-color: white" border="10vh" src="../assets/cat.png" /> <div class="info" style="padding-top: 5vh; text-align: left; text-decoration: none" > <div id="main_info"> Name: {{ user.name }} <br /> Username: {{ user.username }} <br /> Email: {{ user.email }} <br /> </div> Phone: {{ user.phone }} <br /> Website: {{ user.website }} <br /> <div class="buttons"> <router-link @click="user_id = Number(user.id)" :to="{ name: 'user_posts', params: { id: user.id } }" > <button class="posts">User's posts</button> </router-link> <router-link @click="user_id = Number(user.id)" :to="{ name: 'user_photos', params: { id: user.id } }" > <button class="photos">User's albums</button> </router-link> </div> </div> </form> <img id="ears" src="../assets/ears.png" /> <img id="vibris_left1" src="../assets/vibris.png" /> <img id="vibris_left2" src="../assets/vibris.png" /> <img id="vibris_left3" src="../assets/vibris.png" /> <img id="vibris_rigth1" src="../assets/vibris2.png" /> <img id="vibris_rigth2" src="../assets/vibris2.png" /> <img id="vibris_rigth3" src="../assets/vibris2.png" /> </router-link> </div> </div> </template> <script> export default { name: "UserList", data() { return { user_id: -1, usersObj: useUsersStore(), }; }, beforeMount() { this.usersObj.getUsers(); }, }; </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> .buttons { position: absolute; bottom: 0.5vh; display: flex; flex-wrap: nowrap; align-content: center; justify-content: space-between; align-items: center; width: 23vw; } .posts, .photos { background-color: #ffffff; border: 0; width: 11vw; padding: 1vw; font-family: Museo; border-radius: 10px; box-shadow: none; background-color: rgb(255, 171, 198); } .posts:hover, .photos:hover{ animation-name: light; animation-duration: 0.325s; } @keyframes light { 0% { background-color: rgb(255, 171, 198); } 15% { background-image: linear-gradient(45deg, rgb(255, 171, 198) 80%,rgb(255, 195, 214) 90%); } 40% { background-image: linear-gradient(45deg, rgb(255, 171, 198) 40%,rgb(255, 195, 214) 50%, rgb(255, 171, 198) 60%,rgb(255, 207, 222) 90%); } 60% { background-image: linear-gradient(45deg, rgb(255, 195, 214) 10%, rgb(255, 171, 198) 15%, rgb(255, 171, 198) 20%,rgb(255, 207, 222) 50%, rgb(255, 171, 198) 80%); } 80% { background-image: linear-gradient(45deg, rgb(255, 207, 222) 10%, rgb(255, 171, 198) 40%); } 100% { background-color: rgb(255, 171, 198); } } .user_card { filter: grayscale(80%); position: relative; z-index: 5; } #cat_img { height: 12vh; } .user_card img { margin-bottom: 3vh; } .user_card:hover { filter: none; } #ears { width: 24.84%; height: 30vh; position: absolute; left: 37.58%; margin-top: -50vh; z-index: 1; filter: grayscale(80%); transition-property: margin-top; transition-duration: 0.3s; } #vibris_rigth1, #vibris_rigth2, #vibris_rigth3, #vibris_left1, #vibris_left2, #vibris_left3 { width: 15%; position: absolute; z-index: 1; transition-property: left, transform; transform: rotate(25deg); left: 38%; } #vibris_rigth1, #vibris_rigth2, #vibris_rigth3 { transform: rotate(-10deg); left: 50%; } #vibris_left1, #vibris_rigth1 { width: 15%; margin-top: -50vh; transition-duration: 0.5s; } #vibris_left2, #vibris_rigth2 { width: 14%; margin-top: -48vh; transition-duration: 0.7s; } #vibris_left3, #vibris_rigth3 { width: 12%; margin-top: -46vh; transition-duration: 1s; } .user_card:hover ~ #ears { margin-top: -78vh; filter: none; } .user_card:hover ~ #vibris_left1 { transform: rotate(-5deg); left: 28%; } .user_card:hover ~ #vibris_left2 { transform: rotate(-5deg); left: 30%; } .user_card:hover ~ #vibris_left3 { transform: rotate(-5deg); left: 32.5%; } .user_card:hover ~ #vibris_rigth1 { transform: rotate(5deg); left: 58%; } .user_card:hover ~ #vibris_rigth2 { transform: rotate(5deg); left: 57%; } .user_card:hover ~ #vibris_rigth3 { transform: rotate(5deg); left: 56.5%; } @media only screen and (max-width: 768px) { #cat_img { height: 11vh; } .user_card { filter: none; } #vibris_rigth1, #vibris_rigth2, #vibris_rigth3, #vibris_left1, #vibris_left2, #vibris_left3 { display: none; } #ears { width: 76vw; left: 12vw; filter: none; margin-top: -69vh; } .user_card:hover ~ #ears { margin-top: -59.7vh; } .posts, .photos { width: 20vw; margin-left: 10vw; } .buttons { width: 100vw; justify-content:flex-start; bottom: -1vw; } } @media only screen and (min-width: 430px) and (max-width: 768px) { #vibris_rigth1, #vibris_rigth2, #vibris_rigth3, #vibris_left1, #vibris_left2, #vibris_left3 { transform: rotate(0); display: block; } #ears { margin-top: -68vw; width: 50%; left: 25%; } #vibris_left1, .user_card:hover ~ #vibris_left1 { transform: rotate(0); left: 1%; } #vibris_left2, .user_card:hover ~ #vibris_left2 { left: 2.5%; rotate: (15deg); } #vibris_left3, .user_card:hover ~ #vibris_left3 { left: 4%; rotate: (35deg); } #vibris_rigth1, .user_card:hover ~ #vibris_rigth1 { left: 85%; } #vibris_rigth2, .user_card:hover ~ #vibris_rigth2 { left: 84.5%; rotate: (-15deg); } #vibris_rigth3, .user_card:hover ~ #vibris_rigth3 { left: 84%; rotate: (-35deg); } #vibris_left1, #vibris_rigth1 { width: 15%; margin-top: -47vw; } #vibris_left2, #vibris_rigth2 { width: 14%; margin-top: -45.5vw; } #vibris_left3, #vibris_rigth3 { width: 12%; margin-top: -44vw; } .user_card:hover ~ #ears { margin-top: -70vw; } } @media only screen and (min-width: 430px) and (max-width: 768px) { .buttons { width: fit-content; justify-content:flex-end; } .user_card:hover ~ #ears { margin-top: -68vw; } .posts, .photos { margin-left: 2vw; width: 30vw; padding: 2vw; } } @media only screen and (max-width: 430px) { .user_card { height: 50vh; } } </style>
from pathlib import Path from subprocess import PIPE, Popen import pytest from mtap import Pipeline, RemoteProcessor, events_client from mtap.serialization import PickleSerializer from mtap.utilities import find_free_port from biomedicus import java_support @pytest.fixture(name='normalization_processor') def fixture_normalization_processor(events_service, processor_watcher, processor_timeout): port = str(find_free_port()) address = '127.0.0.1:' + port with java_support.create_call( 'edu.umn.biomedicus.normalization.NormalizationProcessor', '-p', port, '--events', events_service ) as call: p = Popen(call, start_new_session=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) yield from processor_watcher(address, p, timeout=processor_timeout) @pytest.mark.integration def test_normalization(events_service, normalization_processor): pipeline = Pipeline(RemoteProcessor( name='biomedicus_normalizer', address=normalization_processor), events_address=events_service ) with events_client(events_service) as client: with PickleSerializer.file_to_event(Path(__file__).parent / '97_95.pickle', client=client) as event: document = event.documents['plaintext'] pipeline.run(document) for norm_form in document.labels['norm_forms']: if norm_form.text == "according": assert norm_form.norm == "accord" if norm_form.text == "expressing": assert norm_form.norm == "express" if norm_form.text == "receiving": assert norm_form.norm == "receive" if norm_form.text == "days": assert norm_form.norm == "day"
NAME Crypt::JWT - JSON Web Token (JWT, JWS, JWE) as defined by RFC7519, RFC7515, RFC7516 SYNOPSIS # encoding use Crypt::JWT qw(encode_jwt); my $jws_token = encode_jwt(payload=>$data, alg=>'HS256', key=>'secret'); my $jwe_token = encode_jwt(payload=>$data, alg=>'PBES2-HS256+A128KW', enc=>'A128GCM', key=>'secret'); # decoding use Crypt::JWT qw(decode_jwt); my $data1 = decode_jwt(token=>$jws_token, key=>'secret'); my $data2 = decode_jwt(token=>$jwe_token, key=>'secret'); DESCRIPTION Implements JSON Web Token (JWT) - <https://tools.ietf.org/html/rfc7519>. The implementation covers not only JSON Web Signature (JWS) - <https://tools.ietf.org/html/rfc7515>, but also JSON Web Encryption (JWE) - <https://tools.ietf.org/html/rfc7516>. The module implements all (100%) algorithms defined in <https://tools.ietf.org/html/rfc7518> - JSON Web Algorithms (JWA). EXPORT Nothing is exported by default. You can export selected functions: use Crypt::JWT qw(decode_jwt encode_jwt); Or all of them at once: use Crypt::JWT ':all'; FUNCTIONS decode_jwt my $data = decode_jwt(%named_args); Named arguments: token Mandatory argument, a string with either JWS or JWE JSON Web Token. ### JWS token example (3 segments) $t = "eyJhbGciOiJIUzI1NiJ9.dGVzdA.ujBihtLSr66CEWqN74SpLUkv28lra_CeHnxLmLNp4Jo"; my $data = decode_jwt(token=>$t, key=>$k); ### JWE token example (5 segments) $t = "eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiQTEyOEtXIn0.UusxEbzhGkORxTRq0xkFKhvzPrXb9smw.VGfOuq0Fxt6TsdqLZUpnxw.JajIQQ.pkKZ7MHS0XjyGmRsqgom6w"; my $data = decode_jwt(token=>$t, key=>$k); key A key used for token decryption (JWE) or token signature validation (JWS). The value depends on "alg" token header value. JWS alg header key value ------------------ ---------------------------------- none no key required HS256 string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct') HS384 dtto HS512 dtto RS256 public RSA key, perl HASH ref with JWK key structure, a reference to SCALAR string with PEM or DER or JSON/JWK data, object: Crypt::PK::RSA, Crypt::OpenSSL::RSA, Crypt::X509 or Crypt::OpenSSL::X509 RS384 public RSA key, see RS256 RS512 public RSA key, see RS256 PS256 public RSA key, see RS256 PS384 public RSA key, see RS256 PS512 public RSA key, see RS256 ES256 public ECC key, perl HASH ref with JWK key structure, a reference to SCALAR string with PEM or DER or JSON/JWK data, an instance of Crypt::PK::ECC ES384 public ECC key, see ES256 ES512 public ECC key, see ES256 JWE alg header key value ------------------ ---------------------------------- dir string (raw octects) or perl HASH ref with JWK, kty=>'oct', length depends on 'enc' algorithm A128KW string (raw octects) 16 bytes (or perl HASH ref with JWK, kty=>'oct') A192KW string (raw octects) 24 bytes (or perl HASH ref with JWK, kty=>'oct') A256KW string (raw octects) 32 bytes (or perl HASH ref with JWK, kty=>'oct') A128GCMKW string (raw octects) 16 bytes (or perl HASH ref with JWK, kty=>'oct') A192GCMKW string (raw octects) 24 bytes (or perl HASH ref with JWK, kty=>'oct') A256GCMKW string (raw octects) 32 bytes (or perl HASH ref with JWK, kty=>'oct') PBES2-HS256+A128KW string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct') PBES2-HS384+A192KW string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct') PBES2-HS512+A256KW string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct') RSA-OAEP private RSA key, perl HASH ref with JWK key structure, a reference to SCALAR string with PEM or DER or JSON/JWK data, an instance of Crypt::PK::RSA or Crypt::OpenSSL::RSA RSA-OAEP-256 private RSA key, see RSA-OAEP RSA1_5 private RSA key, see RSA-OAEP ECDH-ES private ECC key, perl HASH ref with JWK key structure, a reference to SCALAR string with PEM or DER or JSON/JWK data, an instance of Crypt::PK::ECC ECDH-ES+A128KW private ECC key, see ECDH-ES ECDH-ES+A192KW private ECC key, see ECDH-ES ECDH-ES+A256KW private ECC key, see ECDH-ES Examples with raw octect keys: #string my $data = decode_jwt(token=>$t, key=>'secretkey'); #binary key my $data = decode_jwt(token=>$t, key=>pack("H*", "788A6E38F36B7596EF6A669E94")); #pel HASH ref with JWK structure (key type 'oct') my $data = decode_jwt(token=>$t, key=>{kty=>'oct', k=>"GawgguFyGrWKav7AX4VKUg"}); Examples with RSA keys: my $pem_key_string = <<'EOF'; -----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCoVm/Sl5r+Ofky jioRSZK26GW6WyjyfWKddsSi13/NOtCn0rRErSF/u3QrgGMpWFqKohqbi1VVC+SZ ... 8c1vm2YFafgdkSk9Qd1oU2Fv1aOQy4VovOFzJ3CcR+2r7cbRfcpLGnintHtp9yek 02p+d5g4OChfFNDhDtnIqjvY -----END PRIVATE KEY----- EOF my $jwk_key_json_string = '{"kty":"RSA","n":"0vx7agoebG...L6tSoc_BJECP","e":"AQAB"}'; #a reference to SCALAR string with PEM or DER or JSON/JWK data, my $data = decode_jwt(token=>$t, key=>\$pem_key_string); my $data = decode_jwt(token=>$t, key=>\$der_key_string); my $data = decode_jwt(token=>$t, key=>\$jwk_key_json_string); #instance of Crypt::PK::RSA my $data = decode_jwt(token=>$t, key=>Crypt::PK::RSA->new('keyfile.pem')); my $data = decode_jwt(token=>$t, key=>Crypt::PK::RSA->new(\$pem_key_string)); #instance of Crypt::OpenSSL::RSA my $data = decode_jwt(token=>$t, key=>Crypt::OpenSSL::RSA->new_private_key($pem_key_string)); #instance of Crypt::X509 (public key only) my $data = decode_jwt(token=>$t, key=>Crypt::X509->new(cert=>$cert)); #instance of Crypt::OpenSSL::X509 (public key only) my $data = decode_jwt(token=>$t, key=>Crypt::OpenSSL::X509->new_from_file('cert.pem')); my $data = decode_jwt(token=>$t, key=>Crypt::OpenSSL::X509->new_from_string($cert)); #pel HASH ref with JWK structure (key type 'RSA') my $rsa_priv = { kty => "RSA", n => "0vx7agoebGcQSuuPiLJXZpt...eZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw", e => "AQAB", d => "X4cTteJY_gn4FYPsXB8rdXi...FLN5EEaG6RoVH-HLKD9Mdx5ooGURknhnrRwUkC7h5fJLMWbFAKLWY2v7B6NqSzUvx0_YSf", p => "83i-7IvMGXoMXCskv73TKr8...Z27zvoj6pbUQyLPBQxtPnwD20-60eTmD2ujMt5PoMrm8RmNhVWtjjMmMjOpSicFHjXOuVI", q => "3dfOR9cuYq-0S-mkFLzgItg...q3hWeMuG0ouqnb3obLyuqjVZQ1dIrdgTnCdYzBcOW5r37AFXjift_NGiovonzhKpoVVS78", dp => "G4sPXkc6Ya9y8oJW9_ILj4...zi_H7TkS8x5SdX3oE0oiYwxIiemTAu0UOa5pgFGyJ4c8t2VF40XRugKTP8akhFo5tA77Qe", dq => "s9lAH9fggBsoFR8Oac2R_E...T2kGOhvIllTE1efA6huUvMfBcpn8lqW6vzzYY5SSF7pMd_agI3G8IbpBUb0JiraRNUfLhc", qi => "GyM_p6JrXySiz1toFgKbWV...4ypu9bMWx3QJBfm0FoYzUIZEVEcOqwmRN81oDAaaBk0KWGDjJHDdDmFW3AN7I-pux_mHZG", }; my $data = decode_jwt(token=>$t, key=>$rsa_priv}); Examples with ECC keys: my $pem_key_string = <<'EOF'; -----BEGIN EC PRIVATE KEY----- MHcCAQEEIBG1c3z52T8XwMsahGVdOZWgKCQJfv+l7djuJjgetdbDoAoGCCqGSM49 AwEHoUQDQgAEoBUyo8CQAFPeYPvv78ylh5MwFZjTCLQeb042TjiMJxG+9DLFmRSM lBQ9T/RsLLc+PmpB1+7yPAR+oR5gZn3kJQ== -----END EC PRIVATE KEY----- EOF my $jwk_key_json_string = '{"kty":"EC","crv":"P-256","x":"MKB..7D4","y":"4Et..FyM"}'; #a reference to SCALAR string with PEM or DER or JSON/JWK data, my $data = decode_jwt(token=>$t, key=>\$pem_key_string); my $data = decode_jwt(token=>$t, key=>\$der_key_string); my $data = decode_jwt(token=>$t, key=>\$jwk_key_json_string); #instance of Crypt::PK::ECC my $data = decode_jwt(token=>$t, key=>Crypt::PK::ECC->new('keyfile.pem')); my $data = decode_jwt(token=>$t, key=>Crypt::PK::ECC->new(\$pem_key_string)); #pel HASH ref with JWK structure (key type 'RSA') my $ecc_priv = { kty => "EC", crv => "P-256", x => "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", y => "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", d => "870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE", }; my $data = decode_jwt(token=>$t, key=>$ecc_priv}); keypass When 'key' parameter is an encrypted private RSA or ECC key this optional parameter may contain a password for private key decryption. kid_keys This parametes can be either a JWK Set JSON string (see RFC7517) or a perl HASH ref with JWK Set structure like this: my $keylist = { keys => [ { kid=>"key1", kty=>"oct", k=>"GawgguFyGrWKav7AX4VKUg" }, { kid=>"key2", kty=>"oct", k=>"ulxLGy4XqhbpkR5ObGh1gX" }, ] }; my $payload = decode_jwt(token=>$t, kid_keys=>$keylist); When the token header contains 'kid' item the corresponding key is looked up in "kid_keys" list and used for token decoding (you do not need to pass the explicit key via "key" parameter). allow_none 1 - accept JWS tokens with "none" 'alg' header value (which means that token has no signature), BEWARE: DANGEROUS, UNSECURE!!! 0 (default) - do not allow JWS with "none" 'alg' header value ignore_signature 1 - do not check signature on JWS tokens, BEWARE: DANGEROUS, UNSECURE!!! 0 (default) - check signature on JWS tokens accepted_alg "undef" (default) means accept all 'alg' algorithms except 'none' (for accepting 'none' use "allow_none") "string" name of accepted 'alg' algorithm (only one) "ARRAY ref" a list of accepted 'alg' algorithms "Regexp" that has to match 'alg' algorithm name my $payload = decode_jwt(token=>$t, key=>$k, accepted_enc=>'HS256'); #or my $payload = decode_jwt(token=>$t, key=>$k, accepted_enc=>['HS256','HS384']); #or my $payload = decode_jwt(token=>$t, key=>$k, accepted_enc=>qr/^HS(256|384|512)$/); accepted_enc "undef" (default) means accept all 'enc' algorithms "string" name of accepted 'enc' algorithm (only one) "ARRAY ref" a list of accepted 'enc' algorithms "Regexp" that has to match 'enc' algorithm name my $payload = decode_jwt(token=>$t, key=>$k, accepted_enc=>'A192GCM'); #or my $payload = decode_jwt(token=>$t, key=>$k, accepted_enc=>['A192GCM','A256GCM']); #or my $payload = decode_jwt(token=>$t, key=>$k, accepted_enc=>qr/^A(128|192|256)GCM$/); decode_payload 0 - do not decode payload, return it as a raw string (octects). 1 - decode payload from JSON string, return it as perl hash ref (or array ref) - decode_json failure means fatal error (croak). "undef" (default) - if possible decode payload from JSON string, if decode_json fails return payload as a raw string (octets). decode_header 0 (default) - do not return decoded header as a return value of decode_jwt() 1 - return decoded header as a return value of decode_jwt() my $payload = decode_jwt(token=>$t, key=>$k); #or my ($header, $payload) = decode_jwt(token=>$t, key=>$k, decode_header=>1); verify_iss "CODE ref" - subroutine (with 'iss' claim value passed as argument) should return "true" otherwise verification fails "Regexp ref" - 'iss' claim value has to match given regexp otherwise verification fails "undef" (default) - do not verify 'iss' claim verify_aud "CODE ref" - subroutine (with 'aud' claim value passed as argument) should return "true" otherwise verification fails "Regexp ref" - 'aud' claim value has to match given regexp otherwise verification fails "undef" (default) - do not verify 'aud' claim verify_sub "CODE ref" - subroutine (with 'sub' claim value passed as argument) should return "true" otherwise verification fails "Regexp ref" - 'sub' claim value has to match given regexp otherwise verification fails "undef" (default) - do not verify 'sub' claim verify_jti "CODE ref" - subroutine (with 'jti' claim value passed as argument) should return "true" otherwise verification fails "Regexp ref" - 'jti' claim value has to match given regexp otherwise verification fails "undef" (default) - do not verify 'jti' claim verify_iat "undef" - Issued At 'iat' claim must be valid (not in the future) if present 0 (default) - ignore 'iat' claim 1 - require valid 'iat' claim verify_nbf "undef" (default) - Not Before 'nbf' claim must be valid if present 0 - ignore 'nbf' claim 1 - require valid 'nbf' claim verify_exp "undef" (default) - Expiration Time 'exp' claim must be valid if present 0 - ignore 'exp' claim 1 - require valid 'exp' claim leeway Tolerance in seconds related to "verify_exp", "verify_nbf" and "verify_iat". Default is 0. ignore_claims 1 - do not check claims (iat, exp, nbf, iss, aud, sub, jti), BEWARE: DANGEROUS, UNSECURE!!! 0 (default) - check claims encode_jwt my $token = encode_jwt(%named_args); Named arguments: payload Value of this mandatory parameter can be a string/buffer or HASH ref or ARRAY ref my $token = encode_jwt(payload=>"any raw data", key=>$k, alg=>'HS256'); #or my $token = encode_jwt(payload=>{a=>1,b=>2}, key=>$k, alg=>'HS256'); #or my $token = encode_jwt(payload=>[11,22,33,44], key=>$k, alg=>'HS256'); HASH refs and ARRAY refs payloads are serialized as JSON strings alg The 'alg' header value is mandatory for both JWE and JWS tokens. Supported JWE 'alg' algorithms: dir A128KW A192KW A256KW A128GCMKW A192GCMKW A256GCMKW PBES2-HS256+A128KW PBES2-HS384+A192KW PBES2-HS512+A256KW RSA-OAEP RSA-OAEP-256 RSA1_5 ECDH-ES+A128KW ECDH-ES+A192KW ECDH-ES+A256KW ECDH-ES Supported JWS algorithms: none ... no integrity (NOTE: disabled by default) HS256 ... HMAC+SHA256 integrity HS384 ... HMAC+SHA384 integrity HS512 ... HMAC+SHA512 integrity RS256 ... RSA+PKCS1-V1_5 + SHA256 signature RS384 ... RSA+PKCS1-V1_5 + SHA384 signature RS512 ... RSA+PKCS1-V1_5 + SHA512 signature PS256 ... RSA+PSS + SHA256 signature PS384 ... RSA+PSS + SHA384 signature PS512 ... RSA+PSS + SHA512 signature ES256 ... ECDSA + SHA256 signature ES384 ... ECDSA + SHA384 signature ES512 ... ECDSA + SHA512 signature enc The 'enc' header is mandatory for JWE tokens. Supported 'enc' algorithms: A128GCM A192GCM A256GCM A128CBC-HS256 A192CBC-HS384 A256CBC-HS512 key A key used for token encryption (JWE) or token signing (JWS). The value depends on "alg" token header value. JWS alg header key value ------------------ ---------------------------------- none no key required HS256 string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct') HS384 dtto HS512 dtto RS256 private RSA key, perl HASH ref with JWK key structure, a reference to SCALAR string with PEM or DER or JSON/JWK data, object: Crypt::PK::RSA, Crypt::OpenSSL::RSA, Crypt::X509 or Crypt::OpenSSL::X509 RS384 private RSA key, see RS256 RS512 private RSA key, see RS256 PS256 private RSA key, see RS256 PS384 private RSA key, see RS256 PS512 private RSA key, see RS256 ES256 private ECC key, perl HASH ref with JWK key structure, a reference to SCALAR string with PEM or DER or JSON/JWK data, an instance of Crypt::PK::ECC ES384 private ECC key, see ES256 ES512 private ECC key, see ES256 JWE alg header key value ------------------ ---------------------------------- dir string (raw octects) or perl HASH ref with JWK, kty=>'oct', length depends on 'enc' algorithm A128KW string (raw octects) 16 bytes (or perl HASH ref with JWK, kty=>'oct') A192KW string (raw octects) 24 bytes (or perl HASH ref with JWK, kty=>'oct') A256KW string (raw octects) 32 bytes (or perl HASH ref with JWK, kty=>'oct') A128GCMKW string (raw octects) 16 bytes (or perl HASH ref with JWK, kty=>'oct') A192GCMKW string (raw octects) 24 bytes (or perl HASH ref with JWK, kty=>'oct') A256GCMKW string (raw octects) 32 bytes (or perl HASH ref with JWK, kty=>'oct') PBES2-HS256+A128KW string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct') PBES2-HS384+A192KW string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct') PBES2-HS512+A256KW string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct') RSA-OAEP public RSA key, perl HASH ref with JWK key structure, a reference to SCALAR string with PEM or DER or JSON/JWK data, an instance of Crypt::PK::RSA or Crypt::OpenSSL::RSA RSA-OAEP-256 public RSA key, see RSA-OAEP RSA1_5 public RSA key, see RSA-OAEP ECDH-ES public ECC key, perl HASH ref with JWK key structure, a reference to SCALAR string with PEM or DER or JSON/JWK data, an instance of Crypt::PK::ECC ECDH-ES+A128KW public ECC key, see ECDH-ES ECDH-ES+A192KW public ECC key, see ECDH-ES ECDH-ES+A256KW public ECC key, see ECDH-ES keypass When 'key' parameter is an encrypted private RSA or ECC key this optional parameter may contain a password for private key decryption. allow_none 1 - allow JWS with "none" 'alg' header value (which means that token has no signature), BEWARE: DANGEROUS, UNSECURE!!! 0 (default) - do not allow JWS with "none" 'alg' header value extra_headers This optional parameter may contain a HASH ref with items that will be added to JWT header. If you want to use PBES2-based 'alg' like "PBES2-HS512+A256KW" you can set PBES2 salt len (p2s) in bytes and iteration count (p2c) via "extra_headers" like this: my $token = encode_jwt(payload=>$p, key=>$k, alg=>'PBES2-HS512+A256KW', extra_headers=>{p2c=8000, p2s=>32}); #NOTE: handling of p2s header is a special case, in the end it is replaced with the generated salt zip Compression method, currently 'deflate' is the only one supported. "undef" (default) means no compression. my $token = encode_jwt(payload=>$p, key=>$k, alg=>'HS256', zip=>'deflate'); #or define compression level my $token = encode_jwt(payload=>$p, key=>$k, alg=>'HS256', zip=>['deflate', 9]); auto_iat 1 - set 'iat' (Issued At) claim to current time (epoch seconds since 1970) at the moment of token encoding 0 (default) - do not set 'iat' claim NOTE: claims are part of the payload and can be used only if the payload is a HASH ref! relative_exp Set 'exp' claim (Expiration Time) to current time + "relative_exp" value (in seconds). NOTE: claims are part of the payload and can be used only if the payload is a HASH ref! relative_nbf Set 'nbf' claim (Not Before) to current time + "relative_nbf" value (in seconds). NOTE: claims are part of the payload and can be used only if the payload is a HASH ref! SEE ALSO Crypt::Cipher::AES, Crypt::AuthEnc::GCM, Crypt::PK::RSA, Crypt::PK::ECC, Crypt::KeyDerivation, Crypt::KeyWrap LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. COPYRIGHT Copyright (c) 2015 DCIT, a.s. <http://www.dcit.cz> / Karel Miko
const mongoose = require('mongoose'); const slugify = require('slugify'); const tourSchema = new mongoose.Schema( { name: { type: String, required: [true, 'a tour must have a name'], unique: true, trim: true, maxlength: [40, 'Tour name must be at max 40 characters'], minlength: [10, 'Tour name must be at least 10 characters'], }, slug: String, secretTour: { type: Boolean, default: false, }, duration: { type: Number, required: [true, 'a tour must have a duration'], }, maxGroupSize: { type: Number, required: [true, 'a tour must have a maxGroupSize'], }, difficulty: { type: String, required: [true, 'a tour must have a difficulty'], enum: { values: ['easy', 'medium', 'difficult'], message: 'Not a valid difficulty!', }, }, ratingsAverage: { type: Number, default: 4, max: [5, 'Rating must be between 1 and 5'], min: [1, 'Rating must be between 1 and 5'], }, ratingsQuantity: { type: Number, default: 0, }, price: { type: Number, required: [true, 'a tour must have a price'], }, priceDiscount: { type: Number, validate: { validator: function (value) { return value < this.price; }, message: 'Discount must not be below the price', }, }, summary: { type: String, trim: true, required: [true, 'a tour must have a summary'], }, description: { type: String, trim: true, }, imageCover: { type: String, required: [true, 'a tour must have a cover image'], }, images: { type: [String], }, createdAt: { type: Date, default: Date.now(), select: false, }, startDates: { type: [Date], }, startLocation: { type: { type: String, default: 'Point', enum: ['Point'], }, coordinates: [Number], address: String, description: String, }, locations: [ { type: { type: String, default: 'Point', enum: ['Point'], }, coordinates: [Number], address: String, description: String, day: Number, }, ], guides: [ { type: mongoose.Schema.ObjectId, ref: 'User', }, ], }, { toJSON: { virtuals: true }, toObject: { virtuals: true }, }, ); tourSchema.index({ price: 1, ratingsAverage: -1 }); tourSchema.index({ slug: 1 }); tourSchema.index({ startLocation: '2dsphere' }); // Virtual field tourSchema.virtual('durationWeeks').get(function () { return this.duration / 7; }); // Virtual Populate tourSchema.virtual('reviews', { ref: 'Review', foreignField: 'tour', localField: '_id', }); // DOCUMENT MIDDLEWARE, RUNS BEFORE DOCUMENT IS SAVED // Also called a PRE-SAVE HOOK tourSchema.pre('save', function (next) { this.slug = slugify(this.name, { lower: true }); next(); }); // QUERY MIDDLEWARE, RUNS BEFORE THE QUERY IS EXECUTED // PRE-FIND HOOK tourSchema.pre(/^find/, function (next) { this.find({ secretTour: { $ne: true } }); this.start = Date.now(); next(); }); tourSchema.pre(/^find/, function (next) { this.populate({ path: 'guides', select: '-__v -passwordChangedAt', }); next(); }); // AGGREGATION MIDDLEWARE tourSchema.pre('aggregate', function (next) { this.pipeline.unshift({ $match: { secretTour: { $ne: true } }, }); next(); }); const Tour = mongoose.model('Tour', tourSchema); module.exports = Tour;
/* 📝 중복문자제거 소문자로 된 한개의 문자열이 입력되면 중복된 문자를 제거하고 출력하는 프로그램을 작성하 세요. 제거된 문자열의 각 문자는 원래 문자열의 순서를 유지합니다. ▣ 입력설명 첫 줄에 문자열이 입력됩니다. ▣ 출력설명 첫 줄에 중복문자가 제거된 문자열을 출력합니다. ▣ 입력예제 1 ksekkset ▣ 출력예제 1 kset 📝 강의 자료 (1) 해당 문자열의 길이만큼 반복문을 돌려서 해당 index에 해당하는 단어를 indexOf로 찾음. function solution(s){ let answer=""; for(let i=0; i<s.length; i++){ if(s.indexOf(s[i])===i) answer+=s[i]; } return answer; } console.log(solution("ksekkset")); */ // (1) 해당 문자열 문자 하나씩 indexOf로 찾고 없으면 추가 function solution(str) { let result = ''; result += str[0]; for (const char of str) { if (0 > result.indexOf(char)) { result += char; } } return result; } var str = 'ksekkset'; console.log(solution(str)); // 강의 자료랑 비슷하게 푼듯
import { useState, createContext, useContext } from "react"; const ModalContext = createContext(); export function useNavModal() { return useContext(ModalContext); } export function ModalProvider({ children }) { const [openModal, setOpenModal] = useState(false); const [formData, setFormData] = useState({ firstName: "", lastName: "", email: "", phone: "", address: "", }); function handleChange(event) { const { name, value } = event.target; setFormData((prevFormData) => { return { ...prevFormData, [name]: value, }; }); } const toggle = () => setOpenModal((prev) => !prev); return ( <ModalContext.Provider value={{ toggle, handleChange, formData, openModal }} > {children} </ModalContext.Provider> ); }
using Dapplo.Microsoft.Extensions.Hosting.WinForms; using OpenIddict.Client; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Abstractions.OpenIddictExceptions; using static OpenIddict.Client.WebIntegration.OpenIddictClientWebIntegrationConstants; namespace OpenIddict.Sandbox.WinForms.Client { public partial class MainForm : Form, IWinFormsShell { private readonly OpenIddictClientService _service; public MainForm(OpenIddictClientService service) { _service = service ?? throw new ArgumentNullException(nameof(service)); InitializeComponent(); } private async void LocalLoginButton_Click(object sender, EventArgs e) => await AuthenticateAsync("Local"); private async void TwitterLoginButton_Click(object sender, EventArgs e) => await AuthenticateAsync(Providers.Twitter); private async Task AuthenticateAsync(string provider) { using var source = new CancellationTokenSource(delay: TimeSpan.FromSeconds(90)); try { // Ask OpenIddict to initiate the challenge and launch the system browser // to allow the user to complete the interactive authentication dance. var nonce = await _service.ChallengeWithBrowserAsync( provider, cancellationToken: source.Token); // Wait until the user approved or rejected the authorization // demand and retrieve the resulting claims-based principal. var (_, _, principal) = await _service.AuthenticateWithBrowserAsync( nonce, cancellationToken: source.Token); #if SUPPORTS_WINFORMS_TASK_DIALOG TaskDialog.ShowDialog(new TaskDialogPage { Caption = "Authentication successful", Heading = "Authentication successful", Icon = TaskDialogIcon.ShieldSuccessGreenBar, Text = $"Welcome, {principal.FindFirst(Claims.Name)!.Value}." }); #else MessageBox.Show($"Welcome, {principal.FindFirst(Claims.Name)!.Value}.", "Authentication successful", MessageBoxButtons.OK, MessageBoxIcon.Information); #endif } catch (OperationCanceledException) { #if SUPPORTS_WINFORMS_TASK_DIALOG TaskDialog.ShowDialog(new TaskDialogPage { Caption = "Authentication timed out", Heading = "Authentication timed out", Icon = TaskDialogIcon.Warning, Text = "The authentication process was aborted." }); #else MessageBox.Show("The authentication process was aborted.", "Authentication timed out", MessageBoxButtons.OK, MessageBoxIcon.Warning); #endif } catch (ProtocolException exception) when (exception.Error is Errors.AccessDenied) { #if SUPPORTS_WINFORMS_TASK_DIALOG TaskDialog.ShowDialog(new TaskDialogPage { Caption = "Authorization denied", Heading = "Authorization denied", Icon = TaskDialogIcon.Warning, Text = "The authorization was denied by the end user." }); #else MessageBox.Show("The authorization was denied by the end user.", "Authorization denied", MessageBoxButtons.OK, MessageBoxIcon.Warning); #endif } catch { #if SUPPORTS_WINFORMS_TASK_DIALOG TaskDialog.ShowDialog(new TaskDialogPage { Caption = "Authentication failed", Heading = "Authentication failed", Icon = TaskDialogIcon.Error, Text = "An error occurred while trying to authenticate the user." }); #else MessageBox.Show("An error occurred while trying to authenticate the user.", "Authentication failed", MessageBoxButtons.OK, MessageBoxIcon.Error); #endif } } } }
@extends('template') @section('content') <form action="{{route('juegos.store')}}" method="post" enctype="multipart/form-data"> @csrf <div class="modal-body"> <div class="mb-3"> <label for="" class="form-label">Nombre:</label> <input type="text" class="form-control crud @error('nombre') is-invalid @enderror" name="nombre" id="nombre" aria-describedby="helpId" placeholder="Escriba aquí por favor" required value="{{ old('nombre') }}" /> @error('nombre') <div class="invalid-feedback">{{"Por favor introduzca un nombre"}}</div> @enderror <br> <label for="" class="form-label">Descripcion del juego</label> <input class="form-control crud @error('descripcion') is-invalid @enderror" name="descripcion" rows="4" cols="50" placeholder="Escriba aquí por favor" required value="{{ old('descripcion') }}" /> @error('descripcion') <div class="invalid-feedback">{{"Por favor introduzca una descripcion valida"}}</div> @enderror <br> <label for="" class="form-label">Cantidad de jugadores </label> <select name="cantidad" id=""> <option value="1 jugador">1 jugador</option> <option value="1 a 2 jugadores">1 a 2 jugadores</option> <option value="1 a 4 jugadores">1 a 4 jugadores</option> <option value="1 a 4 jugadores">1 a 8 jugadores</option> <option value="1 a 4 jugadores">1 a 16 jugadores</option> <option value="2 jugadores">2 jugadores</option> <option value="Multijugador">Multijugador</option> </select> <br> <label for="" class="form-label">Precio Bs.: </label> <input type="number" step="0.01" min="0" class="form-control crud @error('precio') is-invalid @enderror" name="precio" id="precio" aria-describedby="helpId" placeholder="Ej. 0.10" required value="{{ old('precio') }}" /> @error('precio') <div class="invalid-feedback">{{"Por favor introduzca un monto valida"}}</div> @enderror <br> <label for="" class="form-label">Cantidad en Stock</label> <input type="number" class="form-control crud @error('stock') is-invalid @enderror" name="stock" id="stock" aria-describedby="helpId" placeholder="Agregue la cantidad de stock que posee del juego aqui" required value="{{ old('stock') }}" /> @error('stock') <div class="invalid-feedback">{{"Por favor introduzca una cantidad valida"}}</div> @enderror <br> <label for="" class="form-label">Imagen del juego </label> <input type="file" class="form-control" name="imagen" id="" aria-describedby="helpId" accept="image/*" required /> @error('imagen') <div class="invalid-feedback">{{"Por favor introduzca imagen valida"}}</div> @enderror <br> <label for="" class="form-label">Seleccione los géneros </label> <div class="generos-container"> @foreach ($generos as $genero) <div class="genero"> <div class="form-check"> <input class="form-check-input @error('generos') is-invalid @enderror" type="checkbox" name="generos[]" id="generos" value="{{ $genero->id_genero }}"> <label class="form-check-label" for="">{{ $genero->nombre }}</label> </div> </div> @endforeach @error('generos') <div class="invalid-feedback d-block">{{ $message }}</div> @enderror </div> <br> <label for="" class="form-label">Seleccione las plataformas </label> <div class="plataformas-container"> @foreach ($plataformas as $plataforma) <div class="plataforma"> <div class="form-check"> <input class="form-check-input @error('plataformas') is-invalid @enderror" type="checkbox" name="plataformas[]" id="plataformas" value="{{ $plataforma->id_plataforma }}"> <label class="form-check-label" for="">{{ $plataforma->nombre }}</label> </div> </div> @endforeach @error('plataformas') <div class="invalid-feedback d-block">{{ $message }}</div> @enderror </div> <br> </div> <a href="{{url('juegos')}}"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button></a> <button type="submit" class="btn btn-primary">Agregar</button> </div> </form> @endsection
// Copyright 2023 RisingWave Labs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use risingwave_common::array::{Array, ListRef, StructRef}; use risingwave_common::types::num256::Int256Ref; use crate::{ExprError, Result}; /// Essentially `RTFn` is an alias of the specific Fn. It was aliased not to /// shorten the `where` clause of `GeneralAgg`, but to workaround an compiler /// error`[E0582`]: binding for associated type `Output` references lifetime `'a`, /// which does not appear in the trait input types. #[allow(clippy::upper_case_acronyms)] pub trait RTFn<'a, T, R>: Send + Clone + 'static where T: Array, R: Array, { fn eval( &mut self, result: Option<<R as Array>::RefItem<'a>>, input: Option<<T as Array>::RefItem<'a>>, ) -> Result<Option<<R as Array>::RefItem<'a>>>; } impl<'a, T, R, Z> RTFn<'a, T, R> for Z where T: Array, R: Array, Z: Send + Clone + 'static + Fn( Option<<R as Array>::RefItem<'a>>, Option<<T as Array>::RefItem<'a>>, ) -> Result<Option<<R as Array>::RefItem<'a>>>, { fn eval( &mut self, result: Option<<R as Array>::RefItem<'a>>, input: Option<<T as Array>::RefItem<'a>>, ) -> Result<Option<<R as Array>::RefItem<'a>>> { self.call((result, input)) } } use std::convert::From; use std::ops::{BitAnd, BitOr, BitXor}; use num_traits::CheckedAdd; use risingwave_common::types::ScalarRef; pub fn sum<R, T>(result: Option<R>, input: Option<T>) -> Result<Option<R>> where R: From<T> + CheckedAdd<Output = R> + Copy, { let res = match (result, input) { (_, None) => result, (None, Some(i)) => Some(R::from(i)), (Some(r), Some(i)) => r .checked_add(&R::from(i)) .map_or(Err(ExprError::NumericOutOfRange), |x| Ok(Some(x)))?, }; Ok(res) } pub fn min<'a, T>(result: Option<T>, input: Option<T>) -> Result<Option<T>> where T: ScalarRef<'a> + PartialOrd, { let res = match (result, input) { (None, _) => input, (_, None) => result, (Some(r), Some(i)) => Some(if r < i { r } else { i }), }; Ok(res) } pub fn min_str<'a>(r: Option<&'a str>, i: Option<&'a str>) -> Result<Option<&'a str>> { min(r, i) } pub fn min_struct<'a>( r: Option<StructRef<'a>>, i: Option<StructRef<'a>>, ) -> Result<Option<StructRef<'a>>> { min(r, i) } pub fn min_list<'a>(r: Option<ListRef<'a>>, i: Option<ListRef<'a>>) -> Result<Option<ListRef<'a>>> { min(r, i) } pub fn min_int256<'a>( r: Option<Int256Ref<'a>>, i: Option<Int256Ref<'a>>, ) -> Result<Option<Int256Ref<'a>>> { min(r, i) } pub fn max<'a, T>(result: Option<T>, input: Option<T>) -> Result<Option<T>> where T: ScalarRef<'a> + PartialOrd, { let res = match (result, input) { (None, _) => input, (_, None) => result, (Some(r), Some(i)) => Some(if r > i { r } else { i }), }; Ok(res) } pub fn max_str<'a>(r: Option<&'a str>, i: Option<&'a str>) -> Result<Option<&'a str>> { max(r, i) } pub fn max_struct<'a>( r: Option<StructRef<'a>>, i: Option<StructRef<'a>>, ) -> Result<Option<StructRef<'a>>> { max(r, i) } pub fn max_list<'a>(r: Option<ListRef<'a>>, i: Option<ListRef<'a>>) -> Result<Option<ListRef<'a>>> { max(r, i) } pub fn max_int256<'a>( r: Option<Int256Ref<'a>>, i: Option<Int256Ref<'a>>, ) -> Result<Option<Int256Ref<'a>>> { max(r, i) } pub fn first<T>(result: Option<T>, input: Option<T>) -> Result<Option<T>> { Ok(result.or(input)) } pub fn first_str<'a>(r: Option<&'a str>, i: Option<&'a str>) -> Result<Option<&'a str>> { first(r, i) } pub fn first_struct<'a>( r: Option<StructRef<'a>>, i: Option<StructRef<'a>>, ) -> Result<Option<StructRef<'a>>> { first(r, i) } pub fn first_list<'a>( r: Option<ListRef<'a>>, i: Option<ListRef<'a>>, ) -> Result<Option<ListRef<'a>>> { first(r, i) } pub fn first_int256<'a>( r: Option<Int256Ref<'a>>, i: Option<Int256Ref<'a>>, ) -> Result<Option<Int256Ref<'a>>> { first(r, i) } /// Note the following corner cases: /// /// ```slt /// statement ok /// create table t(v1 int); /// /// statement ok /// insert into t values (null); /// /// query I /// select count(*) from t; /// ---- /// 1 /// /// query I /// select count(v1) from t; /// ---- /// 0 /// /// query I /// select sum(v1) from t; /// ---- /// NULL /// /// statement ok /// drop table t; /// ``` pub fn count<T>(result: Option<i64>, input: Option<T>) -> Result<Option<i64>> { let res = match (result, input) { (None, None) => Some(0), (Some(r), None) => Some(r), (None, Some(_)) => Some(1), (Some(r), Some(_)) => Some(r + 1), }; Ok(res) } pub fn count_str(r: Option<i64>, i: Option<&str>) -> Result<Option<i64>> { count(r, i) } pub fn count_struct(r: Option<i64>, i: Option<StructRef<'_>>) -> Result<Option<i64>> { count(r, i) } pub fn count_list(r: Option<i64>, i: Option<ListRef<'_>>) -> Result<Option<i64>> { count(r, i) } pub fn count_int256(r: Option<i64>, i: Option<Int256Ref<'_>>) -> Result<Option<i64>> { count(r, i) } pub fn bit_and<'a, T>(result: Option<T>, input: Option<T>) -> Result<Option<T>> where T: ScalarRef<'a> + PartialOrd + BitAnd<Output = T>, { let res = match (result, input) { (None, _) => input, (_, None) => result, (Some(r), Some(i)) => Some(r.bitand(i)), }; Ok(res) } pub fn bit_or<'a, T>(result: Option<T>, input: Option<T>) -> Result<Option<T>> where T: ScalarRef<'a> + PartialOrd + BitOr<Output = T>, { let res = match (result, input) { (None, _) => input, (_, None) => result, (Some(r), Some(i)) => Some(r.bitor(i)), }; Ok(res) } pub fn bit_xor<'a, T>(result: Option<T>, input: Option<T>) -> Result<Option<T>> where T: ScalarRef<'a> + PartialOrd + BitXor<Output = T>, { let res = match (result, input) { (None, _) => input, (_, None) => result, (Some(r), Some(i)) => Some(r.bitxor(i)), }; Ok(res) }
import React from 'react'; import { styled } from '@mui/material'; import { ChevronRight as ChevronRightIcon } from '@mui/icons-material'; import BadgeLabel from './BadgeLabel'; import { getDisplayedHref } from '../utilities/sitemap'; const Link = styled('a', { shouldForwardProp: (props) => props !== 'color' && props !== 'active' })(({ active, disabled, color }) => ({ display: 'block', color: '#DDDDDD', borderTop: '1px solid #979797', padding: '10px 5px', fontFamily: 'Montserrat', fontSize: 16, fontWeight: 'bold', letterSpacing: 0, lineHeight: '30px', backgroundColor: active ? '#13A792' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'space-between', textDecoration: 'none', cursor: disabled ? 'default' : 'unset', '&:visited, &:active, &:hover, &:focus': { textDecoration: 'none', color: color, }, '&:last-child': { borderBottom: '1px solid #979797', }, })); const LinkRight = styled('div')({ display: 'flex', alignItems: 'center', }); const disabledColor = '#8091A5'; export default function PrimarySectionLinks({ links = [], activePrimarySection, setActivePrimarySection, redirect }) { const handleClick = (label, link, disabled, newTab = false) => { return (e) => { e.preventDefault(); if (disabled) return; if (link) return redirect(link, newTab) setActivePrimarySection(label); } }; return links.map((link, idx) => { const hideLink = link.hideWithoutPermission && !link.permission; const isDisabled = link.notAvailable || !!link.chip; const color = isDisabled ? disabledColor : '#DDDDDD'; const href = getDisplayedHref(link.link); return !hideLink && <Link href={href} onClick={handleClick(link.label, link.link, isDisabled, link.newTab)} active={activePrimarySection === link.label} key={'primary-link' + idx} disabled={isDisabled} color={color} > <div style={{ color }}>{link.label}</div> {link.links && <ChevronRightIcon style={{ fontSize: 30 }} /> } {isDisabled && <LinkRight data-test-id="primary-link-disabled"> <BadgeLabel width={'110px'} backgroundColor={disabledColor} color="white">{link.chip || 'In Development'}</BadgeLabel> </LinkRight> } </Link> }); }
import { Component, EventEmitter, Output } from '@angular/core'; import { MessageService } from 'primeng/api'; import { catchError, first } from 'rxjs'; import { Conversion } from '../interfaces/conversion'; import { ConversionResult, SalaryRatesResult } from '../interfaces/salary-rates-result'; import { Symbols, Symbol } from '../interfaces/symbols'; import { ExchangeRateService } from '../services/exchange-rate/exchange-rate.service'; import { SalaryRatesData } from '../static-data/salary-rates-data'; @Component({ selector: 'app-salary-conversion-form', templateUrl: './salary-conversion-form.component.html', styleUrls: ['./salary-conversion-form.component.scss'] }) export class SalaryConversionFormComponent { hoursPerWeek: number = 40; daysPerWeek: number = 5; symbols: Array<Symbol> = []; salaryRates: Array<string> = []; selectedFromCurrency: Symbol = { description: 'United States Dollar', code: 'USD' }; selectedToCurrency: Symbol = { description: 'Euro', code: 'EUR' } loadingSymbols: boolean = false; selectedAmount: number | null = null; invalidAmount: boolean = false; userLanguage = navigator.language; @Output() newConversionResultEvent = new EventEmitter<ConversionResult>(); conversionResult?: ConversionResult; selectedSalaryRate: string = 'Yearly'; @Output() newSelectedSalaryRateEvent = new EventEmitter<string>(); loadingConversion: boolean = false; constructor( private exchangeRateService: ExchangeRateService, private messageService: MessageService, ) { this.salaryRates = SalaryRatesData.salaryRates; this.loadingSymbols = true; this.exchangeRateService.getSupportedSymbols() .pipe( first() ) .subscribe((data: Symbols) => { this.symbols = Object.values(data.symbols); this.symbols.sort((a, b) => (a.description < b.description) ? -1 : 1); this.loadingSymbols = false; }); } convert() { if (this.selectedAmount == null || this.selectedAmount <= 0) { this.invalidAmount = true; return; } this.invalidAmount = false; this.loadingConversion = true; let fromCurrCode = this.selectedFromCurrency.code; let toCurrCode = this.selectedToCurrency.code; this.exchangeRateService.convertCurrencies(toCurrCode, fromCurrCode, this.selectedAmount) .pipe( catchError(err => { throw err; }), first() ) .subscribe({ next: result => { this.newSelectedSalaryRateEvent.emit(this.selectedSalaryRate); this.salaryResult(result); this.loadingConversion = false; }, error: err => { console.log(err); this.messageService.add({ severity: 'error', summary: 'Oh noes...', detail: 'Something went wrong retrieving the conversion. Don\'t blame yourself you tried your best. Try again in a few seconds.', life: 10000 }); this.loadingConversion = false; } }); } salaryResult (conversion: Conversion) { //Convert result amount to hourly based on selectedSalaryRate let hourlyAmount = this.convertToHourly(this.selectedSalaryRate, conversion.result); let allSalaryRates = this.getAllSalaryRatesFromHourly(hourlyAmount); this.conversionResult = { toCurrency: JSON.parse(JSON.stringify(this.selectedToCurrency)), fromCurrency: JSON.parse(JSON.stringify(this.selectedFromCurrency)), salaryRates: allSalaryRates }; this.newConversionResultEvent.emit(this.conversionResult); } convertToHourly(salaryRate: string, amount: number) : number { if (salaryRate === "Hourly") { return amount; } if (salaryRate === "Daily") { return amount / 8; } if (salaryRate === "Weekly") { return amount / this.hoursPerWeek; //subject to change when amount of hours per week is implemented } if (salaryRate === "Monthly") { return ((amount * 12) / 52) / this.hoursPerWeek; //subject to change when amount of hours per week is implemented } //Yearly return (amount / 52) / this.hoursPerWeek; //subject to change when amount of hours per week is implemented } getAllSalaryRatesFromHourly(hourly: number) : SalaryRatesResult { var result = { hourly: hourly, daily: hourly * (this.hoursPerWeek / this.daysPerWeek), //assuming 40 hour work week and 5 days a week weekly: hourly * this.hoursPerWeek, //assuming 40 hour work week monthly: (hourly * this.hoursPerWeek * 52) / 12, yearly: hourly * this.hoursPerWeek * 52 } as SalaryRatesResult; result.hourly = Math.round((result.hourly + Number.EPSILON) * 100) / 100; result.daily = Math.round((result.daily + Number.EPSILON) * 100) / 100; result.weekly = Math.round((result.weekly + Number.EPSILON) * 100) / 100; result.monthly = Math.round((result.monthly + Number.EPSILON) * 100) / 100; result.yearly = Math.round((result.yearly + Number.EPSILON) * 100) / 100; return result; } }
package org.example.entity; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Positive; import jakarta.validation.constraints.PositiveOrZero; import jakarta.validation.constraints.Size; import org.jetbrains.annotations.NotNull; import javax.persistence.*; import java.math.BigDecimal; import java.util.Set; @Entity @Table(name = "goods") public class Goods { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false, unique = true) private long id; @Column(name = "products_name") @Size(min = 1, max = 30, message = "Name must be between 1 and 30 characters long!") @Pattern(regexp = "^([A-Z].*)", message = "Product's name should start with a capital letter!") private String name; @Positive @Column(name = "weight") @NotNull private double weight; @Column(name = "goods_quantity") @NotNull @PositiveOrZero private int goodsQuantity; @Column(name = "price_per_good_or_kg") @NotNull @Positive private BigDecimal priceForGoods; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "goods_type_id") // Column referencing GoodsType @NotNull private GoodsType goodsType; @ManyToMany(fetch = FetchType.EAGER) private Set<OrderDetails> orderDetailsSet; // public Goods(String name,@NotNull double weight, @NotNull GoodsType goodsType) { // this.name = name; // this.weight = weight; // this.goodsType = goodsType; // } // // public Goods(String name, @NotNull double weight, @NotNull int goodsQuantity, @NotNull GoodsType goodsType) { // this.name = name; // this.weight = weight; // this.goodsQuantity = goodsQuantity; // this.goodsType = goodsType; // } public Goods(String name, @NotNull double weight, @NotNull int goodsQuantity, @NotNull BigDecimal priceForGoods, @NotNull GoodsType goodsType) { this.name = name; this.weight = weight; this.goodsQuantity = goodsQuantity; this.priceForGoods = priceForGoods; this.goodsType = goodsType; } public Goods(){} public long getId() { return id; } public void setId(long id) { this.id = id; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } // public GoodsType getGoodsType() { // return goodsType; // } // // public void setGoodsType(GoodsType goodsType) { // this.goodsType = goodsType; // } @Override public String toString() { return "Goods{" + "id=" + id + ", weight=" + weight + //", goodsType=" + goodsType + '}'; } //TODO: maybe remove all the setters for the id in all classes //TODO: think about the relations between goods and trip, does it have to be reversed? }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('shipping_boxs', function (Blueprint $table) { $table->id(); $table->string('title', 10); $table->string('desc', 100)->nullable(); $table->foreignId('vender_id')->constrained('venders')->unllable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::create('shipping_boxs', function (Blueprint $table) { $table->dropForeign(['vender_id']); }); Schema::dropIfExists('shipping_boxs'); } };
package com.example.trade_centre.config.JWT; import com.example.trade_centre.entity.User; import com.example.trade_centre.model.UserModel; import io.jsonwebtoken.*; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Date; import static java.lang.String.format; @Component @RequiredArgsConstructor public class JWTTokenUtil { private final String jwtSecret = "zdtlD3JK56m6wTTgsNFhqzjqP"; private final String jwtIssuer = "example.io"; public String generateAccessToken(User user) { return Jwts.builder() .setSubject(format("%s,%s", user.getId(), user.getUsername())) .setIssuer(jwtIssuer) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000)) .signWith(SignatureAlgorithm.HS512, jwtSecret) .compact(); } public String getUserId(String token) { Claims claims = Jwts.parser() .setSigningKey(jwtSecret) .parseClaimsJws(token) .getBody(); return claims.getSubject().split(",")[0]; } public String getUsername(String token) { Claims claims = Jwts.parser() .setSigningKey(jwtSecret) .parseClaimsJws(token) .getBody(); return claims.getSubject().split(",")[1]; } public Date getExpirationDate(String token) { Claims claims = Jwts.parser() .setSigningKey(jwtSecret) .parseClaimsJws(token) .getBody(); return claims.getExpiration(); } public boolean validate(String token){ try{ Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token); return true; } catch (SignatureException ex) { ex.printStackTrace(); } catch (MalformedJwtException ex) { ex.printStackTrace(); } catch (ExpiredJwtException ex) { ex.printStackTrace(); } catch (UnsupportedJwtException ex) { ex.printStackTrace(); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } return false; } }
import { isValidObjectId } from "mongoose"; import { AsyncHandler } from "../utils/AsyncHandler.js"; import { Like } from "../models/like.model.js"; import mongoose from "mongoose"; import { Video } from "../models/video.model.js"; import { APIResponse } from "../utils/APIResponse.js"; import { Comment } from "../models/comment.model.js"; import { Tweet } from "../models/tweet.model.js"; const toggleVideoLike = AsyncHandler(async (req, res) => { if (!req.auth) { // Authentication return res.status(400).json(new APIResponse(400, {}, req.authWarning)); } const { videoId } = req.params; // Toggle like on video if (!isValidObjectId(videoId)) { return res.status(400).json(new APIResponse(400, {}, "Not valid Id.")); } const getVid = await Video.findById(videoId); // Verifying videoId from Database. if (!getVid) { return res .status(400) .json(new APIResponse(400, {}, "Not valid video Id.")); } const likeData = await Like.aggregate([ // Checking either this user has liked this video. { $match: { video: new mongoose.Types.ObjectId(getVid?._id), likedBy: new mongoose.Types.ObjectId(req.user?._id), }, }, ]); if (likeData.length > 0) { // Toggling likes based on gathered likeData. await Like.findByIdAndDelete(likeData[0]?._id); return res .status(200) .json(new APIResponse(200, {}, "Unliked video successfully.")); } else { await Like.create({ video: getVid?._id, likedBy: req.user?._id, }); return res .status(200) .json(new APIResponse(200, {}, "Liked video successfully.")); } }); const toggleCommentLike = AsyncHandler(async (req, res) => { if (!req.auth) { // Authentication return res.status(400).json(new APIResponse(400, {}, req.authWarning)); } const { commentId } = req.params; // Toggle like on comment if (!isValidObjectId(commentId)) { return res.status(400).json(new APIResponse(400, {}, "Not valid Id.")); } const getComment = await Comment.findById(commentId); // Verifying commentId if (!getComment) { return res .status(400) .json(new APIResponse(400, {}, "Not valid comment Id.")); } const commentData = await Like.aggregate([ { $match: { comment: new mongoose.Types.ObjectId(getComment?._id), likedBy: new mongoose.Types.ObjectId(req.user?._id), }, }, ]); if (commentData.length > 0) { // Toggling like on comment. await Like.findByIdAndDelete(commentData[0]?._id); return res .status(200) .json(new APIResponse(200, {}, "Unliked comment successfully.")); } else { await Like.create({ comment: getComment?._id, likedBy: req.user?._id, }); return res .status(200) .json(new APIResponse(200, {}, "Liked comment successfully.")); } }); const toggleTweetLike = AsyncHandler(async (req, res) => { if (!req.auth) { // Authentication return res.status(400).json(new APIResponse(400, {}, req.authWarning)); } const { tweetId } = req.params; // Toggle like on tweet if (!isValidObjectId(tweetId)) { return res.status(400).json(new APIResponse(400, {}, "Not valid Id.")); } const getTweet = await Tweet.findById(tweetId); // Verifying tweetId from Database. if (!getTweet) { return res .status(400) .json(new APIResponse(400, {}, "Not valid tweet Id.")); } const tweetData = await Like.aggregate([ { $match: { tweet: new mongoose.Types.ObjectId(getTweet?._id), likedBy: new mongoose.Types.ObjectId(req.user?._id), }, }, ]); if (tweetData.length > 0) { // Toggling like on tweet. await Like.findByIdAndDelete(tweetData[0]?._id); return res .status(200) .json(new APIResponse(200, {}, "Unliked tweet successfully.")); } else { await Like.create({ tweet: getTweet?._id, likedBy: req.user?._id, }); return res .status(200) .json(new APIResponse(200, {}, "Liked tweet successfully.")); } }); const getLikedVideos = AsyncHandler(async (req, res) => { if (!req.auth) { return res.status(400).json(new APIResponse(400, {}, req.authWarning)); } let { page = 1, limit = 10 } = req.query; page = Number(page); limit = Number(limit); let likedVideoData = await Like.aggregate([ { $match: { likedBy: new mongoose.Types.ObjectId(req.user?._id), video: { $exists: true }, }, }, { $lookup: { // Left joining of Video file in Like through referenced videoId. from: "videos", localField: "video", foreignField: "_id", as: "video", pipeline: [ { $lookup: { // Left joining for Video owner details. from: "users", localField: "owner", foreignField: "_id", as: "owner", pipeline: [ { $project: { // Filtering owner details specifically. fullName: 1, email: 1, avatarImage: 1, }, }, ], }, }, { $addFields: { // Here, we'll be getting owner as an array, extracting first array element. owner: { $first: "$owner", }, }, }, { $project: { // Filtering video fields. title: 1, videoFile: 1, thumbnail: 1, duration: 1, views: 1, owner: 1, }, }, ], }, }, { $addFields: { // Here, we'll be getting video as an array, extracting first array element. video: { $first: "$video", }, }, }, { $facet: { metadata: [ { $count: "totalVideos", // Total document count is total video. }, { $addFields: { pageNumber: page, totalPages: { $ceil: { $divide: ["$totalVideos", limit] } }, }, }, ], data: [ { $skip: (page - 1) * limit, }, { $limit: limit, }, ], }, }, ]); likedVideoData = likedVideoData[0]; //TODO: get all liked videos return res .status(200) .json( new APIResponse( 200, { videos: likedVideoData }, "Fetched liked videos successfully." ) ); }); export { toggleCommentLike, toggleTweetLike, toggleVideoLike, getLikedVideos };
import React from 'react' import './Style/Style.css' import List from '@mui/material/List'; import ListItem from '@mui/material/ListItem'; import Divider from '@mui/material/Divider'; import ListItemText from '@mui/material/ListItemText'; import ListItemAvatar from '@mui/material/ListItemAvatar'; import Avatar from '@mui/material/Avatar'; import Typography from '@mui/material/Typography'; const Sidebar = ({user}) => { return ( <> <div className='sidebar'> <List sx={{ width: '100%', bgcolor: 'whitesmoke' }}> <ListItem alignItems="flex-start"> <ListItemAvatar> <Avatar alt="Remy Sharp" src=""/> </ListItemAvatar> <ListItemText primary={ <React.Fragment> <Typography sx={{ display: 'inline' }} component="span" variant="body2" color="text.primary" > {user.first_name} </Typography> </React.Fragment> } secondary={ <React.Fragment> <Typography sx={{ display: 'inline' }} component="span" variant="body2" color="text.primary" > {user.email} </Typography> </React.Fragment> } /> </ListItem> <Divider variant="inset" component="li" /> </List> </div> </> ) } export default Sidebar
import { Client, Wallet, AccountSet, Import, xrpToDrops } from '@transia/xrpl' import { validateConnection, Xrpld, getXpopBlob } from '@transia/xpop-toolkit' export async function main(): Promise<void> { // BURN CLIENT const burnUrl = 'wss://s.altnet.rippletest.net:51233' const burnClient = new Client(burnUrl) await burnClient.connect() // MINT CLIENT const mintUrl = 'wss://xahau-test.net' const mintClient = new Client(mintUrl) await mintClient.connect() mintClient.networkID = await mintClient.getNetworkID() const aliceWallet = Wallet.fromSeed('sEdTunqTkQWu114ieMbWjdTujjo7KSH') // validate burn syncronization - 1 mins (6 tries at 10 seconds) await validateConnection(burnClient, 6) // validate mint syncronization - 1 mins (6 tries at 10 seconds) await validateConnection(mintClient, 6) // ACCOUNT SET OUT const burnTx: AccountSet = { TransactionType: 'AccountSet', Account: aliceWallet.classicAddress, // @ts-expect-error - leave this alone OperationLimit: mintClient.networkID, Fee: xrpToDrops(10), } const burnResult = await Xrpld.submitRippled(burnClient, burnTx, aliceWallet) await burnClient.disconnect() // GET XPOP const xpopHex = await getXpopBlob( burnResult.hash, 'https://testnet.xrpl-labs.com/xpop', 'url', 10 ) // IMPORT OUT const mintTx: Import = { TransactionType: 'Import', Account: aliceWallet.classicAddress, Blob: xpopHex, } const mintResult = await Xrpld.submitXahaud(mintClient, mintTx, aliceWallet) console.log(mintResult) await mintClient.disconnect() } main()
/** * Функция применяется для того, чтобы подставить 0 перед целым числом для дней или месяцев в тех случаях, где это необходимо * @param {*} datePart - Является частью даты (день, месяц или год) * @returns возвращает строку с 0, если число от 1 до 9 и без 0, если больше 9 */ const addZeroBefore = (datePart: number) => { const datePartStr = datePart.toString(); if (datePartStr.length === 1) { return `0${datePartStr}`; } else return datePartStr; }; /** * Функция для отпределения интервала по умолчанию * @returns возвращает кортеж объектов дат 1го и последнего дня текущего месяца [fD, lD] */ export const datesRangesDefault = () => { const date = new Date(), y = date.getFullYear(), m = date.getMonth(); const fD = new Date(y, m, 1); const lD = new Date(y, m + 1, 0); return [fD, lD]; }; /** * Функция для отпределения интервала по умолчанию для недели * @returns возвращает кортеж объектов дат 1го и последнего дня текущей недели [fD, lD] */ export const weekDatesDefault = () => { const today = new Date(); const currentDayOfWeek = today.getDay(); // Получаем текущий день недели (0 - воскресенье, 1 - понедельник, и так далее) const diff = currentDayOfWeek === 0 ? 6 : currentDayOfWeek - 1; // Рассчитываем разницу между текущим днем недели и понедельником (0 - если воскресенье, иначе текущий день минус 1) const startDate = new Date(today); startDate.setDate(today.getDate() - diff); // Вычисляем начальную дату недели startDate.setHours(0, 0, 0, 0); // Устанавливаем время на начало дня const endDate = new Date(startDate); endDate.setDate(startDate.getDate() + 6); // Вычисляем конечную дату недели endDate.setHours(23, 59, 59, 999); // Устанавливаем время на конец дня return [startDate, endDate]; }; /** * Изменяет формат даты-времени c объекта Data на подходящий для базы данных => dd.mm.yyyy hh?:mm? * @param {*} date - стандартный объект даты * @returns строку даты в виде ${d}.${m}.${yy} */ export const transformDate = (date: Date) => { const day = addZeroBefore(date.getDate()); const month = addZeroBefore(date.getMonth() + 1); const year = addZeroBefore(date.getFullYear()); return `${day}.${month}.${year}`; }; /** * Изменяет формат даты-времени c объекта Data на строку вида => dd.mm.yy * @param {*} date - стандартный объект даты * @returns строку даты в виде ${d}.${m}.${yy} */ export const transformDateYY = (date: Date) => { const day = addZeroBefore(date.getDate()); const month = addZeroBefore(date.getMonth() + 1); let year = date.getFullYear().toString(); let yy = year.substring(2); return `${day}.${month}.${yy}`; }; export const readableDate = (date: string) => { const [day, month, year] = date.split('/').map(Number); const months = [ '', 'янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек', ]; const daysOfWeek = ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб']; const monthStr = months[month]; const yearStr = String(year).slice(-2); const dateObj = new Date(year, month - 1, day); const dayOfWeekStr = daysOfWeek[dateObj.getDay()]; return `${day} ${monthStr} ${yearStr} | ${dayOfWeekStr}`; }; // Функция для преобразования даты в строку "dd.MM.yyyy" export function formatDateToDDMMYYYY(date: Date) { const day = date.getDate().toString().padStart(2, '0'); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const year = date.getFullYear(); return `${day}.${month}.${year}`; }
import pandas as pd SORTING_ORDER = ["nb_items_int", "positive_feedback_percentage", "rating_avg", "price_dollars"] def sort_scraped_df(df: pd.DataFrame) -> pd.DataFrame: """ Given the DataFrame with scraped data, sorts it along SORTING_ORDER variable :param df: DataFrame with scraped data :return: sorted DataFrame """ df = df.dropna().copy() df['nb_items_int'] = df['nb_items_sold'].map(lambda nb: nb.as_int) assert all(col in df.columns for col in SORTING_ORDER) return df.sort_values(by=SORTING_ORDER, ascending=(False, False, False, True), ignore_index=True) def remove_items_not_full_input(df: pd.DataFrame, user_input: str) -> pd.DataFrame: """ Removes items that do not have the full user input in their title :param df: DataFrame to filter :param user_input: given user input fetched from website form :return: filtered DataFrame """ resulting_df = df.loc[df.title.str.contains(user_input, case=False)].reset_index(drop=True) if resulting_df.shape[0] > 10: return resulting_df return df def main(scraped_data: pd.DataFrame, user_input: str) -> pd.DataFrame: """ Processes scraped data from eBay and returns a copy of it after processing. :param scraped_data: data that was scraped on eBay website :param user_input: input of user on web scraping website :return: sorted DataFrame to display on website """ resulting_df = sort_scraped_df(scraped_data) resulting_df = remove_items_not_full_input(resulting_df, user_input) return resulting_df
import {FormControl, FormLabel, Input} from "@chakra-ui/react"; import {ChangeEventHandler, FunctionComponent, HTMLInputTypeAttribute, useEffect} from "react"; interface inputProps { id: string title: string value: string onChange: ChangeEventHandler type?: HTMLInputTypeAttribute } const MiInput: FunctionComponent<inputProps> = (props) => { let type: HTMLInputTypeAttribute = 'text' if (props.type) { type = props.type } return ( <FormControl> <FormLabel htmlFor={props.id}>{props.title}</FormLabel> <Input name={props.id} value={props.value} onChange={props.onChange} id={props.id} placeholder={props.title} type={type}/> </FormControl> ) } export default MiInput
package com.glaf.report.core.service; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.session.RowBounds; import org.mybatis.spring.SqlSessionTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.glaf.core.dao.EntityDAO; import com.glaf.core.id.IdGenerator; import com.glaf.core.util.JdbcUtils; import com.glaf.report.core.domain.SysReportTemplate; import com.glaf.report.core.mapper.SysReportTemplateMapper; import com.glaf.report.core.query.SysReportTemplateQuery; @Service("com.glaf.report.service.sysReportTemplateService") @Transactional(readOnly = true) public class SysReportTemplateServiceImpl implements SysReportTemplateService { protected final Logger logger = LoggerFactory.getLogger(getClass()); protected EntityDAO entityDAO; protected IdGenerator idGenerator; protected JdbcTemplate jdbcTemplate; protected SqlSessionTemplate sqlSessionTemplate; protected SysReportTemplateMapper sysReportTemplateMapper; public SysReportTemplateServiceImpl() { } @Transactional public void deleteById(String id) { if (id != null) { sysReportTemplateMapper.deleteSysReportTemplateById(id); } } @Transactional public void deleteByIds(List<String> ids) { if (ids != null && !ids.isEmpty()) { for (String id : ids) { sysReportTemplateMapper.deleteSysReportTemplateById(id); } } } public int count(SysReportTemplateQuery query) { return sysReportTemplateMapper.getSysReportTemplateCount(query); } public List<SysReportTemplate> list(SysReportTemplateQuery query) { List<SysReportTemplate> list = sysReportTemplateMapper .getSysReportTemplates(query); return list; } /** * 根据查询参数获取记录总数 * * @return */ public int getSysReportTemplateCountByQueryCriteria( SysReportTemplateQuery query) { return sysReportTemplateMapper.getSysReportTemplateCount(query); } /** * 根据查询参数获取一页的数据 * * @return */ public List<SysReportTemplate> getSysReportTemplatesByQueryCriteria( int start, int pageSize, SysReportTemplateQuery query) { RowBounds rowBounds = new RowBounds(start, pageSize); List<SysReportTemplate> rows = sqlSessionTemplate.selectList( "getSysReportTemplates", query, rowBounds); return rows; } public SysReportTemplate getSysReportTemplate(String id) { if (id == null) { return null; } SysReportTemplate sysReportTemplate = sysReportTemplateMapper .getSysReportTemplateById(id); return sysReportTemplate; } @Transactional public void save(SysReportTemplate sysReportTemplate) { if (StringUtils.isEmpty(sysReportTemplate.getId())) { sysReportTemplate.setId(idGenerator.getNextId("SYSREPORTTEMPLATE")); // sysReportTemplate.setCreateDate(new Date()); // sysReportTemplate.setDeleteFlag(0); sysReportTemplateMapper.insertSysReportTemplate(sysReportTemplate); } else { sysReportTemplateMapper.updateSysReportTemplate(sysReportTemplate); } } @Transactional public void runBatch() { logger.debug("-------------------start run-------------------"); String sql = " ";// 要运行的SQL语句 Connection connection = null; PreparedStatement psmt = null; try { connection = DataSourceUtils.getConnection(jdbcTemplate .getDataSource()); psmt = connection.prepareStatement(sql); for (int i = 0; i < 2; i++) { psmt.addBatch(); } psmt.executeBatch(); psmt.close(); } catch (Exception ex) { ex.printStackTrace(); logger.error("run batch error", ex); throw new RuntimeException(ex); } finally { JdbcUtils.close(psmt); } logger.debug("-------------------end run-------------------"); } @javax.annotation.Resource public void setEntityDAO(EntityDAO entityDAO) { this.entityDAO = entityDAO; } @javax.annotation.Resource public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; } @javax.annotation.Resource(name = "com.glaf.report.mapper.SysReportTemplateMapper") public void setSysReportTemplateMapper( SysReportTemplateMapper sysReportTemplateMapper) { this.sysReportTemplateMapper = sysReportTemplateMapper; } @javax.annotation.Resource public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @javax.annotation.Resource public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { this.sqlSessionTemplate = sqlSessionTemplate; } }
import 'package:flutter/material.dart'; import 'package:flutter_snappyshop/config/constants/app_colors.dart'; class CustomButton extends StatelessWidget { const CustomButton({ super.key, this.onPressed, required this.child, this.width = double.infinity, this.height = 52, }); final void Function()? onPressed; final Widget child; final double width; final double height; @override Widget build(BuildContext context) { return Container( height: height, width: width, decoration: BoxDecoration( color: AppColors.primaryPearlAqua, borderRadius: BorderRadius.circular(10), ), child: TextButton( style: TextButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), foregroundColor: Colors.white60, ), onPressed: () { if (onPressed != null) { onPressed!(); } }, child: child, ), ); } }
#!/bin/bash # Since: January, 2023 # Author: aalmiray # # Copyright 2023 Andres Almiray, Gerald Venzl # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ORADATA="/opt/oracle/oradata" DEFAULT_CONTAINER_NAME="oracledb" HEALTH_MAX_RETRIES=0 HEALTH_INTERVAL=0 CONTAINER_RUNTIME="" CONTAINER_ARGS="" CONTAINER_IMAGE="" CONTAINER_NAME="" VALIDATION="OK" FASTSTART="" ############################################################################### echo "::group::🔍 Verifying inputs" # CONTAINER_RUNTIME # If the setup container runtime is set, verify the runtime is available if [ -n "${SETUP_CONTAINER_RUNTIME}" ]; then # Container runtime exists if type "${SETUP_CONTAINER_RUNTIME}" > /dev/null; then CONTAINER_RUNTIME="${SETUP_CONTAINER_RUNTIME}" echo "✅ container runtime set to ${CONTAINER_RUNTIME}" fi fi # If container runtime is empty (either doesn't exist, or wasn't passed on), find default if [ -z "${CONTAINER_RUNTIME}" ]; then if type podman > /dev/null; then CONTAINER_RUNTIME="podman" echo "☑️️ container runtime set to ${CONTAINER_RUNTIME} (default)" elif type docker > /dev/null; then CONTAINER_RUNTIME="docker" echo "☑️️ container runtime set to ${CONTAINER_RUNTIME} (default)" else echo "❌ container runtime not available." VALIDATION="" fi fi # TAG if [ -z "${SETUP_TAG}" ]; then SETUP_TAG="latest" fi echo "✅ tag set to ${SETUP_TAG}" CONTAINER_IMAGE="gvenzl/oracle-free:${SETUP_TAG}" # PORT echo "✅ port set to ${SETUP_PORT}" CONTAINER_ARGS="-p 1521:${SETUP_PORT}" # CONTAINER_NAME if [ -n "${SETUP_CONTAINER_NAME}" ]; then echo "✅ container name set to ${SETUP_CONTAINER_NAME}" CONTAINER_NAME=${SETUP_CONTAINER_NAME} else echo "☑️️ container name set to ${DEFAULT_CONTAINER_NAME} (default)" CONTAINER_NAME=${DEFAULT_CONTAINER_NAME} fi CONTAINER_ARGS="${CONTAINER_ARGS} --name ${CONTAINER_NAME}" # HEALTH_MAX_RETRIES if [ -n "${SETUP_HEALTH_MAX_RETRIES}" ]; then echo "✅ health max retries set to ${SETUP_HEALTH_MAX_RETRIES}" HEALTH_MAX_RETRIES=$SETUP_HEALTH_MAX_RETRIES else # Set default if scripts is invoked outside the GH Action (otherwise this is set in action.yml) echo "☑️️ health max retries set to 60 (default)" HEALTH_MAX_RETRIES=60 fi # HEALTH_INTERVAL if [ -n "${SETUP_HEALTH_INTERVAL}" ]; then echo "✅ health interval set to ${SETUP_HEALTH_INTERVAL}" HEALTH_INTERVAL=${SETUP_HEALTH_INTERVAL} else # Set default if scripts is invoked outside the GH Action (otherwise this is set in action.yml) echo "☑️️ health interval set to 3 (default)" HEALTH_INTERVAL=3 fi # VOLUME if [ -n "${SETUP_VOLUME}" ]; then # skip volume if tag ends with 'faststart' FASTSTART=$(echo "${SETUP_TAG}" | grep -Eq "^.*faststart$" && echo "true" || echo "false") if [ "${FASTSTART}" = "true" ]; then echo "⚠️ Volume ${SETUP_VOLUME} skipped because tag is ${SETUP_TAG}" else echo "✅ volume set to ${SETUP_VOLUME} mapped to ${ORADATA}" CONTAINER_ARGS="${CONTAINER_ARGS} -v ${SETUP_VOLUME}:${ORADATA}" chmod 777 "${SETUP_VOLUME}" fi fi # PASSWORD if [ -z "${SETUP_ORACLE_PASSWORD}" ]; then echo "⚠️ Oracle password will be randomly generated" CONTAINER_ARGS="${CONTAINER_ARGS} -e ORACLE_RANDOM_PASSWORD=true" else echo "✅ ORACLE_PASSWORD explicitly set" CONTAINER_ARGS="${CONTAINER_ARGS} -e ORACLE_PASSWORD=${SETUP_ORACLE_PASSWORD}" fi # DATABASE if [ -n "${SETUP_ORACLE_DATABASE}" ]; then echo "✅ database name set to ${SETUP_ORACLE_DATABASE}" CONTAINER_ARGS="${CONTAINER_ARGS} -e ORACLE_DATABASE=${SETUP_ORACLE_DATABASE}" fi # APP_USER if [ -n "${SETUP_APP_USER}" ]; then echo "✅ APP_USER explicitly set" CONTAINER_ARGS="${CONTAINER_ARGS} -e APP_USER=${SETUP_APP_USER}" else echo "❌ APP_USER is not set" VALIDATION="" fi # APP_USER_PASSWORD if [ -n "${SETUP_APP_USER_PASSWORD}" ]; then echo "✅ APP_USER_PASSWORD explicitly set" CONTAINER_ARGS="${CONTAINER_ARGS} -e APP_USER_PASSWORD=${SETUP_APP_USER_PASSWORD}" else echo "❌ APP_USER_PASSWORD is not set" VALIDATION="" fi # SETUP_SCRIPTS if [ -n "${SETUP_SETUP_SCRIPTS}" ]; then echo "✅ setup scripts from ${SETUP_SETUP_SCRIPTS}" CONTAINER_ARGS="${CONTAINER_ARGS} -v ${SETUP_SETUP_SCRIPTS}:/container-entrypoint-initdb.d" fi # STARTUP_SCRIPTS if [ -n "${SETUP_STARTUP_SCRIPTS}" ]; then echo "✅ startup scripts from ${SETUP_STARTUP_SCRIPTS}" CONTAINER_ARGS="${CONTAINER_ARGS} -v ${SETUP_STARTUP_SCRIPTS}:/container-entrypoint-startdb.d" fi if [ -n "${VALIDATION}" ]; then echo "✅ All inputs are valid" else echo "❌ Validation failed" fi echo "::endgroup::" ############################################################################### if [ -z "${VALIDATION}" ]; then exit 1; fi ############################################################################### echo "::group::🐳 Running Container" CMD="${CONTAINER_RUNTIME} run -d ${CONTAINER_ARGS} ${CONTAINER_IMAGE}" echo "${CMD}" # Run Docker container eval "${CMD}" echo "::endgroup::" ############################################################################### ############################################################################### echo "::group::⏰ Waiting for database to be ready" DB_IS_UP=1 EXIT_VALUE=0 for ((COUNTER=1; COUNTER <= HEALTH_MAX_RETRIES; COUNTER++)) do echo " - try #${COUNTER} of ${HEALTH_MAX_RETRIES}" sleep "${HEALTH_INTERVAL}" DB_IS_UP=$("${CONTAINER_RUNTIME}" exec "${CONTAINER_NAME}" healthcheck.sh && echo "yes" || echo "no") if [ "${DB_IS_UP}" = "yes" ]; then break fi done if [ "${DB_IS_UP}" = "yes" ]; then echo "✅ Database is ready!" else echo "❌ Database failed to start on time" EXIT_VALUE=1 fi echo "::endgroup::" ############################################################################### exit ${EXIT_VALUE}
import React, { useState, useEffect } from "react"; function CountDown({ hours = 0, minutes = 0, seconds = 0 }) { const [paused, setPaused] = useState(false); const [over, setOver] = useState(false); const [time, setTime] = useState({ hours: parseInt(hours), minutes: parseInt(minutes), seconds: parseInt(seconds), }); const tick = () => { if (paused || over) return; if (time.hours === 0 && time.minutes === 0 && time.seconds === 0) setOver(true); else if (time.minutes === 0 && time.seconds === 0) setTime({ hours: time.hours - 1, minutes: 59, seconds: 59, }); else if (time.seconds === 0) setTime({ hours: time.hours, minutes: time.minutes - 1, seconds: 59, }); else { setTime({ hours: time.hours, minutes: time.minutes, seconds: time.seconds - 1, }); } }; useEffect(() => { let timerID = setInterval(() => tick(), 1000); return () => clearInterval(timerID); }); return ( <> <div style={{ display: "flex", alignItems: "center" }}> <div> <p style={{ display: "flex", alignItems: "center", marginLeft: "10px", }} >{`${time.hours .toString() .padStart(2, "0")}:${time.minutes .toString() .padStart(2, "0")}:${time.seconds.toString().padStart(2, "0")}`}</p> </div> </div> </> ); } export default CountDown;
function [status, MEh] = test_pca_2() % TEST_PCA_2 - Test functionality of pca class import test.simple.*; import mperl.file.spec.*; import physioset.*; import pset.session; import safefid.safefid; import datahash.DataHash; import misc.rmdir; import meegpipe.node.*; MEh = []; % Number of iterations to perform when computing model selection indices. % Increase for better robustness at the cost of computation time NB_ITER = 15; initialize(15); %% Create a new session try name = 'create new session'; warning('off', 'session:NewSession'); session.instance; warning('on', 'session:NewSession'); hashStr = DataHash(randn(1,100)); session.subsession(hashStr(1:5)); ok(true, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% learning PCA basis from physioset try name = 'learning PCA basis'; data = import(physioset.import.matrix, rand(5,1000)); myPCA = learn(spt.pca, data); pcs = proj(myPCA, data); ok(myPCA.DimOut == 5 & myPCA.DimIn == 5 & ... max(max((abs(cov(pcs) - eye(5))))) < 0.01, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% learning PCA basis from numeric try name = 'learning PCA basis from numeric'; data = rand(5,1000); myPCA = learn(spt.pca, data); pcs = proj(myPCA, data); ok(myPCA.DimOut == 5 & myPCA.DimIn == 5 & ... max(max((abs(cov(pcs') - eye(5))))) < 0.01, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% reducing dimensionality try name = 'reducing dimensionality'; data = import(physioset.import.matrix, rand(5,1000)); myPCA = spt.pca('MaxCard', 3); myPCA = learn(myPCA, data); pcs = proj(myPCA, data); ok(myPCA.DimOut == 3 & myPCA.DimIn == 5 & ... max(max((abs(cov(pcs) - eye(3))))) < 0.01, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% backprojecting, restoring sensors try name = 'backprojecting, restoring sensors'; mySensors = sensors.eeg.dummy(5); myImporter = physioset.import.matrix('Sensors', mySensors); data = import(myImporter, rand(5,1000)); myPCA = spt.pca('MaxCard', 3); myPCA = learn(myPCA, data); pcs = proj(myPCA, data); sensPCs = sensors(pcs); dataR = bproj(myPCA, pcs); sensR = sensors(dataR); ok(isa(sensPCs, 'sensors.dummy') & ... isa(sensR, 'sensors.eeg'), name); catch ME ok(ME, name); MEh = [MEh ME]; end %% RetainedVar try name = 'RetainedVar'; mySensors = sensors.eeg.dummy(5); myImporter = physioset.import.matrix('Sensors', mySensors); data = import(myImporter, rand(5,1000)); myPCA = spt.pca('RetainedVar', 50); myPCA = learn(myPCA, data); pcs = proj(myPCA, data); ok(size(pcs, 1) < 5, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% RetainedVar overriden by MinCard try name = 'RetainedVar overriden by MinCard'; mySensors = sensors.eeg.dummy(5); myImporter = physioset.import.matrix('Sensors', mySensors); data = import(myImporter, rand(5,1000)); myPCA = spt.pca('RetainedVar', 0, 'MinCard', 4); myPCA = learn(myPCA, data); pcs = proj(myPCA, data); ok(size(pcs, 1) == 4, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% MaxCard overriden by MinCard try name = 'MaxCard overriden by MinCard'; mySensors = sensors.eeg.dummy(5); myImporter = physioset.import.matrix('Sensors', mySensors); data = import(myImporter, rand(5,1000)); myPCA = spt.pca('MaxCard', 2, 'MinCard', 4); myPCA = learn(myPCA, data); pcs = proj(myPCA, data); ok(size(pcs, 1) == 4, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% MinSamplesPerParamRatio try name = 'MinSamplesPerParamRatio'; mySensors = sensors.eeg.dummy(5); myImporter = physioset.import.matrix('Sensors', mySensors); data = import(myImporter, rand(5,100)); myPCA = spt.pca('MinSamplesPerParamRatio', 10); myPCA = learn(myPCA, data); pcs = proj(myPCA, data); ok(size(pcs, 1) == 3, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% Sphering=false try name = 'Sphering=false'; mySensors = sensors.eeg.dummy(5); myImporter = physioset.import.matrix('Sensors', mySensors); data = import(myImporter, rand(5,100)); myPCA = spt.pca('Sphering', false); myPCA = learn(myPCA, data); pcs = proj(myPCA, data); pcVars = var(pcs, [], 2); ok(all(diff(pcVars)<0), name); catch ME ok(ME, name); MEh = [MEh ME]; end %% Criterion=mdl try name = 'Criterion=mdl'; mySensors = sensors.eeg.dummy(5); myImporter = physioset.import.matrix('Sensors', mySensors); X = rand(5,3)*rand(3, 10000) + 0.01*randn(5, 10000); data = import(myImporter, X); myPCA = spt.pca('Criterion', 'NONE', 'RetainedVar', 100); myPCA = learn(myPCA, data); origDim = myPCA.DimOut; newDim = nan(1, 5); for i = 1:NB_ITER, X = rand(5,3)*rand(3, 10000) + 0.01*randn(5, 10000); data = import(myImporter, X); myPCA = spt.pca('Criterion', 'MDL', 'RetainedVar', 100); myPCA = learn(myPCA, data); newDim(i) = myPCA.DimOut; end newDim = median(newDim); ok(origDim == 5 & newDim == 3, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% Criterion=aic try name = 'Criterion=aic'; mySensors = sensors.eeg.dummy(5); myImporter = physioset.import.matrix('Sensors', mySensors); X = rand(5,3)*rand(3, 10000) + 0.01*randn(5, 10000); data = import(myImporter, X); myPCA = spt.pca('Criterion', 'NONE', 'RetainedVar', 100); myPCA = learn(myPCA, data); origDim = myPCA.DimOut; newDim = nan(1, 10); for i = 1:NB_ITER, X = rand(5,3)*rand(3, 10000) + 0.01*randn(5, 10000); data = import(myImporter, X); myPCA = spt.pca('Criterion', 'AIC', 'RetainedVar', 100); myPCA = learn(myPCA, data); newDim(i) = myPCA.DimOut; end newDim = median(newDim); ok(origDim == 5 & newDim == 3, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% Criterion=mibs try name = 'Criterion=mibs'; mySensors = sensors.eeg.dummy(5); myImporter = physioset.import.matrix('Sensors', mySensors); X = rand(5,3)*rand(3, 10000) + 0.01*randn(5, 10000); data = import(myImporter, X); myPCA = spt.pca('Criterion', 'NONE', 'RetainedVar', 100); myPCA = learn(myPCA, data); origDim = myPCA.DimOut; newDim = nan(1, 10); for i = 1:NB_ITER, X = rand(5,3)*rand(3, 10000) + 0.01*randn(5, 10000); data = import(myImporter, X); myPCA = spt.pca('Criterion', 'MIBS', 'RetainedVar', 100); myPCA = learn(myPCA, data); newDim(i) = myPCA.DimOut; end newDim = median(newDim); ok(origDim == 5 & newDim == 3, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% reverse component sorting try name = 'reverse component sorting'; X = rand(5,1000); myPCA = learn(spt.pca('Sphering', false), X); pcs = proj(myPCA, X); condition = all(diff(var(pcs, [], 2)) < 0); if condition, myPCA = sort(myPCA, 5:-1:1); pcs = proj(myPCA, X); condition = all(diff(var(pcs, [], 2)) > 0); end ok(condition, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% Cleanup try name = 'cleanup'; clear data ans; rmdir(session.instance.Folder, 's'); session.clear_subsession(); ok(true, name); catch ME ok(ME, name); MEh = [MEh ME]; end %% Testing summary status = finalize(); end
import asyncio from aiogram import Bot, Dispatcher, F from aiogram.types import Message bot = Bot(token='') dp = Dispatcher() # Основная команда /start @dp.message(F.text == '/start') async def cmd_start(message: Message): await message.answer('Добро пожаловать!') # Получение id/имени с помощью message.from_user.id @dp.message(F.text == '/my_id') async def cmd_my_id(message: Message): await message.answer(f'Ваш ID: {message.from_user.id}') await message.reply(f'Ваше имя: {message.from_user.first_name}') await message.answer_photo(photo='url', caption='описание') # Пример отправки картинок @dp.message(F.text == '/send_image') async def cmd_send_image(message: Message): await message.answer_photo(photo='url', caption='описание') # Пример обработки фотографий @dp.message(F.photo) async def get_photo(message: Message): await message.answer(message.photo[-1].file_id) # Пример отправки документов @dp.message(F.text == '/send_doc') async def cmd_send_doc(message: Message): await message.answer_document(document='id', caption='описание') # Пример обработки документов @dp.message(F.document) async def get_document(message: Message): await message.answer(message.document.file_id) # Хэндлер без фильтра, сработает, если ни один выше не сработает. @dp.message() async def echo(message: Message): await message.answer('Я тебя не понимаю...') # Polling, т.е бесконечный цикл проверки апдейтов async def main(): await dp.start_polling(bot) # Функция main() запускается только в случае если скрипт запущен с этого файла if __name__ == '__main__': try: asyncio.run(main()) except KeyboardInterrupt: print('Exit')
=== Easy Image Gallery === Contributors: devrix, nofearinc Tags: image gallery, image, galleries, simple, easy, devrix Requires at least: 3.5 Tested up to: 4.9.2 Stable tag: 1.3 License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Easily create an image gallery on your posts, pages or any custom post type == Description == There comes a time when you need more flexibility than the standard WP gallery offers, That's when this plugin steps in. This plugin's goal is to make it easy to create a gallery and place it wherever you need. A perfect example would be to create a product gallery for an ecommerce website and then have the flexibility to position it where you wanted to match your theme's design. This plugin allows you to easily create an image gallery on any post, page or custom post type. Images are can be added and previewed from the metabox. Images can be re-ordered by drag and drop. Features: 1. Added the possibility to add two or more different galleries on one page 1. Fixed image styles. 1. Fixed some of PHP errors & bugs. 1. Drag and drop re-ordering 1. Add gallery to any post, page or custom post type 1. If more than one image is added to the gallery, the images become grouped in the lightbox so you can easily view the next one 1. CSS and JS are only loaded on pages where needed 1. Images link to larger versions (can be turned off) 1. Fully Localized (translation ready) with .mo and .po files 1. Add multiple images to the gallery at once 1. Uses the thumbnail size specified in Settings -> Media 1. Custom webfont icon for hover effect 1. Uses the new WP 3.5+ media manager for a familiar and intuitive way to add your images = Usage = Use the shortcode or the function to show the gallery. = Shortcode Usage = Use the following shortcode anywhere in the content area to display the gallery [easy_image_gallery gallery="XXX"] Where "XXX" is the ID of the gallery item. = Template Tag Usage = The following template tag is available to display the gallery if( function_exists( 'easy_image_gallery' ) ) { echo easy_image_gallery( "XXX" ); } Where "XXX" is the ID of the gallery item. If you use the template tag above, you will need to remove the default content filter: = Developer Friendly = 1. Modify the gallery HTML using filters 1. Developed with WP Coding Standards 1. Easily add your preferred lightbox script via hooks and filters 1. Easily unhook CSS and add your own styling 1. Pass in a different image size for the thumbnails via filter 1. Minimalistic markup and styling **Stay up to date** *Become a fan on Facebook* [https://www.facebook.com/DevriXLtd](https://www.facebook.com/DevriXLtd "Facebook Devrix") *Follow us on Twitter* [https://twitter.com/wpdevrix](https://twitter.com/wpdevrix) == Installation == 1. Upload the entire `easy-image-gallery` folder to the `/wp-content/plugins/` directory, or just upload the ZIP package via 'Plugins > Add New > Upload' in your WP Admin 1. Activate Easy Image Gallery from the 'Plugins' page in WordPress 1. Configure the plugin's settings from Settings -> Media 1. Create a gallery on any post or page from the added 'Image Gallery' metabox. == Screenshots == 1. The plugin's simple configuration screen. Any existing custom post types will appear here 1. The plugin's simple metabox that is added to the publish/edit screens 1. WordPress 3.5's new media manager is launched when you click "Add gallery images". You can select multiple images to insert into the gallery 1. The plugin's Image Gallery metabox after images have been inserted and the post has been saved 1. The front-end of the website showing the gallery which has been automatically appended to the content 1. Clicking on an image launches the lightbox. Here it's shown with prettyPhoto == Frequently Asked Questions == = Why my galleries don't show up after an update to Version 1.3 or above? = In Version 1.3 of the plugin, we've added a major update. Now, you have the ability to add more than one galleries to your posts or pages. For that reason, we have to introduce Gallery ID as an argument for the shortcode. E.g. you need to use [easy_image_gallery gallery="XXX"], where XXX is the ID of the gallery you want to display. Each of your galleries in the edit screen of your page or post will generate a new shortcode which you'll be able to use in the page or post editor. = fancyBox looks different after upgrading to 1.1 = This plugin mistakenly had fancyBox 2 included. Non-GPL software is not allowed on the WordPress repo (fancyBox 2 is licensed under Creative Commons). It has now been replaced with fancyBox 1, which is GPL compatible. If you'd like to add fancyBox 2 back into the plugin, simply [download this free plugin](http://sumobi.com/shop/easy-image-gallery-extend/ "Extend Easy Image Gallery with additional lightboxes") = Where are the plugin's settings? = In your WordPress admin under Settings -> Media = How can I add another Lightbox script to the plugin? = [Read This](http://sumobi.com/how-to-add-any-lightbox-script-to-the-easy-image-gallery-plugin "How to add another lightbox script to Easy Image Gallery") or [download this free plugin](http://sumobi.com/shop/easy-image-gallery-extend/ "Extend Easy Image Gallery with additional lightboxes") to add Colorbox and fancyBox 2 = How can I use a different thumbnail size for each post type? = [Read This](http://sumobi.com/different-thumbnail-sizes-for-each-post-type-with-easy-image-gallery/ "Different thumbnail sizes for each post type with Easy Image Gallery") == Upgrade Notice == The plugin ownership was transferred to DevriX. There are no functionality changes. We are going to work on a few version, adding some nice feature in the near feature, stay tuned! :) == Changelog == = 1.3.1 = * Release date - May 07, 2018. * Remove jquery-ui.min.js from the plugin and use the WordPress Core version of the library. * Bugfix: add a fallback when the user is using the plugin's function in the code, instead of a shortcoe. = 1.3 = * Release date - January 19, 2018. * Add the possibility to add two or more different galleries on one page/post. * Improved the UI / UX = 1.2 = * Release date - Release date - January 26, 2017. * The plugin ownership was transferred to DevriX. We are going to maintain and update the plugin for now on :) = 1.1.5 = * Update Easy Image Gallery author = 1.1.4 = * Tweak: Updated French translations, props fxbenard = 1.1.3 = * Tweak: Added text domain to plugin headers in accordance with new translation system = 1.1.2 = * Fix: Added esc_attr to title attribute. Captions that included quotes were getting cut off. * Fix: Updated PrettyPhoto JavaScript file to v3.1.6 = 1.1.1 = * Fix: Missing slash on path to CSS file when plugin's CSS is overridden from a child theme = 1.1 = * Tweak: fancybox 2 has been replaced with fancybox 1, as non GPL software is not allowed on the WP repo (fancyBox 2 is license under Creative Commons). = 1.0.6 = * Fix: Settings link on plugins page * Fix PHP notice on Settings -> Media page * Tweak: removed unneeded function = 1.0.5 = * Tweak: The plugin's options page has been moved to settings -> media * Tweak: Renamed the 'thumbnail_image_size' filter name to be 'easy_image_gallery_thumbnail_image_size' so it's unique to the plugin * Tweak: Renamed the 'linked_image_size' filter name to be 'easy_image_gallery_linked_image_size' so it's unique to the plugin = 1.0.4 = * Fix: Images now use the image's caption rather than title field * New: Styling for image placeholder as images are being dragged = 1.0.3 = * Fix: jQuery script that calls light box was being loaded when there were no gallery images = 1.0.2 = * Tweak: Improved loading of scripts = 1.0.1 = * Tweak: Images now link to the "large" image size by default, rather than the original image * Tweak: Removed "remove" links underneath each image and added a [-] on hover to be consistent with WordPress' media manager styling * New: linked_image_size filter for specifying which image size the thumbnails should link to * New: 2 new filters added for overriding the JS for prettyPhoto and fancyBox. easy_image_gallery_prettyphoto_js and easy_image_gallery_fancybox_js = 1.0 = * Initial release
import bcrypt from "bcryptjs"; import mongoose from "mongoose"; const userSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true }, avatarUrl: String, socialOnly: { type: Boolean, default: false }, username: { type: String, required: true, unique: true }, password: { type: String }, name: { type: String, required: true, unique: true }, location: String, comments: [{ type: mongoose.Schema.Types.ObjectId, ref: "Comment" }], videos: [{ type: mongoose.Schema.Types.ObjectId, ref: "Video" }], }); userSchema.pre("save", async function () { // pre, post 메소드 : 스키마에 붙여 사용하는데, 각각 특정 동작 이전, 이후에 어떤 행동을 취할 지를 정의할 수 있다.(Hook를 건다고 생각하면 된다.) // 여기서는 save 하기 전에 호출된다. next를 실행하지 않으면 save가 되지 않기 때문에 다큐먼트 저장 전 최종 검증으로 쓸 수 있다. if (this.isModified("password")) { // bcrypt를 통해 해싱(DB에 비밀번호를 저장할때 랜덤한 값으로 저장) this.password = await bcrypt.hash(this.password, 5); } }); const User = mongoose.model("User", userSchema); export default User;
/* Copyright 2014-2015 Harald Sitter <sitter@kde.org> 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.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. 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, see <http://www.gnu.org/licenses/>. */ #ifndef OPERATION_H #define OPERATION_H #include <pulse/operation.h> namespace QPulseAudio { /** * @brief The PAOperation class * Helps with management of pa_operations. pa_operations need to be expicitly * unref'd after use, so this class is essentially a fancy scoping helper where * destruction of an instance would also unref the held operation (if there is * one). */ class PAOperation { public: /** * @brief PAOperation * @param operation operation to manage the scope of */ PAOperation(pa_operation *operation = nullptr); ~PAOperation(); PAOperation &operator =(pa_operation *operation); /** * @brief operator ! * @return whether or not there is an operation pointer */ bool operator !(); /** * @brief operator bool representing whether there is an operation */ operator bool(); /** * @brief operator * * @return pointer to internal pa_operation object */ pa_operation *&operator *(); private: pa_operation *m_operation; }; } // QPulseAudio #endif // OPERATION_H
;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER LISP) -*- ;;; Copyright (c) 2020 Smart Information Flow Technologies ;;; ;;; File: "driver" ;;; Module: "drivers;sources:" ;;; Version: May 2020 ;; Created 3/20/20 to organize the marshalling and reading of json-based ;; documents with the same range of options as run-an-article has ;; for nxml documents. (in-package :sparser) (defun run-json-article-from-handle (&key (n 1) (corpus '0713-pdf) ((:sexp return-sexp) nil) (sweep t) (read t) (quiet t) (skip-errors t) (verbose t) (show-sect nil) (stats nil)) "Assemble the file handle, use it to assemble an article, and pass the article to run-json-article. Standard way to run an article from the json corpus. Designed for iterating over: (loop for i from 11 to 50 do (run-json-article-from-handle :n i)) Passes its keyword arguments through to the routines that actually use them. " (declare (special *write-article-objects-file*)) (multiple-value-bind (article para-count sexp) (make-article-from-handle :n n :corpus corpus :verbose verbose) (let ((result (if return-sexp sexp (run-json-article article :sweep sweep :read read :quiet quiet :show-sect show-sect :stats stats :skip-errors skip-errors :verbose verbose :para-count para-count)))) (when *write-article-objects-file* (write-article-objects-file article)) result))) (defun run-json-article (article &key (sweep t) (read t) para-count (quiet t) (skip-errors t) (verbose t) (show-sect nil) (stats nil)) "Modeled directly on run-an-article in R3. This is how we take a article individual and pass it through the document-type driven reader methods; :sweep -- first pass that adds sentences to the paragraphs in the article. :read -- second pass where the sentences are parsed. Runs for side-effects on the 'content' fields of the document elements. :quiet -- turn off printing from the parser. If it is nil you will aways see the bracketing of the phrases. :skip-errors -- run via an error catch that traps any errors rather than going into the debugger. Error is printed to standard- out, usually includes the text of the sentence where it occurred." (let ((*trap-error-skip-sentence* skip-errors)) (declare (special *trap-error-skip-sentence* *article*)) (setq *article* article) ;; If sweep is nil, this returns the raw document, ;; i.e. no section-of-sections or sentences. (when sweep ;; Make the sentences and implicit subsections. ;; Same as r3::sweep-article but w/o the handler. (sp::sweep-document article)) (unless sweep ;; later pass contingent on first (setq read nil stats nil)) (when read (if quiet (with-total-quiet (sp::read-from-document article)) (with-total-quiet (let ((*show-section-printouts* show-sect)) (declare (special *show-section-printouts*)) (read-from-document article))))) (if stats (summary-document-stats article) (else (when para-count (format t "~&~a paragraphs~%" para-count)) (report-time-to-read-article article))) (when *write-article-objects-file* (write-article-objects-file article)) article)) (defun make-article-from-handle (&key (n 1) (corpus '0713-pdf) (verbose t)) "Checks that we've specified enough information, then calls make-json-article-from-file-handle to extract the Lisp sexp from the JSON file, pass it to make-document to assemble an article from it. Returns the article and the sexp that is the translation of the JSON." (unless (and (and corpus n) (numberp n) (or (symbolp corpus) (stringp corpus))) (return-from make-article-from-handle nil)) (make-json-article-from-file-handle (corpus-file-handle corpus n) :verbose verbose)) (defun make-json-article-from-file-handle (file-handle &key (verbose t) save?) "Locates the file indicated by the handle, reads it and converts its json to an sexp (decode-json-from-source), has the sexp interpreted to instantiate an instance of an article (make-document). Returns the article, the number of paragraphs in it and the raw sexp. Saves the article if the 'save?' parameter is set." (let (file-namestring filepath sexp) (unless (setq file-namestring (decoded-file file-handle)) (warn "No registered json path found for file handle ~a.~ ~%Run collect-json-directory to register a directory's files." file-handle) (return-from make-json-article-from-file-handle nil)) (unless (setq filepath (probe-file file-namestring)) (error "probe-file returned nil for file path ~s" file-namestring)) (unless (setq sexp (cl-json:decode-json-from-source filepath)) (warn "The json file looks empty.") (return-from make-json-article-from-file-handle nil)) (when verbose (format t "~&Reading ~a~%" file-handle)) (multiple-value-bind (article para-count) (make-document sexp file-namestring :handle file-handle) (when save? (save-article file-handle article)) (values article para-count sexp)))) ;;;-------------------- ;;; saving out results ;;;-------------------- (defparameter *write-article-objects-file* nil "If T, then save the facts for the article to a file with name derived from the article") (defun corpus-file-handle (corpus n) (intern (string-append corpus "-" n) (find-package :sparser))) (defun corpus-file-namestring (corpus n) (decoded-file (corpus-file-handle corpus n))) (defun mentions-filename (&key corpus n) (let ((article-namestring (json-relative-pathname (corpus-file-namestring corpus n)))) (declare (special article-namestring)) (json-absolute-pathname (format nil "~amentions/mentions-in-~a.lisp" (directory-namestring article-namestring) (pathname-name (file-namestring article-namestring)))))) (defun article-relevant-mentions (article &aux (contents (contents article))) (loop for slot-name in *term-buckets* as bucket = (slot-value contents slot-name) unless (member slot-name '(other comlex)) append (loop for mention-set in bucket append (third mention-set)))) (defun article-corpus (article &aux (name (name article))) (intern (subseq (string name) 0 (search "-" (string name) :from-end t)) :sp)) (defun article-corpus-index (article &aux (name (name article))) (read-from-string (subseq (string name) (+ 1 (search "-" (string name) :from-end t))))) (defun write-article-objects-file (article) (let* ((corpus (article-corpus article)) (n (article-corpus-index article)) (mention-file (mentions-filename :corpus corpus :n n))) (ensure-directories-exist mention-file) (with-open-file (mf mention-file :direction :output :if-exists :supersede :if-does-not-exist :create) (format mf "(in-package :sp)~%;;;;;mentions for article ~s~%" (name article)) (push-list-on-param (name article) (grouped-article-mentions article) mf) mention-file))) (defparameter *article-mentions* nil) (defparameter *grouped-mention-article* nil) (defun grouped-article-mentions (article &optional (with-offsets nil)) (setq *grouped-mention-article* article) (setq *article-mentions* (article-relevant-mentions article)) (list (name article) (sort (group-by (loop for g in (group-by (loop for m in *article-mentions* unless (itypep (mention-head-referent m) '(:or number-sequence)) collect m) #'(lambda(m) (handler-case (krisp->sexpr (mention-head-referent m)) (error (e) (list '**error-in-krisp->sexpr**))))) collect (list (car g) (loop for m in (remove-duplicates (second g) :test #'equal) collect (let* ((str (car (mentioned-in-article-where m))) (where (intern (subseq str (+ 1 (search "." str))) (find-package :sp)))) (if with-offsets (list where (mentioned-where m)) where))))) #'caar) #'string< :key #'car))) (defparameter *gam* nil) (defparameter *dgs* nil) (defun article-mention-ht (article) (let ((ht (make-hash-table :size 100 :test #'equal))) (loop for group in (setq *gam* (second (grouped-article-mentions article t))) do (loop for descrip-group in (setq *dgs* (second group)) do (setf (gethash (sp-prin1-to-string (car descrip-group)) ht ) (second descrip-group)))) ht)) ;;;------------------------ ;;; saving article objects ;;;------------------------ (defvar *handles-to-articles* (make-hash-table) "Handle symbols to article objects") (defvar *handles-analyzed* nil "Simple list in reverse chronological order") (defgeneric save-article (handle article) (:method ((handle symbol) (article article)) (push handle *handles-analyzed*) (setf (gethash handle *handles-to-articles*) article)) (:method ((handle string) (article article)) (push handle *handles-analyzed*) (setf (gethash handle *handles-to-articles*) article))) (defgeneric get-article (handle) (:method ((handle symbol)) (gethash handle *handles-to-articles*)) (:method ((handle string)) (gethash handle *handles-to-articles*))) (defun initialize-article-saving () (clrhash *handles-to-articles*) (setq *handles-analyzed* nil)) ;;;-------------- ;;; original set ;;;-------------- #| These are quick and dirty -- don't incorporate any way to change the default setting. Intended to see a mass effect such as collecting vocabulary 1. (collect-json-directory) -- prime the pump 2. (do-next-json) --> #<article > Sets *current-json-based-article* to the article so it can be accessed 3. (run-json-article *current-json-based-article* :quiet nil :show-sect t) |# (defun pull-json-and-run (&optional quiet?) (do-next-json) (if quiet? (run-json-article *current-json-based-article*) (run-json-article *current-json-based-article* :quiet nil :show-sect t))) (defun run-n-json-articles (n) (dotimes (i n) (pull-json-and-run :quiet))) (defvar *article-short-name* nil) (defvar *article-json* nil) (defvar *json-article* nil) (defun run-nth-json-article (n &key ((:corpus article-set-name) '0713-PDF) (quiet t) (skip-errors t) (show-sect nil) (sexp nil)) (let* ((*article-short-name* (format nil "~a-~a" article-set-name n)) ; file-handle (file-path-name (decoded-file *article-short-name*)) (file-path (when file-path-name (probe-file file-path-name)))) (unless file-path-name (format t "~%~%No article #~s~%" n) (return-from run-nth-json-article nil)) (setq *article-json* (cl-json::decode-json-from-source file-path)) (if sexp ;; return the decoding and don't do anything else *article-json* (progn (setq *json-article* (make-document *article-json* file-path :handle (if (stringp *article-short-name*) (intern *article-short-name* :sp) *article-short-name*))) (extract-authors-and-bibliography *article-json*) (run-json-article *json-article* :quiet quiet :skip-errors skip-errors))))) ;;;------------------------- ;;; gather paragraph counts ;;;------------------------- (defun article-paragraph-count (&key (n 1) (corpus '0713-pdf) (stream *standard-output*)) "Have the article assembled from the JSON file indicated by the handle, collect the paragraph count, and emit the handle and count on the stream." (let ((handle (corpus-file-handle corpus n))) (multiple-value-bind (article para-count sexp) (make-article-from-handle :n n :corpus corpus :verbose nil) (format stream "~&(~a . ~a)" handle para-count)))) (defun save-article-paragraph-count (count &optional (filepath "/users/ddm/temp/counts.lisp")) (with-open-file (stream filepath :direction :output :if-does-not-exist :create :if-exists :append) (loop for i from 1 to count do (article-paragraph-count :n i :stream stream))))
// let forEach = (arr, callback) =>{ // for(let i = 0; i < arr.length; i++){ // callback(arr[i],i, arr) // } // } let arr = [1,2,3,4,5,6] // forEach(arr, (element, index) => console.log(element, index)) arr.forEach((element, index) => console.log(element,index)) ////////// .map ////////// // let map = (arr, callback)=>{ // let results =[] // for( let i = 0; i < arr.length; i++){ // results.push(callback(arr[i])) // } // return results // } // let mappedArr = map(arr, (element)=> element *2) // console.log(mappedArr) arr.map((element)=> console.log(element *2)) let stringArray = ["apples", "bananas", "kiwi", "oranges"] let filteredArray = stringArray.filter((element, index, array) =>{ return element.length > 5 }) console.log(filteredArray) var users = [ { id: '12d', email: 'tyler@gmail.com', name: 'Tyler', address: '167 East 500 North' }, { id: '15a', email: 'cahlan@yahoo.com', name: 'Cahlan', address: '135 East 320 North' }, { id: '16t', email: 'ryan@gmail.com', name: 'Ryan', address: '192 East 32 North' }, ] // users.forEach((user)=>{ // // console.log(`${user.name} has the email address of ${user.email}`) // user.nameID = user.id + user.name // }) // console.log(users) let mappedUsers = users.map((user)=>{ return user.email }) console.log(mappedUsers) // .forEach() = Doesn't return a new array // .map() = returns a new array so you must assign it to a variable // .filter() = returns a new array so you must assign it to a variable let filteredUsers = users.filter((user) =>{ return user.email.includes("gmail") }) console.log(filteredUsers) const dogProducts = [ { name: 'leash', colors: ['red', 'blue', 'green'], category: 1, inventory: 30, basePrice: 13.99, displayPrice: 13.99 }, { name: 'chew toy', colors: ['brown'], category: 2, inventory: 120, basePrice: 6.00, displayPrice: 6.00 }, { name: 'rope', colors: ['blue & green', 'red & yellow'], category: 2, inventory: 75, basePrice: 4.99, displayPrice: 4.99 } ] let myTotal = dogProducts.reduce((acc, curr) =>{ // console.log(acc) return +(acc +curr.basePrice).toFixed(2) },0) console.log(myTotal) // --------------------------------------------------------- const catProducts = [ { name: 'mouse toy', colors: ['pink', 'grey', 'black'], category: 2, inventory: 125, basePrice: 2.50, displayPrice: 2.50 }, { name: 'cat sweater', colors: ['black'], category: 1, inventory: 15, basePrice: 10.00, displayPrice: 10.00 }, { name: 'straching post', colors: ['tan'], category: 2, inventory: 40, basePrice: 22.99, displayPrice: 22.99 } ] //// CHAINING METHOD //// let myCatTotal = catProducts.filter((element)=>{ return element.displayPrice < 20 }).reduce((acc, curr) =>{ return curr.displayPrice + acc },0) ///one line but same answer /// let myCatTotalOneLine = catProducts.filter((element)=>element.displayPrice < 20).reduce((acc,curr) => curr.displayPrice + acc,0) console.log(myCatTotal) // let func = ()=>{} // let array = [] // let obj = {} ////CALLBACK///// // let five = (x,y)=>{ // return x+y // } // let ten = (cb)=>{ // return cb(2,3) + 5 //cb is referencing another function -- in this case "let five" // } // console.log(ten(five))
To begin we will be working in our terminal which can be found if you click on the editor tab in the top left, and then navigating down to the bottom of your screen. Create a new empty file called `my-new-file` in your home directory <br> ### Solution First we make sure we're in our home directory using ```plain cd ~ ```{{exec}} We can list the current directory using ```plain pwd ```{{exec}} Now we create the file ```plain mkdir my-new-file ```{{exec}}
/* Copyright (c) 2010 Steve Oldmeadow Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. $Id$ */ /** @file @b IMPORTANT There are 3 different ways of using CocosDenshion. Depending on which you choose you will need to include different files and frameworks. @par SimpleAudioEngine This is recommended for basic audio requirements. If you just want to play some sound fx and some background music and have no interest in learning the lower level workings then this is the interface to use. Requirements: - Firmware: OS 2.2 or greater - Files: SimpleAudioEngine.*, CocosDenshion.* - Frameworks: OpenAL, AudioToolbox, AVFoundation @par CDAudioManager CDAudioManager is basically a thin wrapper around an AVAudioPlayer object used for playing background music and a CDSoundEngine object used for playing sound effects. It manages the audio session for you deals with audio session interruption. It is fairly low level and it is expected you have some understanding of the underlying technologies. For example, for many use cases regarding background music it is expected you will work directly with the backgroundMusic AVAudioPlayer which is exposed as a property. Requirements: - Firmware: OS 2.2 or greater - Files: CDAudioManager.*, CocosDenshion.* - Frameworks: OpenAL, AudioToolbox, AVFoundation @par CDSoundEngine CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch example. It can playback up to 32 sounds simultaneously with control over pitch, pan and gain. It can be set up to handle audio session interruption automatically. You may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine because you require OS 2.0 compatibility. Requirements: - Firmware: OS 2.0 or greater - Files: CocosDenshion.* - Frameworks: OpenAL, AudioToolbox */ #import <OpenAL/al.h> #import <OpenAL/alc.h> #import <AudioToolbox/AudioToolbox.h> #import <Foundation/Foundation.h> #import "CDConfig.h" #if !defined(CD_DEBUG) || CD_DEBUG == 0 #define CDLOG(...) do {} while (0) #define CDLOGINFO(...) do {} while (0) #elif CD_DEBUG == 1 #define CDLOG(...) NSLog(__VA_ARGS__) #define CDLOGINFO(...) do {} while (0) #elif CD_DEBUG > 1 #define CDLOG(...) NSLog(__VA_ARGS__) #define CDLOGINFO(...) NSLog(__VA_ARGS__) #endif // CD_DEBUG #import "CDOpenALSupport.h" //Tested source limit on 2.2.1 and 3.1.2 with up to 128 sources and appears to work. Older OS versions e.g 2.2 may support only 32 #define CD_SOURCE_LIMIT 32 //Total number of sources we will ever want, may actually get less #define CD_NO_SOURCE 0xFEEDFAC //Return value indicating playback failed i.e. no source #define CD_IGNORE_AUDIO_SESSION 0xBEEFBEE //Used internally to indicate audio session will not be handled #define CD_MUTE 0xFEEDBAB //Return value indicating sound engine is muted or non functioning #define CD_NO_SOUND = -1; #define CD_SAMPLE_RATE_HIGH 44100 #define CD_SAMPLE_RATE_MID 22050 #define CD_SAMPLE_RATE_LOW 16000 #define CD_SAMPLE_RATE_BASIC 8000 #define CD_SAMPLE_RATE_DEFAULT 44100 extern NSString * const kCDN_BadAlContext; extern NSString * const kCDN_AsynchLoadComplete; extern float const kCD_PitchDefault; extern float const kCD_PitchLowerOneOctave; extern float const kCD_PitchHigherOneOctave; extern float const kCD_PanDefault; extern float const kCD_PanFullLeft; extern float const kCD_PanFullRight; extern float const kCD_GainDefault; enum bufferState { CD_BS_EMPTY = 0, CD_BS_LOADED = 1, CD_BS_FAILED = 2 }; typedef struct _sourceGroup { int startIndex; int currentIndex; int totalSources; bool enabled; bool nonInterruptible; int *sourceStatuses;//pointer into array of source status information } sourceGroup; typedef struct _bufferInfo { ALuint bufferId; int bufferState; void* bufferData; ALenum format; ALsizei sizeInBytes; ALsizei frequencyInHertz; } bufferInfo; typedef struct _sourceInfo { bool usable; ALuint sourceId; ALuint attachedBufferId; } sourceInfo; #pragma mark CDAudioTransportProtocol @protocol CDAudioTransportProtocol <NSObject> /** Play the audio */ -(BOOL) play; /** Pause the audio, retain resources */ -(BOOL) pause; /** Stop the audio, release resources */ -(BOOL) stop; /** Return playback to beginning */ -(BOOL) rewind; @end #pragma mark CDAudioInterruptProtocol @protocol CDAudioInterruptProtocol <NSObject> /** Is audio mute */ -(BOOL) mute; /** If YES then audio is silenced but not stopped, calls to start new audio will proceed but silently */ -(void) setMute:(BOOL) muteValue; /** Is audio enabled */ -(BOOL) enabled; /** If NO then all audio is stopped and any calls to start new audio will be ignored */ -(void) setEnabled:(BOOL) enabledValue; @end #pragma mark CDUtilities /** Collection of utilities required by CocosDenshion */ @interface CDUtilities : NSObject { } /** Fundamentally the same as the corresponding method is CCFileUtils but added to break binding to cocos2d */ +(NSString*) fullPathFromRelativePath:(NSString*) relPath; @end #pragma mark CDSoundEngine /** CDSoundEngine is built upon OpenAL and works with SDK 2.0. CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch example. It can playback up to 32 sounds simultaneously with control over pitch, pan and gain. It can be set up to handle audio session interruption automatically. You may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine because you require OS 2.0 compatibility. Requirements: - Firmware: OS 2.0 or greater - Files: CocosDenshion.* - Frameworks: OpenAL, AudioToolbox @since v0.8 */ @class CDSoundSource; @interface CDSoundEngine : NSObject <CDAudioInterruptProtocol> { bufferInfo *_buffers; sourceInfo *_sources; sourceGroup *_sourceGroups; ALCcontext *context; NSUInteger _sourceGroupTotal; UInt32 _audioSessionCategory; BOOL _handleAudioSession; ALfloat _preMuteGain; NSObject *_mutexBufferLoad; BOOL mute_; BOOL enabled_; ALenum lastErrorCode_; BOOL functioning_; float asynchLoadProgress_; BOOL getGainWorks_; //For managing dynamic allocation of sources and buffers int sourceTotal_; int bufferTotal; } @property (readwrite, nonatomic) ALfloat masterGain; @property (readonly) ALenum lastErrorCode;//Last OpenAL error code that was generated @property (readonly) BOOL functioning;//Is the sound engine functioning @property (readwrite) float asynchLoadProgress; @property (readonly) BOOL getGainWorks;//Does getting the gain for a source work /** Total number of sources available */ @property (readonly) int sourceTotal; /** Total number of source groups that have been defined */ @property (readonly) NSUInteger sourceGroupTotal; /** Sets the sample rate for the audio mixer. For best performance this should match the sample rate of your audio content */ +(void) setMixerSampleRate:(Float32) sampleRate; /** Initializes the engine with a group definition and a total number of groups */ -(id)init; /** Plays a sound in a channel group with a pitch, pan and gain. The sound could played looped or not */ -(ALuint) playSound:(int) soundId sourceGroupId:(int)sourceGroupId pitch:(float) pitch pan:(float) pan gain:(float) gain loop:(BOOL) loop; /** Creates and returns a sound source object for the specified sound within the specified source group. */ -(CDSoundSource *) soundSourceForSound:(int) soundId sourceGroupId:(int) sourceGroupId; /** Stops playing a sound */ - (void) stopSound:(ALuint) sourceId; /** Stops playing a source group */ - (void) stopSourceGroup:(int) sourceGroupId; /** Stops all playing sounds */ -(void) stopAllSounds; -(void) defineSourceGroups:(NSArray*) sourceGroupDefinitions; -(void) defineSourceGroups:(int[]) sourceGroupDefinitions total:(NSUInteger) total; -(void) setSourceGroupNonInterruptible:(int) sourceGroupId isNonInterruptible:(BOOL) isNonInterruptible; -(void) setSourceGroupEnabled:(int) sourceGroupId enabled:(BOOL) enabled; -(BOOL) sourceGroupEnabled:(int) sourceGroupId; -(BOOL) loadBufferFromData:(int) soundId soundData:(ALvoid*) soundData format:(ALenum) format size:(ALsizei) size freq:(ALsizei) freq; -(BOOL) loadBuffer:(int) soundId filePath:(NSString*) filePath; -(void) loadBuffersAsynchronously:(NSArray *) loadRequests; -(BOOL) unloadBuffer:(int) soundId; -(ALCcontext *) openALContext; /** Returns the duration of the buffer in seconds or a negative value if the buffer id is invalid */ -(float) bufferDurationInSeconds:(int) soundId; /** Returns the size of the buffer in bytes or a negative value if the buffer id is invalid */ -(ALsizei) bufferSizeInBytes:(int) soundId; /** Returns the sampling frequency of the buffer in hertz or a negative value if the buffer id is invalid */ -(ALsizei) bufferFrequencyInHertz:(int) soundId; /** Used internally, never call unless you know what you are doing */ -(void) _soundSourcePreRelease:(CDSoundSource *) soundSource; @end #pragma mark CDSoundSource /** CDSoundSource is a wrapper around an OpenAL sound source. It allows you to manipulate properties such as pitch, gain, pan and looping while the sound is playing. CDSoundSource is based on the old CDSourceWrapper class but with much added functionality. @since v1.0 */ @interface CDSoundSource : NSObject <CDAudioTransportProtocol, CDAudioInterruptProtocol> { ALenum lastError; @public ALuint _sourceId; ALuint _sourceIndex; CDSoundEngine* _engine; int _soundId; float _preMuteGain; BOOL enabled_; BOOL mute_; } @property (readwrite, nonatomic) float pitch; @property (readwrite, nonatomic) float gain; @property (readwrite, nonatomic) float pan; @property (readwrite, nonatomic) BOOL looping; @property (readonly) BOOL isPlaying; @property (readwrite, nonatomic) int soundId; /** Returns the duration of the attached buffer in seconds or a negative value if the buffer is invalid */ @property (readonly) float durationInSeconds; /** Stores the last error code that occurred. Check against AL_NO_ERROR */ @property (readonly) ALenum lastError; /** Do not init yourself, get an instance from the sourceForSound factory method on CDSoundEngine */ -(id)init:(ALuint) theSourceId sourceIndex:(int) index soundEngine:(CDSoundEngine*) engine; @end #pragma mark CDAudioInterruptTargetGroup /** Container for objects that implement audio interrupt protocol i.e. they can be muted and enabled. Setting mute and enabled for the group propagates to all children. Designed to be used with your CDSoundSource objects to get them to comply with global enabled and mute settings if that is what you want to do.*/ @interface CDAudioInterruptTargetGroup : NSObject <CDAudioInterruptProtocol> { BOOL mute_; BOOL enabled_; NSMutableArray *children_; } -(void) addAudioInterruptTarget:(NSObject<CDAudioInterruptProtocol>*) interruptibleTarget; @end #pragma mark CDAsynchBufferLoader /** CDAsynchBufferLoader TODO */ @interface CDAsynchBufferLoader : NSOperation { NSArray *_loadRequests; CDSoundEngine *_soundEngine; } -(id) init:(NSArray *)loadRequests soundEngine:(CDSoundEngine *) theSoundEngine; @end #pragma mark CDBufferLoadRequest /** CDBufferLoadRequest */ @interface CDBufferLoadRequest: NSObject { NSString *filePath; int soundId; //id loader; } @property (readonly) NSString *filePath; @property (readonly) int soundId; - (id)init:(int) theSoundId filePath:(const NSString *) theFilePath; @end /** Interpolation type */ typedef enum { kIT_Linear, //!Straight linear interpolation fade kIT_SCurve, //!S curved interpolation kIT_Exponential //!Exponential interpolation } tCDInterpolationType; #pragma mark CDFloatInterpolator @interface CDFloatInterpolator: NSObject { float start; float end; float lastValue; tCDInterpolationType interpolationType; } @property (readwrite, nonatomic) float start; @property (readwrite, nonatomic) float end; @property (readwrite, nonatomic) tCDInterpolationType interpolationType; /** Return a value between min and max based on t which represents fractional progress where 0 is the start and 1 is the end */ -(float) interpolate:(float) t; -(id) init:(tCDInterpolationType) type startVal:(float) startVal endVal:(float) endVal; @end #pragma mark CDPropertyModifier /** Base class for classes that modify properties such as pitch, pan and gain */ @interface CDPropertyModifier: NSObject { CDFloatInterpolator *interpolator; float startValue; float endValue; id target; BOOL stopTargetWhenComplete; } @property (readwrite, nonatomic) BOOL stopTargetWhenComplete; @property (readwrite, nonatomic) float startValue; @property (readwrite, nonatomic) float endValue; @property (readwrite, nonatomic) tCDInterpolationType interpolationType; -(id) init:(id) theTarget interpolationType:(tCDInterpolationType) type startVal:(float) startVal endVal:(float) endVal; /** Set to a fractional value between 0 and 1 where 0 equals the start and 1 equals the end*/ -(void) modify:(float) t; -(void) _setTargetProperty:(float) newVal; -(float) _getTargetProperty; -(void) _stopTarget; -(Class) _allowableType; @end #pragma mark CDSoundSourceFader /** Fader for CDSoundSource objects */ @interface CDSoundSourceFader : CDPropertyModifier{} @end #pragma mark CDSoundSourcePanner /** Panner for CDSoundSource objects */ @interface CDSoundSourcePanner : CDPropertyModifier{} @end #pragma mark CDSoundSourcePitchBender /** Pitch bender for CDSoundSource objects */ @interface CDSoundSourcePitchBender : CDPropertyModifier{} @end #pragma mark CDSoundEngineFader /** Fader for CDSoundEngine objects */ @interface CDSoundEngineFader : CDPropertyModifier{} @end
from __future__ import division from sklearn import datasets, decomposition from sklearn.utils.extmath import randomized_svd from scipy import stats, sparse import graphtools import numpy as np import harmonicalignment import unittest import warnings warnings.filterwarnings( "ignore", category=PendingDeprecationWarning, message="the matrix subclass is not the recommended way to represent " "matrices or deal with linear algebra ", ) def randPCA(X, n_components=None, random_state=None): pca_op = decomposition.PCA(n_components, random_state=random_state) U, S, VT = pca_op._fit(X) return U, S, VT.T def randSVD(X, n_components=None, random_state=None): if n_components is None: n_components = min(X.shape) U, S, VT = randomized_svd(X, n_components, random_state=random_state) return U, S, VT.T def diffusionCoordinates(X, decay, knn, n_pca, random_state=None): # diffusion maps with normalized Laplacian # n_pca = 0 corresponds to NO pca G = graphtools.Graph( X, knn=knn, decay=decay, n_pca=n_pca, use_pygsp=True, thresh=0, random_state=random_state, ) n_samples = X.shape[0] W = G.W.tocoo() # W / (DD^T) W.data = W.data / (G.dw[W.row] * G.dw[W.col]) # this is the anisotropic kernel nsqrtD = sparse.dia_matrix((np.array(np.sum(W, 0)) ** (-0.5), [0]), W.shape) L = sparse.eye(n_samples) - nsqrtD.dot(W).dot(nsqrtD) U, S, _ = randSVD(L, random_state=random_state) # smallest to largest S_idx = np.argsort(S) U, S = U[:, S_idx], S[S_idx] # trim trivial information U, S = U[:, 1:], S[1:] return U, S def itersine(x): return np.sin(0.5 * np.pi * (np.cos(np.pi * x)) ** 2) * ((x >= -0.5) & (x <= 0.5)) def wavelet(loc, scale, overlap): def wavelet_i(x): return itersine(x / scale - loc / overlap + 1 / 2) * np.sqrt(2 / overlap) return wavelet_i def build_wavelets(lmbda, n_filters, overlap): lambda_max = max(lmbda) # maximum laplacian eigenvalue scale = lambda_max / (n_filters - overlap + 1) * (overlap) # response evaluation... this is the money lambda_filt = np.zeros((len(lmbda), n_filters)) for i in range(n_filters): filter_i = wavelet(loc=i + 1, scale=scale, overlap=overlap) lambda_filt[:, i] = filter_i(lmbda) return lambda_filt class TestDigits(unittest.TestCase): def setUp(self): self.random_state = 42 np.random.seed(self.random_state) digits = datasets.load_digits() labels = digits["target"] imgs = digits["data"] self.n_samples = 100 self.n_features = imgs.shape[1] # kernel params self.knn_1 = 20 self.decay_1 = 20 self.pca_1 = 32 self.knn_2 = self.knn_1 self.decay_2 = self.decay_1 self.pca_2 = self.pca_1 # Z = transformed self.knn_transform = 10 self.decay_transform = 10 self.pca_transform = None # diffusion time for final embedding self.diffusion_t = 1 self.overlap = 2 self.pct = 0.5 self.n_filters = 4 self.run_example(imgs, labels) def run_example(self, imgs, labels): self.generate_data(imgs, labels) self.align() def generate_data(self, imgs, labels): np.random.seed(self.random_state) random_rotation = stats.ortho_group.rvs(self.n_features) # random orthogonal rotation colReplace = np.random.choice( self.n_features, np.floor(self.pct * self.n_features).astype(int), replace=False, ) random_rotation[:, colReplace] = np.eye(self.n_features)[:, colReplace] # sample two sets of digits from MNIST X1_idx = np.random.choice(len(labels), self.n_samples, replace=False) X2_idx = np.random.choice(len(labels), self.n_samples, replace=False) # slice the digits self.X1 = imgs[X1_idx, :] X2 = imgs[X2_idx, :] # transform X2 self.X2_rotate = X2.dot(random_rotation.T) def align(self): np.random.seed(self.random_state) phi_X, lambda_X = diffusionCoordinates( self.X1, self.decay_1, self.knn_1, self.pca_1, random_state=self.random_state, ) phi_Y, lambda_Y = diffusionCoordinates( self.X2_rotate, self.decay_2, self.knn_2, self.pca_2, random_state=self.random_state, ) X1_fourier = phi_X.T.dot(self.X1) X2_rotate_fourier = phi_Y.T.dot(self.X2_rotate) wavelet_1 = build_wavelets(lambda_X, self.n_filters, self.overlap) wavelet_2 = build_wavelets(lambda_Y, self.n_filters, self.overlap) wavelet_1_eval = np.conj(wavelet_1)[:, :, None] * X1_fourier[:, None, :] wavelet_2_eval = np.conj(wavelet_2)[:, :, None] * X2_rotate_fourier[:, None, :] # correlate the spectral domain wavelet coefficients. blocks = np.zeros( (wavelet_1_eval.shape[0], self.n_filters, wavelet_2_eval.shape[0]) ) for i in range(self.n_filters): # for each filter, build a correlation blocks[:, i, :] = wavelet_1_eval[:, i, :].dot(wavelet_2_eval[:, i, :].T) # construct transformation matrix transform = np.sum(blocks, axis=1) # the orthogonal transformation matrix Ut, _, Vt = randSVD(transform, random_state=self.random_state) transform_orth = Ut.dot(Vt.T) # compute transformed data phi_X_transform = phi_X.dot(transform_orth) # phi_X in span(phi_Y) phi_Y_transform = phi_Y.dot(transform_orth.T) # phi_Y in span(phi_X) E = np.vstack( [np.hstack([phi_X, phi_X_transform]), np.hstack([phi_Y_transform, phi_Y])] ) E_weighted = E.dot( np.diag(np.exp(-self.diffusion_t * np.concatenate([lambda_X, lambda_Y]))) ) # store output self.phi_X = phi_X self.phi_Y = phi_Y self.lambda_X = lambda_X self.lambda_Y = lambda_Y self.wavelet_1_eval = wavelet_1_eval self.wavelet_2_eval = wavelet_2_eval self.transform = transform self.transform_orth = transform_orth self.E_weighted = E_weighted def test_harmonicalignment(self): G = harmonicalignment.HarmonicAlignment( self.n_filters, t=self.diffusion_t, overlap=self.overlap, n_jobs=1, verbose=0, random_state=self.random_state, knn_X=self.knn_1, knn_Y=self.knn_2, knn_XY=self.knn_transform, decay_X=self.decay_1, decay_Y=self.decay_2, decay_XY=self.decay_transform, n_pca_X=self.pca_1, n_pca_Y=self.pca_2, n_pca_XY=self.pca_transform, ).align(self.X1, self.X2_rotate) assert G.K.shape == (self.n_samples * 2, self.n_samples * 2) # parallel processing harmonic_op = harmonicalignment.HarmonicAlignment( self.n_filters, t=self.diffusion_t, overlap=self.overlap, n_jobs=-1, verbose=0, random_state=self.random_state, knn_X=self.knn_1, knn_Y=self.knn_2, knn_XY=self.knn_transform, decay_X=self.decay_1, decay_Y=self.decay_2, decay_XY=self.decay_transform, n_pca_X=self.pca_1, n_pca_Y=self.pca_2, n_pca_XY=self.pca_transform, ) harmonic_op.fit(self.X1, self.X2_rotate) harmonic_op.plot_wavelets() G2 = harmonic_op.align(self.X1, self.X2_rotate) np.testing.assert_allclose((G.K - G2.K).data, 0, rtol=1e-10, atol=1e-10) DM = harmonic_op.diffusion_map() assert DM.shape == (self.n_samples * 2, self.n_samples * 2 - 1) def test_diffusion_coords(self): np.testing.assert_allclose( self.lambda_X, harmonicalignment.math.diffusionCoordinates( self.X1, knn=self.knn_1, decay=self.decay_1, n_pca=self.pca_1, random_state=self.random_state, )[1], atol=1e-3, rtol=1e-2, ) def test_diffusion_map(self): np.testing.assert_equal( self.phi_X * np.exp(-self.diffusion_t * self.lambda_X), harmonicalignment.math.diffusionMap( self.phi_X, self.lambda_X, t=self.diffusion_t ), ) def test_wavelets(self): for filter_idx in range(self.n_filters): np.testing.assert_equal( self.wavelet_1_eval[:, filter_idx, :], harmonicalignment.evaluate_itersine_wavelet( filter_idx, self.X1, self.phi_X, self.lambda_X, self.n_filters, overlap=self.overlap, ), ) def test_correlate(self): np.testing.assert_equal( self.transform, harmonicalignment.correlate_wavelets( self.X1, self.phi_X, self.lambda_X, self.X2_rotate, self.phi_Y, self.lambda_Y, self.n_filters, overlap=self.overlap, ), ) def test_orthogonalize(self): np.testing.assert_allclose( self.transform_orth, harmonicalignment.math.orthogonalize(self.transform) ) def test_combine(self): ( phi_combined, lambda_combined, ) = harmonicalignment.harmonicalignment.combine_eigenvectors( self.transform_orth, self.phi_X, self.phi_Y, self.lambda_X, self.lambda_Y ) E = phi_combined @ np.diag(lambda_combined ** self.diffusion_t) np.testing.assert_equal(self.E_weighted, E)
// BeginLicense: // Part of: spacelibs - reusable libraries for 3d space calculations // Copyright (C) 2017 Carsten Arnholm // All rights reserved // // This file may be used under the terms of either the GNU General // Public License version 2 or 3 (at your option) as published by the // Free Software Foundation and appearing in the files LICENSE.GPL2 // and LICENSE.GPL3 included in the packaging of this file. // // This file is provided "AS IS" with NO WARRANTY OF ANY KIND, // INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE. // EndLicense: #ifndef MUTABLE_POLYHEDRON3D_H #define MUTABLE_POLYHEDRON3D_H #include "polyhealer_config.h" #include "spacemath/polyhedron3d.h" #include "spacemath/vec3d.h" using namespace spacemath; #include <map> #include <unordered_map> #include <unordered_set> typedef std::unordered_map<id_edge, vertex_pair> edge_vertex_map; // edge end vertices typedef std::unordered_set<id_edge> edge_set; // a set of edges typedef std::unordered_set<id_face> face_set; // a set of faces typedef std::unordered_map<id_edge, face_set> edge_face_map; // faces connected to an edge typedef std::unordered_map<id_face, edge_set> face_edge_map; // edges connected to a face // mutable_polyhedron3d is similar to a polyhedron3d, but supports additional // datastructures to support operations to modify it, including remeshing operations. // In addition, it is assumed that mutable_polyhedron3d contains only triangle faces class POLYHEALER_PUBLIC mutable_polyhedron3d { public: typedef std::map<id_vertex,pos3d> vtx_map; typedef vtx_map::iterator vertex_iterator; typedef std::unordered_map<id_face, pface> pface_map; typedef pface_map::iterator pface_iterator; public: mutable_polyhedron3d(const std::shared_ptr<polyhedron3d> poly); virtual ~mutable_polyhedron3d(); // update the input polyhedron to match the current mutable polyhedron std::shared_ptr<polyhedron3d> update_input(); // clear all mutable polyhedron data, except input polyhedron void clear(); // === BASIC VERTEX/FACE TRAVERSAL // ------------------------------- // vertex traversal inline size_t vertex_size() const { return m_vert.size(); } inline const pos3d& vertex(id_vertex i) const { return m_vert.find(i)->second; } inline vertex_iterator vertex_begin() { return m_vert.begin(); } inline vertex_iterator vertex_end() { return m_vert.end(); } // face traversal inline pface_iterator face_begin() { return m_face.begin(); } inline pface_iterator face_end() { return m_face.end(); } // get face by face_id. Note that face id's are NOT contiguous inline const pface& face(id_face i) const { return m_face.find(i)->second; } // === ACCESS TO COMPUTED DATA STRUCTURES // -------------------------------------- // return vertex pair for edge inline const vertex_pair& edge_vertices(id_edge iedge) const { return m_edge_vert.find(iedge)->second; } // return faces connected to given edge inline const face_set& get_edge_faces(id_edge iedge) const { return m_edge_faces.find(iedge)->second; } // return access to all the edges and their connected faces inline const edge_face_map& get_edge_faces() const { return m_edge_faces; } // return access to all faces and their connected edges inline const face_edge_map& get_face_edges() const { return m_face_edges; } // return neighbour faces connected to given face face_set get_face_neighbour_faces(id_face iface) const; // get coedges of given face coedge_vector get_face_coedges(id_face iface); // for given face and edge, return vertex opposite to edge id_vertex opposite_vertex(id_face iface, id_edge iedge); // === MODIFY MUTABLE POLYHEDRON // ----------------------------- // add vertex to polyhedron id_vertex add_vertex(const pos3d& pos); // add face to polyhedron id_face add_face(id_vertex iv1, id_vertex iv2, id_vertex iv3); // remove face and edge from polyhedron void remove_face(id_face iface, id_edge iedge); // flip selected face void face_flip(id_face iface); // remove vertex // Note: it is assumed that the vertex being removed is unreferenced, no checking is done void remove_vertex(id_vertex iv); // ==== COMPUTE PROPERTIES // ----------------------- // compute edge length from 2 vertices in assumed edge order double edge_length(id_vertex iv1, id_vertex iv2) const; // compute edge length double edge_length(id_edge iedge) const; // compute normal from 3 vertices in assumed face order double face_area(id_vertex iv1, id_vertex iv2, id_vertex iv3); // compute face area double face_area(id_face iface); // compute face aspect ratio from 3 vertices double face_aspect_ratio(id_vertex iv1, id_vertex iv2, id_vertex iv3); // compute face aspect ratio double face_aspect_ratio(id_face iface); // compute normal from 3 vertices in assumed face order vec3d face_normal(id_vertex iv1, id_vertex iv2, id_vertex iv3); // compute face normal of existing face vec3d face_normal(id_face iface); public: // helper functions edge_count_map construct_edge_use_count(); edge_face_map construct_edge_faces(); edge_vertex_map construct_edge_vertices(); protected: // initialize all data structures belonging to // mutable_polyhedron3d, based on input polyhedron3d void construct(); private: std::shared_ptr<polyhedron3d> m_poly; // original polyhedron // Additional data structures vtx_map m_vert; // <id_vertex,pos3d> vertices as a map, can grow more easily. pface_map m_face; // <id_face, pface> faces as as a map, can add and remove faces more easily id_face m_face_counter; // ever growing face counter. Note: we never re-use an id when removing a face edge_face_map m_edge_faces; // <id_edge, face_set> edge faces face_edge_map m_face_edges; // <id_face, edge_set> face edges edge_vertex_map m_edge_vert; // <id_edge, vertex_pair> edge vertices }; #endif // MUTABLE_POLYHEDRON3D_H
import React, {useEffect, useState} from 'react'; import { View, Text, StyleSheet, ActivityIndicator, ScrollView, } from 'react-native'; import {Card, Avatar} from 'react-native-elements'; import {apiUrl, apiImage} from '../config'; import defaultAvatar from '../img/dosen.jpeg'; import ActionButton from './ActionButton'; import {useNavigation} from '@react-navigation/native'; import AsyncStorage from '@react-native-async-storage/async-storage'; const DetailDosen = ({route}) => { const {nidn_2020023} = route.params; const [dosen, setDosen] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); const navigation = useNavigation(); const goToPageFormUpload = () => { navigation.navigate('FormUpload', { nidn_2020023: nidn_2020023, foto_2020023: dosen.foto_thumb_2020023, }); }; useEffect(() => { const unsubscribe = navigation.addListener('focus', () => { const fetchData = async () => { token = await AsyncStorage.getItem('userToken'); try { const response = await fetch(`${apiUrl}dosen/${nidn_2020023}`, { headers: { Authorization: `Bearer ${token}`, }, }); const json = await response.json(); setDosen(json); } catch (error) { setError('Tidak dapat memuat data'); } finally { setLoading(false); } }; fetchData(); }); return unsubscribe; }, [navigation, nidn_2020023]); if (loading) { return <ActivityIndicator size="large" />; } if (error) { return <Text>{error}</Text>; } return ( <View style={styles.container}> {dosen && ( <ScrollView> <Card> <Avatar size="xlarge" rounded source={ dosen.foto_2020023 ? {uri: `${apiImage}${dosen.foto_thumb_2020023}`} : defaultAvatar } containerStyle={styles.avatarContainer} onPress={goToPageFormUpload} /> <Card.Title style={styles.title}>{dosen.nidn_2020023}</Card.Title> <Card.Divider /> <Text style={styles.detail}>Nama:</Text> <Text style={styles.detailData}>{dosen.nama_lengkap_2020023}</Text> <Text style={styles.detail}>Jenkel:</Text> <Text style={styles.detailData}> {dosen.jenkel_2020023 == 'L' ? 'Laki-Laki' : 'Perempuan'} </Text> <Text style={styles.detail}>Alamat:</Text> <Text style={styles.detailData}>{dosen.alamat_2020023}</Text> <Text style={styles.detail}>Tempat/Tgl.Lahir:</Text> <Text style={styles.detailData}> {dosen.tempat_lahir_2020023} / {dosen.tanggal_lahir_2020023} </Text> <Text style={styles.detail}>Telp/Hp:</Text> <Text style={styles.detailData}>{dosen.notelp_2020023}</Text> </Card> </ScrollView> )} <ActionButton nidn={dosen.nidn_2020023} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, padding: 5, }, avatarContainer: { alignSelf: 'center', marginBottom: 10, }, title: { fontSize: 20, fontWeight: 'bold', textAlign: 'center', }, detail: { fontSize: 14, marginBottom: 5, color: '#00FFFF', fontWeight: 'bold', marginTop: 10, }, detailData: { fontSize: 18, marginBottom: 5, borderBottomWidth: 1, borderBottomColor: '#00FFFF', color: 'black', fontWeight: 'bold', }, }); export default DetailDosen;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> /*:before 前面 :after 后面 content内容*/ /*伪元素选择器*/ div::before{ /*选中div标签的 前面,可以在div的前面加内容*/ content: "前面"; /*对点缀进行样式的设置*/ color: red; /*设置字体类型为斜体*/ font-style: italic; } div::after{ /*内容中的标签对不会被识别,会被当做一个普通的字符来显示*/ content: "<b>我是后面的点缀</b>"; font-size: 30px; } /* 通过before after 这些伪元素选择器 可以对元素进行点缀 也可以通过样式对这些点缀进行美化 before,after 也可以通过添加一些标签(元素)来实现相同的效果 所以叫做伪元素选择器 使用伪元素选择器的好处 1.点缀部分并不是内容,如果直接写会污染内容,导致百度搜索等 提取网页内容受到干扰 2.有时,HTML标签和内容是服务器端程序生成的,通过这种技术可以向标签 中注入新的内容 3.写法简单,可以使用样式控制 */ </style> </head> <body> <div>我是内容,是需要进行点缀,但是点缀并不是我的内容</div> </body> </html>
// // BleConnectTargetDetailView.swift // BleSample // // Created by 佐藤汰一 on 2023/06/24. // import SwiftUI import CoreBluetooth struct BleConnectTargetDetailView: View { @ObservedObject var viewModel: BlePeripheralDetailViewModel let presenter: BleConnectTargetDetailViewPresenter var body: some View { GeometryReader { proxy in ZStack { ScrollView { HStack { Spacer() VStack(alignment: .leading) { createIdSecionView() .font(.system(size: 30, weight: .bold)) Divider() createAdvertiseSection() Divider() createRssiSectionView() .font(.system(size: 30, weight: .regular)) Divider() createConnectStatusSectionView(parentSize: proxy) Spacer() } .frame(width: proxy.size.width - 50) Spacer() } } if viewModel.isShowIndicator { Color(.black) .opacity(0.4) .ignoresSafeArea() UtilityViews(viewType: .indicater) .foregroundColor(.gray) } } } .navigationTitle(viewModel.blePeripheralEntity.name) .navigationBarTitleDisplayMode(.automatic) .onAppear{ presenter.didApearView() } .onDisappear{ presenter.willDisapearView() } } private func createIdSecionView() -> some View { HStack{ Text("id:") .padding(.trailing, 30) Text(viewModel.blePeripheralEntity.id) Spacer() } } @ViewBuilder private func createAdvertiseSection() -> some View { Text("AdvertisementData") .font(.largeTitle) .padding(.init(top: 0, leading: 0, bottom: 0, trailing: 0)) ZStack { Color(.gray) .cornerRadius(20) VStack(alignment: .leading, spacing: 10) { createKeyValueDispView(key: .localName, value: viewModel.blePeripheralEntity.localName) createKeyValueDispView(key: .connectable, value: viewModel.blePeripheralEntity.isConnectable) ForEach(viewModel.blePeripheralEntity.serviceUUIDKey) { serviceUUID in createKeyValueDispView(key: .serviceUUIDKey, value: serviceUUID.key) } } .padding() } } private func createRssiSectionView() -> some View { HStack { Text("RSSI値") .padding(.trailing, 20) Text(String(viewModel.blePeripheralEntity.rssi)) Spacer() } } @ViewBuilder private func createKeyValueDispView(key: BleAdvertisementType, value: Any) -> some View { HStack { Text("\(key.getName()): \(selectAdvertisementValue(value: value, type: key))") Spacer() } } @ViewBuilder private func createConnectStatusSectionView(parentSize: GeometryProxy) -> some View { VStack(alignment: .leading) { Text("Connection Status") .font(.largeTitle) HStack { Spacer() Image(systemName: viewModel.isConnectedStatus == .connected ? "line.3.horizontal.decrease.circle" : "circle.slash") .resizable() .scaledToFill() .clipped() .frame(width: parentSize.size.width / 1.5, height: parentSize.size.width / 1.5) .foregroundColor(viewModel.isConnectedStatus == .connected ? .green : .red ) Spacer() } HStack { Text("Status") .padding(.trailing, 20) Text(viewModel.isConnectedStatus.name()) Spacer() } .font(.system(size: 30, weight: .regular)) HStack { Spacer() Button { if viewModel.isConnectedStatus == .connected { presenter.tappedDisconnectButton() }else{ presenter.tappedConnectButton() } } label: { Text(viewModel.isConnectedStatus == .connected ? "切断" : "接続") .frame(width: parentSize.size.width / 3, height: 50) .background(.teal) .foregroundColor(.white) .font(.title) .cornerRadius(20) .contentShape(RoundedRectangle(cornerRadius: 20)) } Spacer() } } } private func selectAdvertisementValue(value: Any, type: BleAdvertisementType) -> String{ var resutlString: String switch type { case .localName, .serviceUUIDKey: resutlString = value as? String ?? "No Value" case .connectable: resutlString = (value as? Bool ?? false).description } return resutlString } } struct BleConnectTargetDetailView_Previews: PreviewProvider { static var previews: some View { BleConnectTargetDetailViewRouter.assembleModule(viewModel: BlePeripheralDetailViewModel(model: BlePeripheralDetailEntity(id: "test", name: "testName", isConnectable: true, localName: "testLocalName", serviceUUIDKey: [ServiceUUIDKeys(id: UUID(), key: UUID().uuidString)], rssi: -30))) } }
import fs from "fs"; import { PDFDocument, PDFHexString, PDFName, PDFNumber, PDFString } from "pdf-lib"; // Local copy of Node SignPDF because https://github.com/vbuch/node-signpdf/pull/187 was not published in NPM yet. Can be switched to npm package. const signer = require("./node-signpdf/dist/signpdf"); export const addDigitalSignature = async (documentAsBase64: string): Promise<string> => { // Custom code to add Byterange to PDF const PDFArrayCustom = require("./PDFArrayCustom"); const pdfBuffer = Buffer.from(documentAsBase64, "base64"); const p12Buffer = Buffer.from( fs .readFileSync(process.env.CERT_FILE_PATH || "resources/certificate.p12") .toString(process.env.CERT_FILE_ENCODING ? undefined : "binary"), (process.env.CERT_FILE_ENCODING as BufferEncoding) || "binary" ); const SIGNATURE_LENGTH = p12Buffer.length * 2; const pdfDoc = await PDFDocument.load(pdfBuffer); const pages = pdfDoc.getPages(); const ByteRange = PDFArrayCustom.withContext(pdfDoc.context); ByteRange.push(PDFNumber.of(0)); ByteRange.push(PDFName.of(signer.DEFAULT_BYTE_RANGE_PLACEHOLDER)); ByteRange.push(PDFName.of(signer.DEFAULT_BYTE_RANGE_PLACEHOLDER)); ByteRange.push(PDFName.of(signer.DEFAULT_BYTE_RANGE_PLACEHOLDER)); const signatureDict = pdfDoc.context.obj({ Type: "Sig", Filter: "Adobe.PPKLite", SubFilter: "adbe.pkcs7.detached", ByteRange, Contents: PDFHexString.of("A".repeat(SIGNATURE_LENGTH)), Reason: PDFString.of("Signed by Documenso"), M: PDFString.fromDate(new Date()), }); const signatureDictRef = pdfDoc.context.register(signatureDict); const widgetDict = pdfDoc.context.obj({ Type: "Annot", Subtype: "Widget", FT: "Sig", Rect: [0, 0, 0, 0], V: signatureDictRef, T: PDFString.of("Signature1"), F: 4, P: pages[0].ref, }); const widgetDictRef = pdfDoc.context.register(widgetDict); // Add signature widget to the first page pages[0].node.set(PDFName.of("Annots"), pdfDoc.context.obj([widgetDictRef])); // Create an AcroForm object containing the signature widget pdfDoc.catalog.set( PDFName.of("AcroForm"), pdfDoc.context.obj({ SigFlags: 3, Fields: [widgetDictRef], }) ); const modifiedPdfBytes = await pdfDoc.save({ useObjectStreams: false }); const modifiedPdfBuffer = Buffer.from(modifiedPdfBytes); const signObj = new signer.SignPdf(); const signedPdfBuffer: Buffer = signObj.sign(modifiedPdfBuffer, p12Buffer, { passphrase: process.env.CERT_PASSPHRASE || "", }); return signedPdfBuffer.toString("base64"); };
import 'dart:io'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:teclix/data/models/customer_search.dart'; import 'package:teclix/logic/bloc/customer_late_pay/customer_late_pay_bloc.dart'; import 'package:teclix/logic/bloc/customer_late_pay/customer_late_pay_event.dart'; import 'package:teclix/logic/bloc/customer_late_pay/customer_late_pay_state.dart'; import 'package:teclix/logic/bloc/search_customer/search_customer_bloc.dart'; import 'package:teclix/logic/bloc/search_customer/search_customer_event.dart'; import 'package:teclix/logic/bloc/search_customer/search_customer_state.dart'; import 'package:teclix/presentation/screens/customer/customer_late_payment/customer_details_page.dart'; class MockCustomerLatePayBloc extends MockBloc<CustomerLatePayEvent, CustomerLatePayState> implements CustomerLatePayBloc {} class CustomerLatePayEventFake extends Fake implements CustomerLatePayEvent {} class CustomerLatePayStateFake extends Fake implements CustomerLatePayState {} class MockSearchCustomerBloc extends MockBloc<SearchCustomerEvent, SearchCustomerState> implements SearchCustomerBloc {} class SearchCustomerEventFake extends Fake implements SearchCustomerEvent {} class SearchCustomerStateFake extends Fake implements SearchCustomerState {} final customerSearch = CustomerSearch( id: 1, loyaltyPoints: '0.0', city: 'c', street: 's', district: 'd', ownerLastName: 'ol', ownerFirstName: 'of', shopName: 'shop', email: 'test@gmail.com', longitude: '1.0', latitude: '1.1', contactNo: '123', outstanding: '250.0', profilePicture: 'https://upload.wikimedia.org/wikipedia/commons/b/b6/Image_created_with_a_mobile_phone.png'); void main() { group('Late pay customer details page is rendered properly.', () { MockCustomerLatePayBloc mockCustomerLatePayBloc; MockSearchCustomerBloc mockSearchCustomerBloc; setUpAll(() { registerFallbackValue<CustomerLatePayEvent>(CustomerLatePayEventFake()); registerFallbackValue<CustomerLatePayState>(CustomerLatePayStateFake()); registerFallbackValue<SearchCustomerEvent>(SearchCustomerEventFake()); registerFallbackValue<SearchCustomerState>(SearchCustomerStateFake()); mockCustomerLatePayBloc = MockCustomerLatePayBloc(); mockSearchCustomerBloc = MockSearchCustomerBloc(); HttpOverrides.global = null; }); testWidgets('should render the main ui properly', (WidgetTester tester) async { when(() => mockCustomerLatePayBloc.state).thenReturn( CustomerLatePayState( error: '', amount: '250.0', checkBoxValue: true, loading: false, paymentFailed: false, customerId: null, paymentDone: false, ), ); when(() => mockSearchCustomerBloc.state).thenReturn( SearchCustomerState( error: "", loading: false, selectedCus: customerSearch, searchResult: []), ); final page = CustomerDetails(); final width = 488.0; final height = 750; tester.binding.window.devicePixelRatioTestValue = (2.625); tester.binding.window.textScaleFactorTestValue = (0.8); final dpi = tester.binding.window.devicePixelRatio; tester.binding.window.physicalSizeTestValue = Size(width * dpi, height * dpi); await tester.pumpWidget(BlocProvider<SearchCustomerBloc>( create: (context) => mockSearchCustomerBloc, child: BlocProvider<CustomerLatePayBloc>( create: (context) => mockCustomerLatePayBloc, child: MediaQuery( data: MediaQueryData(), child: MaterialApp( home: Scaffold(body: page), ), ), ), )); await tester.pumpAndSettle(); expect(find.text('Customer Details'), findsOneWidget); expect(find.text('Back'), findsOneWidget); }); testWidgets('should render the customer information in the ui properly', (WidgetTester tester) async { when(() => mockCustomerLatePayBloc.state).thenReturn( CustomerLatePayState( error: '', amount: '250.0', checkBoxValue: true, loading: false, paymentFailed: false, customerId: null, paymentDone: false, ), ); when(() => mockSearchCustomerBloc.state).thenReturn( SearchCustomerState( error: "", loading: false, selectedCus: customerSearch, searchResult: []), ); final page = CustomerDetails(); final width = 488.0; final height = 750; tester.binding.window.devicePixelRatioTestValue = (2.625); tester.binding.window.textScaleFactorTestValue = (0.8); final dpi = tester.binding.window.devicePixelRatio; tester.binding.window.physicalSizeTestValue = Size(width * dpi, height * dpi); await tester.pumpWidget(BlocProvider<SearchCustomerBloc>( create: (context) => mockSearchCustomerBloc, child: BlocProvider<CustomerLatePayBloc>( create: (context) => mockCustomerLatePayBloc, child: MediaQuery( data: MediaQueryData(), child: MaterialApp( home: Scaffold(body: page), ), ), ), )); await tester.pumpAndSettle(); expect(find.text('shop'), findsOneWidget); expect(find.text('of ol'), findsOneWidget); }); testWidgets('should render the current outstanding properly', (WidgetTester tester) async { when(() => mockCustomerLatePayBloc.state).thenReturn( CustomerLatePayState( error: '', amount: '250.0', checkBoxValue: true, loading: false, paymentFailed: false, customerId: null, paymentDone: false, ), ); when(() => mockSearchCustomerBloc.state).thenReturn( SearchCustomerState( error: "", loading: false, selectedCus: customerSearch, searchResult: []), ); final page = CustomerDetails(); final width = 488.0; final height = 750; tester.binding.window.devicePixelRatioTestValue = (2.625); tester.binding.window.textScaleFactorTestValue = (0.8); final dpi = tester.binding.window.devicePixelRatio; tester.binding.window.physicalSizeTestValue = Size(width * dpi, height * dpi); await tester.pumpWidget(BlocProvider<SearchCustomerBloc>( create: (context) => mockSearchCustomerBloc, child: BlocProvider<CustomerLatePayBloc>( create: (context) => mockCustomerLatePayBloc, child: MediaQuery( data: MediaQueryData(), child: MaterialApp( home: Scaffold(body: page), ), ), ), )); await tester.pumpAndSettle(); expect(find.text('Current Outstanding'), findsOneWidget); expect(find.text('Rs 250.00'), findsOneWidget); }); }); }
#include "BLEManager.h" #include <Arduino.h> BLEService sensorService("180C"); // Custom service UUID BLECharacteristic sensorCharacteristic("2A56", BLERead | BLEWrite, 20); // Custom characteristic UUID, max length 20 BLEManager::BLEManager() { // Initialization code if needed } void BLEManager::initBLE() { Serial.println("Initializing BLE..."); if (!BLE.begin()) { Serial.println("Starting BLE failed!"); while (1); } BLE.setLocalName("Nano33BLE"); BLE.setAdvertisedService(sensorService); sensorService.addCharacteristic(sensorCharacteristic); BLE.addService(sensorService); BLE.advertise(); Serial.println("BLE initialized."); } void BLEManager::sendData(const String& data) { BLEDevice central = BLE.central(); // If a central is connected. if (central) { Serial.print("Connected to central: "); Serial.println(central.address()); // If the central is still connected to the peripheral. while (central.connected()) { sensorCharacteristic.writeValue(data.c_str()); Serial.print("Sent data: "); Serial.println(data); delay(1000); } Serial.print("Disconnected from central: "); Serial.println(central.address()); } } void BLEManager::sendData(const SensorData& data) { sendData(data.format()); }
--- title: In 2024, 4 Ways to Sync Contacts from Apple iPhone 7 to iPad Easily | Dr.fone date: 2024-05-19T02:47:38.713Z updated: 2024-05-20T02:47:38.713Z tags: - iphone transfer categories: - ios description: This article describes 4 Ways to Sync Contacts from Apple iPhone 7 to iPad Easily excerpt: This article describes 4 Ways to Sync Contacts from Apple iPhone 7 to iPad Easily keywords: transfer data from iphone,transfer data from ios to pc,transfer data from ios to samsung,transfer data from ios,transfer data from iphone to pc,export data from iphone,transfer data from iphone to samsung thumbnail: https://www.lifewire.com/thmb/Dp9islCb9GD3RtQaIU23WoKYMSs=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/001_best-lgbt-movies-on-netflix-right-now-5069913-92c9bcd3792548908be32c420bc4fa27.jpg --- ## 4 Ways to Sync Contacts from Apple iPhone 7 to iPad Easily One of the key elements within the Apple ecosystem is its capacity to synchronize data across various devices. In this age of inter connectivity, the importance of harmonizing contacts across multiple devices has emerged as vital. With the prevalence of iPhones and iPads, the demand for an efficient method to sync contacts between these two devices has surged. For better contact management, the contacts syncing between iPhone and iPad is critical. This article discusses **how do you sync contacts from Apple iPhone 7 to iPad**. It will go through 4 effective methods to sync contacts from an iPhone to an iPad. ## Part 1: Sync Contacts from Apple iPhone 7 to iPad Using Wondershare Dr.Fone [Wondershare Dr.Fone](https://drfone.wondershare.com/iphone-backup-and-restore.html) can be used to [transfer contacts from Apple iPhone 7 to iPad/iPhone](https://drfone.wondershare.com/iphone-transfer/transfer-contacts-from-iphone-to-iphone.html). You can back up iPhone contacts using Dr.Fone and then restore the contacts to the iPad without losing any data. ### [Wondershare Dr.Fone](https://drfone.wondershare.com/iphone-backup-and-restore.html) Back up & Restore iOS Data Turns Flexible. - One-click to back up the whole iOS device to your computer. - Allow to preview and restore any item from the backup to a device. - Export what you want from the backup to your computer. - No data loss on devices during the restoration. - Selectively restore any data you want. - Supported the newest iPhone and Android phones. **3981454** people have downloaded it Here's how to sync iPhone contacts to iPad: - **Step 1: Connect the iPhone to the computer** Launch [Wondershare Dr.Fone](https://tools.techidaily.com/wondershare/drfone/phone-switch/) on the computer and then select "My Backup" from among various options. Now, using a cable, connect the iPhone to the computer and then allow Dr.Fone to automatically detect your connected iPhone device. ![dr.fone for ios](https://images.wondershare.com/drfone/guide/drfone-home.png) - **Step 2: Click "Back Up Now" to Back up** After the iPhone is connected successfully, Dr.Fone will automatically detect the file types in it. Click on "Back Up Now" to back up your iPhone. ![select contacts to backup](https://images.wondershare.com/drfone/guide/ios-backup-and-restore-1.png) The backup process will start and take a few minutes to complete depending on the volume of data to be backed up. Dr.Fone will display all the data that are supported after the backup is completed. ![backup iphone contacts](https://images.wondershare.com/drfone/guide/ios-backup-and-restore-2.png) Now that you have backed up all the contacts on the iPhone and then restoring them to the iPad is the way to it. - **Step 3: Select Restore to Device** Once the backup is completed, connect your iPad using a USB cable. Select the backup file and hit "Restore to Device". It's as simple as it sounds, and anyone can back up your contacts and sync them to your iPad. ![backup iphone contacts](https://images.wondershare.com/drfone/guide/ios-backup-and-restore-6.png) In addition to manual backup, you can also back up contacts on iPhone automatically. **How to back up contacts automatically and wirelessly?** **Step 1:** Click "Backup Preference" to set up the backup frequency and backup period. ![auto backup](https://images.wondershare.com/drfone/guide/ios-backup-and-restore-4.png) **Step 2:** Connect your iPhone and PC with the same wifi, the contacts on iPhone will be backed up automatically. You don't need to use a USB cable to connect the iPhone to the PC in this step. Next time, if you would like to back up contacts again, it will only be for newly added data or modified files, which helps you save storage space and backup time. **Step 3:** Restore the backup file to iPad/iPhone. You can preview the backup data and select the data you want to restore. ![backup iphone contacts](https://images.wondershare.com/drfone/guide/backup-history.png) ### Bonus Tip: Sync Contacts from Apple iPhone 7 to iPad with 1 Click Except the Phone Backup feature can help you sync contacts from Apple iPhone 7 to iPad easily, there is another tool that can also help you. If you have downloaded the Wondershare Dr.Fone, you may see this tool on the homepage, too. Yes! It is [Dr.Fone - Phone Transfer](https://tools.techidaily.com/wondershare/drfone/phone-switch/). **Features of Dr.Fone - Phone Transfer tool:** - Easily [share contacts](https://drfone.wondershare.com/iphone-transfer/share-contacts-on-iphone.html) and other types of data on iPhone to iPad/another iPhone. - Just 1 click to transfer contacts to the iPad. - Sync the data from Apple iPhone 7 to iPad within less than 3 minutes, the time of a cup of coffee! ![phone to phone transfer](https://images.wondershare.com/drfone/guide/transfer-ios-to-android-1.png) ## Part 2: Sync Contacts from Apple iPhone 7 to iPad Using iCloud If you're heavily invested in the Apple environment, choosing iCloud is the optimal route. It serves as a convenient tool for synchronizing contacts between your iPhone and iPad. Leveraging iCloud's powerful synchronization features, you can effortlessly maintain updated contact lists across all your Apple devices. Follow the simple steps outlined below to **sync contacts from Apple iPhone 7 to iPad**: **Step 1:** After ensuring that the same Apple ID is logged in on both iPhone and iPad, first move to iPhone's Settings. Here, tap "Apple ID," and on the following screen, choose "iCloud." In the "iCloud" tab, move to the "Apps Using iCloud" section and ensure the "Contacts" app is toggled on. Afterward, transfer to your iPad and access the Apple iPhone 7 device's Settings. ![turn on sync contacts option](https://images.wondershare.com/drfone/article/2023/11/sync-contacts-from-iphone-to-ipad-1.jpg) **Step 2:** Within the Settings app, tap "Apple ID” and follow it by pressing "iCloud" on the following screen. Here, move to the "Apps Using iCloud" section and toggle on the "Contacts" app. Wait a few moments, and your contacts will be synced across devices. ![enable contacts icloud option](https://images.wondershare.com/drfone/article/2023/11/sync-contacts-from-iphone-to-ipad-2.jpg) ## Part 3: Sync Contacts from Apple iPhone 7 to iPad Using AirDrop AirDrop is a convenient feature native to Apple devices. It presents a convenient wireless solution for seamlessly transferring contacts between an iPhone and an iPad. With its user-friendly configuration, AirDrop enables the easy sharing of diverse data, including contacts, among nearby Apple devices. Follow the instructions below for how do I sync contacts from Apple iPhone 7 to iPad using AirDrop: **Step 1:** Begin by ensuring that Bluetooth and Wi-Fi are enabled on both iPhone and iPad. Afterward, access Control Center by swiping down from the top right corner of the Apple iPhone 7 device. ![enable wifi and bluetooth option](https://images.wondershare.com/drfone/article/2023/11/sync-contacts-from-iphone-to-ipad-3.jpg) **Step 2:** Here, enable AirDrop and set its visibility to "Everyone." Now, open the 'Contacts' app on your iPhone, select the contacts you want to transfer and tap the "Share" button. ![choose the everyone option](https://images.wondershare.com/drfone/article/2023/11/sync-contacts-from-iphone-to-ipad-4.jpg) **Step 3:** Tap on "AirDrop" from the list of sharing options provided. After selecting "AirDrop," choose your iPad as the receiving device. A prompt will appear on your iPad to accept the incoming contacts. Tap "Accept" to initiate the transfer. ![tap on airdrop sharing option](https://images.wondershare.com/drfone/article/2023/11/sync-contacts-from-iphone-to-ipad-5.jpg) ## Part 4: Sync Contacts from Apple iPhone 7 to iPad Using iTunes/Finder iTunes/Finder serves as a robust option for users who prefer a traditional and reliable method. It is a tested and trusted way of syncing data between their Apple devices. This software offers comprehensive backup and sync functionalities. That's why iTunes/Finder provides a secure and efficient way to transfer contacts from an iPhone to an iPad. Follow the steps below to sync your contacts using iTunes or Finder: **Step 1.** Begin by launching the most recent version of iTunes/Finder on your computer. Connect your iPhone and navigate to the "Summary" tab by clicking the “iPhone” icon. Here, enable the "Sync with this iPhone via Wi-Fi" feature. ![enable sync this iphone feature](https://images.wondershare.com/drfone/article/2023/11/sync-contacts-from-iphone-to-ipad-6.jpg) **Step 2.** Subsequently, disconnect the iPhone and link your iPad to the computer. In iTunes/Finder, select the “Device” icon and switch to the "Info" tab. Here, ensure that the "Sync Contacts" box is checked, and then choose either "All Contacts" or "Selected Groups." ![enable sync contacts feature](https://images.wondershare.com/drfone/article/2023/11/sync-contacts-from-iphone-to-ipad-7.jpg) **Step 3.** Once you have made your selection, click on "Apply" to initiate the contacts synchronization process. Upon completion, you can disconnect the iPad and access the synced contacts from your iPhone. ![press the apply button](https://images.wondershare.com/drfone/article/2023/11/sync-contacts-from-iphone-to-ipad-8.jpg) So, these are four ways in which you can transfer contacts from Apple iPhone 7 to iPad. Since these methods are the outcome of thorough research, all the methods are absolutely safe, and there is absolutely no data loss in the process. However, we would recommend [Wondershare Dr.Fone](https://drfone.wondershare.com/iphone-backup-and-restore.html), considering its robust and efficient working design. It is one of the best and most popular tools to transfer data from Apple iPhone 7 to iPad and offers an amazing overall experience with a simple interface and fast process. What's imperative is to ensure that you follow all the steps properly and that's all, there you have it; all the contacts on the iPad. ## How to Transfer from Apple iPhone 7 to Samsung Galaxy S20? If you are willing to switch your phone from an iOS device to an android, the primary issue which restricts you to do so is your data loss and the data transferring from one device to another. In this article, we'll be learning How to Transfer Data from Apple iPhone 7 to Samsung Galaxy S20, with some easy and best techniques. The discussed techniques will ensure your data from not getting lost. ![transfer data from iphone to samsung s20](https://images.wondershare.com/drfone/article/2020/02/transfer-data-from-iphone-to-samsung-s20.jpg) ## Part 1: Transfer from Apple iPhone 7 to Samsung Galaxy S20 Directly (Easy and Fast) Dr.Fone - Phone Transfer program is a phone transfer tool, you can transfer all types of data like photos, music, contacts, messages, calendar, etc. from one phone to another easily. **Let's see how we can to transfer data from Apple iPhone 7 to Galaxy S20** Dr.Fone - Phone Transfer allows you to transfer data between various phones with one click, including Android, iOS, Symbian, and WinPhone. Use this program to transfer and convey data between any of them. **Down below there's a detailed step by step process explaining how you can transfer all your data from one phone to another using computer** **Step 1. Connect Your Apple iPhone 7 to the computer** After opening Dr.Fone on your computer, select "Phone Transfer" among the modules. ![drfone home](https://images.wondershare.com/drfone/guide/drfone-home.png) Make sure you have connected both of your devices with it. Here let's take an iOS and a Samsung Galaxy S20(any Android device) as an example. ![phone switch 01](https://images.wondershare.com/drfone/guide/transfer-ios-to-android-1.png) The data from the source device will be conveyed/transferred to the destination device. To exchange their position, you can use the "Flip" button too. **Step 2. Select the file and start to transfer** Choose the file types you desire to move. To begin the process, click on-Start Transfer. Until the process is completed, please don't disconnect the Apple iPhone 7 devices for its maximum efficiency. ![phone switch 02](https://images.wondershare.com/drfone/guide/transfer-ios-to-android-4.png) Before commencing the data transfer process between both the phones, if you want to erase the data of the destination device-check the "Clear Data before Copy" box. All the files you selected will be transferred to the targeted phone successfully In a couple of minutes. ![phone switch 03](https://images.wondershare.com/drfone/guide/transfer-ios-to-android-5.png) ## Part 2: Transfer from iCloud Backup to Samsung Galaxy S20 (Wireless and Safe) ### 1\. Dr.Fone - Switch App If you don't have a computer device and want to transfer data from an iOS device to an Android device, here is an in-depth step by step process guiding you how to do so. **How to sync data from the iCloud account to Android** **Step 1.** Touch "Import from iCloud", after installing the Android version of Dr.Fone - Switch. ![transfer data from iphone to samsung s20 by drfone app 1](https://images.wondershare.com/drfone/article/2020/02/transfer-data-from-iphone-to-samsung-s20-by-drfone-app-1.jpg) **Step 2.** With your Apple ID and passcode, log in to the iCloud account. If you have enabled the two-factor authentication, enter the verification code. ![transfer data from iphone to samsung s20 by drfone app 2](https://images.wondershare.com/drfone/article/2020/02/transfer-data-from-iphone-to-samsung-s20-by-drfone-app-2.jpg) **Step 3.** On your iCloud account now in a while later, all types of data can be detected. Touch "Start Importing" after Selecting your desired data or all of these data. ![transfer data from iphone to samsung s20 by drfone app 3](https://images.wondershare.com/drfone/article/2020/02/transfer-data-from-iphone-to-samsung-s20-by-drfone-app-3.jpg) **Step 4.** Sit back until and unless data importing is fully completed. Then you can exit this app and check the data synced from iCloud on your Apple iPhone 7 or tablet. **Prons:** - Transfer data from Apple iPhone 7 to Android without a PC. - Support mainstream Android phones (including Xiaomi, Huawei, Samsung, etc.) **Cons:** - For direct data transfer, connect iPhone to Android by using an iOS-to-Android adapter. ### 2\. Samsung Smart Switch App **Export data from iCloud to Samsung S20 with Smart Switch** If you make use of the Samsung Smart Switch app, syncing iTunes with Samsung is just an easy-peasy task. It has become simpler to sync iCloud to Samsung S20 as it stretches compatibility with iCloud. Here is how- **How to transfer data from iCloud to Samsung S20 with Smart Switch** - Download Smart Switch from Google Play on your Samsung Device. Open the app, then click on 'WIRELESS,' after that tap on 'RECEIVE' and select the 'iOS' option. - Sign in with your Apple ID and password. Now, select the desired content you want to transfer from iCloud to Samsung Galaxy S20 and press 'IMPORT.' ![transfer data from iphone to samsung s20 by samsung app 1](https://images.wondershare.com/drfone/article/2020/02/transfer-data-from-iphone-to-samsung-s20-by-samsung-app-1.jpg) - If you are using a USB cable, do keep iOS cable, Mirco USB, and USB Adapter handy. Then, load Smart Switch on your Samsung S20 model and click on 'USB CABLE.' - Further, connect the two devices by iPhone's USB cable and the USB-OTG adapter with Samsung S20. - Click on 'Trust' followed by pressing 'Next' to proceed further. Choose the file and press on 'TRANSFER' to convey/Transfer from iCloud to Samsung S20. ![transfer data from iphone to samsung s20 by samsung app 2](https://images.wondershare.com/drfone/article/2020/02/transfer-data-from-iphone-to-samsung-s20-by-samsung-app-2.jpg) **Prons:** - Wireless transfer. **Cons:** - Only for Samsung phones. _If you prefer to run a desktop software to transfer data, use Dr.Fone - Phone Transfer. It's a hassle-free solution. Connect both phones to computer and start to transfer data in one-click._ [Free Download](https://tools.techidaily.com/wondershare/drfone/drfone-toolkit/) [Free Download](https://tools.techidaily.com/wondershare/drfone/drfone-toolkit/) ## Part 3: Transfer from iTunes Backup to Samsung Galaxy S20 without iTunes **Step 1. Select the backup file** Launch Dr.Fone and select Phone Backup. Connect your Samsung S20 to the computer. Click on Restore. It will give the option View backup history if you have used this function to backup your iOS device before. Click on View backup history option to view the backup file index. ![ios device backup 01](https://images.wondershare.com/drfone/guide/ios-backup-and-restore-1.png) After that, Dr.Fone will display the backup history. Just pick the backup file you want and click on the Next on the bottom of the program or view button next to the backup file. ![ios device backup 04](https://images.wondershare.com/drfone/guide/backup-history.png) **Step 2. View and Restore the backup file** The program will take a few seconds to examine the backup file and display all data in categories in the backup file after you click on View. After you find the files you require, you can pick a few files or choose them all to move to the next step. ![ios device backup 05](https://images.wondershare.com/drfone/guide/ios-backup-and-restore-6.png) Currently, Dr.Fone supports to restore the music, Safari bookmarks, Call History, Calendar, Voice memo, Notes, Contacts, Messages, Photos, videos to the Apple iPhone 7 device. So you can restore these data to your Samsung device or transfer them all to your computer. If you want to restore the files to your device, select the files and click on Restore to Device. In a couple of seconds, you will get these files on your Android gadget. If you want to export the chosen files to your computer, click on Export to PC. Then select the save path to transfer your data. ![ios device backup 07](https://images.wondershare.com/drfone/guide/ios-backup-and-restore-11.png) [Free Download](https://tools.techidaily.com/wondershare/drfone/drfone-toolkit/) [Free Download](https://tools.techidaily.com/wondershare/drfone/drfone-toolkit/) ## Final Words The techniques which are discussed above are meant to solve your problem and let you know How to Transfer from Apple iPhone 7 to Samsung Galaxy S20. These techniques will guide you through transferring your file quickly and swiftly. The method discussed over here is related to both the users- who are willing to transfer their data using a computer and without using it. So, finally, we hope that this article would help you to solve your issue related to data transfer. ## How to Transfer Everything from Apple iPhone 7 to iPhone 8/X/11 [![Bhavya Kaushik](https://drfone.wondershare.com/images/Bhavya_Kaushik.png)](https://drfone.wondershare.com/author/bhavya-kaushik/) This article guide focuses on the techniques and tools you need to **transfer everything from Apple iPhone 7 to iPhone 8/X/11**. As we know that most of the iPhone users will be switching their devices because of the new and improved iPhone 8/X/11 device which has to offer more features to the Apple users however, there is always a need for proper tool that can transfer data from the old iPhone device to new iPhone 8/X/11. We have different kinds of files in our iPhone and almost all of the files are important to us. We would never want to stay out of touch with our important ones, and contacts help us to do that. All of that collection of your favorite music is not east to gather and you would certainly not like it if all of it is gone from your handset, So Contacts, Photos, SMS, Music all of these files are very important to us one can only understand the importance when they have no more access to these contents. Similarly, Photos are also important because they are the proof of our precious memories, and we don’t want to lose them. SMS messages are the records of every conversation we had with our contacts and sometimes we need record to continue the conversation regarding the subject. To transfer all of the content from one phone to another, we need a transfer tool because different handsets have different operating systems. And it is not easy to perform transfer functions between two devices. Most of the people hesitate to switch to a newer device because of the hassle they think they might have to go through to transfer data to new device, including the new iPhone 8/X/11. ## How to transfer everything from Apple iPhone 7 to iPhone 8/X/11 If you are looking to **transfer everything from your old iPhone to your new iPhone 8/X/11** then Dr.Fone - **Phone Transfer** is a must get tool. With Dr.Fone application, you can easily transfer your important music, pictures, videos, SMS and much more transfer data to your new iPhone 8/X/11. There are always complications for iPhone users when they want to switch to new and latest device, but it is very easy thanks to Wondershare’s Mobile Trans. ### [Dr.Fone - Phone Transfer](https://tools.techidaily.com/wondershare/drfone/phone-switch/ "iPhone to iPhone Transfer") Transfer Everything from Apple iPhone 7 to iPhone 8/X/11 in 1 Click!. - Easily transfer photos, videos, calendar, contacts, messages and music from old iPhone to new iPhone 8/X/11. - Enable to transfer from HTC, Samsung, Nokia, Motorola and more to iPhone 11/X/8/7S/7/6S/6 (Plus)/5s/5c/5/4S/4/3GS. - Works perfectly with Apple, Samsung, HTC, LG, Sony, Google, HUAWEI, Motorola, ZTE, Nokia and more smartphones and tablets. - Fully compatible with major providers like AT&T, Verizon, Sprint and T-Mobile. - Supports iPhone, iPad, iPod touch and the latest iOS version. - Fully compatible with the latest Windows or Mac version. **3981454** people have downloaded it This section of the article focuses on the steps through which you can transfer your data from your Apple iPhone 7 to your new iPhone 8/X/11. Step 1: The first and foremost step includes connecting your devices to your PC. When you are done simply launch the Dr.Fone software click **Phone Transfer** in the main menu. ![transfer everything from Apple iPhone 7 to iPhone 8](https://images.wondershare.com/drfone/guide/drfone-home.png "transfer everything from iPhone 5s to iPhone 8") Step 2: Right after your devices have been connected simply note the source and destination phone are connected at this moment, you will get a proper tab with source and destination phone images and their connection status. Step 3: When you are done with selecting the source which in this case would be iPhone 7/7Plus and destination device which in this case would be iPhone 8/X/11 click **Start Transfer**, you need to specify the data you want to transfer in this case you would select all contents since you want to transfer everything. Step 4: Simply click start transfer and the transfer process will begin make sure that both of the Apple iPhone 7 devices remain connected throughout the transfer process. ![transfer from Apple iPhone 7 to iPhone 8](https://images.wondershare.com/drfone/drfone/phone-switch-ios-to-ios-01.jpg "transfer from iPhone 5s to iPhone 8") ## Part 2: How to transfer everything from Apple iPhone 7 to iPhone 8/X/11 with iCloud Initially signing up for ICloud gets you 5GB of storage, you can use this storage for IOS device backup, iCloud photo library, app data and documents stored in the ICloud. If you feel 5gb storage is not enough you, you can always upgrade your storage but then you will have to pay. iCloud as a backup is a great if anything happens to your phone you can get access to your data anywhere with the internet besides this you can also use this data to switch your new iPhone 8/X/11 device. Step 1. From your IPhone 7 device connect to a Wi-Fi network. Go to IPhone 7 **settings** and tap on your name. Scroll down and select the **iCloud** option. Step 2. After you have clicked the iCloud option in the backup section enable **iCloud backup** option. And hit “**Backup Now**”. Step 3. You must be connected to the Wi-Fi until the backup process is completed. In ICloud tab select storage to see the details of your backup. ![transfer everything from Apple iPhone 7 to iPhone 8](https://images.wondershare.com/drfone/article/2017/09/transfer-from-iphone-7-to-iphone-8-via-icloud.jpg "transfer everything from Apple iPhone 7 to iPhone 8") Step 4. Now that your data has been backed up using your iCloud id you can always add this id to your new iPhone 8/X/11 device. Right after you add your iCloud id to your new iPhone 8/X/11, and **Restore from iCloud Backup**, all of the backed up data from Apple iPhone 7 will be transferred to your new iPhone 8/X/11 device. ## Part 3: How to transfer everything from Apple iPhone 7 to iPhone 8/X/11 with iTunes? You can create a local backup for your Apple iPhone 7 device on your PC through iTunes, and then restore to your new iPhone 8/X/11. So that you sync all data from Apple iPhone 7 to iPhone 8/X/11 with iTunes. If you don’t have iTunes you can download for free from apple’s official website. Step 1. After you have successfully installed iTunes on your Computer connect the Apple iPhone 7 device to your system and launch the iTunes Application. Step 2. iTunes will detect your device, simply click summary of your phone, in the Backups tab you must click “**Backup Up Now**” under the Manually Backup and Restore. Step 3. The iTunes will back up your iPhone. After the process is complete you can disconnect your Apple iPhone 7. Step 4. After you have backed up the data from your old Apple iPhone 7 device, simply connect your new iPhone 8/X/11 and restore the data to your new iPhone 8/X/11 device through iTunes. ![transfer everything from Apple iPhone 7 to iPhone 8 with iTunes](https://images.wondershare.com/drfone/article/2017/09/transfer-from-iphone-7-to-iphone-8-via-itunes.jpg "transfer everything from Apple iPhone 7 to iPhone 8 with iTunes") With the advancements in the mobile technology we are presented with the new and improved features every year, there is always a point where we need to change our device because we do need those new features. So in one of the cases iPhone users would want to change their device because of the extensive features iPhone 8/X/11 has to offer. So in this case we would want to **transfer the data from our Apple iPhone 7 to iPhone 8/X/11**. Apple users and techie’s are always up for new handset and they love to get their hands on the newer Apple’s device. This is where there is a need for an effective tool to transfer the data from the old Apple iPhone 7 to iPhone 8/X/11. After going through this article guide we can conclude that iPhone users can transfer their data to their latest iPhone 8/X/11 with the help of iTunes, iCloud and Dr.Fone - Phone Transfer (iOS & Android). However, Dr.Fone is very effective for data transfer operations. Plus, the **iPhone to iPhone Transfer** tool is very easy to use because of its user friendly interface design. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://iphone-transfer.techidaily.com/in-2024-how-to-copy-contacts-from-apple-iphone-xr-to-sim-drfone-by-drfone-transfer-from-ios/"><u>In 2024, How to Copy Contacts from Apple iPhone XR to SIM? | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-transfer-your-apple-iphone-6s-apps-to-new-iphone-drfone-by-drfone-transfer-from-ios/"><u>In 2024, Transfer your Apple iPhone 6s Apps to New iPhone | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-4-ways-to-transfer-messages-from-apple-iphone-13-mini-to-iphone-including-iphone-15-drfone-by-drfone-transfer-from-ios/"><u>In 2024, 4 Ways to Transfer Messages from Apple iPhone 13 mini to iPhone Including iPhone 15 | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/switch-cards-between-apple-iphone-12-pro-and-other-iphones-will-move-all-phone-services-drfone-by-drfone-transfer-from-ios/"><u>Switch Cards Between Apple iPhone 12 Pro and other iPhones Will Move All Phone Services? | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/5-ways-to-send-ringtones-from-apple-iphone-8-to-iphone-including-iphone-15-drfone-by-drfone-transfer-from-ios/"><u>5 Ways to Send Ringtones from Apple iPhone 8 to iPhone Including iPhone 15 | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-fix-apple-iphone-12-stuck-on-data-transfer-verified-solution-drfone-by-drfone-transfer-from-ios/"><u>In 2024, Fix Apple iPhone 12 Stuck on Data Transfer Verified Solution! | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-4-quick-ways-to-transfer-contacts-from-apple-iphone-xs-to-iphone-withwithout-itunes-drfone-by-drfone-transfer-from-ios/"><u>In 2024, 4 Quick Ways to Transfer Contacts from Apple iPhone XS to iPhone With/Without iTunes | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-transfer-your-apple-iphone-8-apps-to-new-iphone-drfone-by-drfone-transfer-from-ios/"><u>In 2024, Transfer your Apple iPhone 8 Apps to New iPhone | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/5-easy-ways-to-transfer-contacts-from-apple-iphone-se-2020-to-android-drfone-by-drfone-transfer-from-ios/"><u>5 Easy Ways to Transfer Contacts from Apple iPhone SE (2020) to Android | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-how-to-transfersync-notes-from-apple-iphone-15-plus-to-ipad-drfone-by-drfone-transfer-from-ios/"><u>In 2024, How to Transfer/Sync Notes from Apple iPhone 15 Plus to iPad | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-how-to-transfer-data-from-apple-iphone-6-to-zte-phones-drfone-by-drfone-transfer-from-ios/"><u>In 2024, How to Transfer Data from Apple iPhone 6 to ZTE Phones | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-how-to-transfer-photos-from-apple-iphone-7-to-other-iphone-without-icloud-drfone-by-drfone-transfer-from-ios/"><u>In 2024, How to Transfer Photos from Apple iPhone 7 to other iPhone without iCloud | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/how-to-transfer-photos-from-apple-iphone-11-to-other-iphone-without-icloud-drfone-by-drfone-transfer-from-ios/"><u>How to Transfer Photos from Apple iPhone 11 to other iPhone without iCloud | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/4-ways-to-transfer-music-from-apple-iphone-15-pro-max-to-ipod-touch-drfone-by-drfone-transfer-from-ios/"><u>4 Ways to Transfer Music from Apple iPhone 15 Pro Max to iPod touch | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-how-to-transfersync-notes-from-apple-iphone-se-to-ipad-drfone-by-drfone-transfer-from-ios/"><u>In 2024, How to Transfer/Sync Notes from Apple iPhone SE to iPad | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-how-to-transfer-from-apple-iphone-14-plus-to-iphone-8x11-drfone-by-drfone-transfer-from-ios/"><u>In 2024, How to Transfer from Apple iPhone 14 Plus to iPhone 8/X/11 | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-4-ways-to-transfer-contacts-from-apple-iphone-13-pro-max-to-iphone-quickly-drfone-by-drfone-transfer-from-ios/"><u>In 2024, 4 Ways to Transfer Contacts from Apple iPhone 13 Pro Max to iPhone Quickly | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-easy-methods-how-to-transfer-pictures-from-apple-iphone-se-to-pc-drfone-by-drfone-transfer-from-ios/"><u>In 2024, Easy Methods How To Transfer Pictures From Apple iPhone SE to PC | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-how-to-transfer-photos-from-apple-iphone-14-to-other-iphone-without-icloud-drfone-by-drfone-transfer-from-ios/"><u>In 2024, How to Transfer Photos from Apple iPhone 14 to other iPhone without iCloud | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/6-methods-for-switching-from-apple-iphone-13-to-samsung-drfone-by-drfone-transfer-from-ios/"><u>6 Methods for Switching from Apple iPhone 13 to Samsung | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-refurbished-apple-iphone-15-pro-everything-you-need-to-know-drfone-by-drfone-transfer-from-ios/"><u>In 2024, Refurbished Apple iPhone 15 Pro Everything You Need to Know | Dr.fone</u></a></li> <li><a href="https://ai-video-apps.techidaily.com/new-mov-video-rotator-top-5-free-downloads-for-2024/"><u>New MOV Video Rotator Top 5 Free Downloads for 2024</u></a></li> <li><a href="https://fix-guide.techidaily.com/solved-warning-camera-failed-on-itel-p40plus-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Solved Warning Camera Failed on Itel P40+ | Dr.fone</u></a></li> <li><a href="https://ai-voice-clone.techidaily.com/updated-in-2024-best-10-free-ai-video-generators-with-innovativeadvanced-algorithms/"><u>Updated In 2024, Best 10 Free AI Video Generators with Innovative/Advanced Algorithms</u></a></li> <li><a href="https://android-frp.techidaily.com/in-2024-is-gsm-flasher-adb-legit-full-review-to-bypass-your-sony-xperia-1-v-phone-frp-lock-by-drfone-android/"><u>In 2024, Is GSM Flasher ADB Legit? Full Review To Bypass Your Sony Xperia 1 V Phone FRP Lock</u></a></li> <li><a href="https://ai-editing-video.techidaily.com/how-to-import-and-adjust-the-video-clips-on-wondershare-filmora/"><u>How To Import and Adjust the Video Clips on Wondershare Filmora?</u></a></li> <li><a href="https://ios-unlock.techidaily.com/5-most-effective-methods-to-unlock-apple-iphone-14-pro-in-lost-mode-by-drfone-ios/"><u>5 Most Effective Methods to Unlock Apple iPhone 14 Pro in Lost Mode</u></a></li> <li><a href="https://location-social.techidaily.com/how-to-change-location-on-tiktok-to-see-more-content-on-your-oppo-reno-10-proplus-5g-drfone-by-drfone-virtual-android/"><u>How to Change Location on TikTok to See More Content On your Oppo Reno 10 Pro+ 5G | Dr.fone</u></a></li> <li><a href="https://android-frp.techidaily.com/in-2024-is-gsm-flasher-adb-legit-full-review-to-bypass-your-sony-xperia-10-v-phone-frp-lock-by-drfone-android/"><u>In 2024, Is GSM Flasher ADB Legit? Full Review To Bypass Your Sony Xperia 10 V Phone FRP Lock</u></a></li> <li><a href="https://android-location-track.techidaily.com/in-2024-two-ways-to-track-my-boyfriends-realme-11-proplus-without-him-knowing-drfone-by-drfone-virtual-android/"><u>In 2024, Two Ways to Track My Boyfriends Realme 11 Pro+ without Him Knowing | Dr.fone</u></a></li> <li><a href="https://screen-mirror.techidaily.com/in-2024-how-to-cast-xiaomi-redmi-note-12-pro-5g-screen-to-pc-using-wifi-drfone-by-drfone-android/"><u>In 2024, How to Cast Xiaomi Redmi Note 12 Pro 5G Screen to PC Using WiFi | Dr.fone</u></a></li> <li><a href="https://animation-videos.techidaily.com/updated-12-best-stop-motion-studios-worth-recommending/"><u>Updated 12 Best Stop Motion Studios Worth Recommending</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/2024-approved-best-12-ai-video-generators-to-pick/"><u>2024 Approved Best 12 AI Video Generators to Pick</u></a></li> <li><a href="https://apple-account.techidaily.com/how-to-change-credit-card-on-your-iphone-x-apple-id-and-apple-pay-by-drfone-ios/"><u>How to Change Credit Card on Your iPhone X Apple ID and Apple Pay</u></a></li> <li><a href="https://ios-pokemon-go.techidaily.com/catchemall-celebrate-national-pokemon-day-with-virtual-location-on-apple-iphone-11-pro-max-drfone-by-drfone-virtual-ios/"><u>CatchEmAll Celebrate National Pokémon Day with Virtual Location On Apple iPhone 11 Pro Max | Dr.fone</u></a></li> <li><a href="https://phone-solutions.techidaily.com/device-unlock-camon-20-pro-5g-by-drfone-android-unlock-android-unlock/"><u>Device unlock Camon 20 Pro 5G</u></a></li> <li><a href="https://review-topics.techidaily.com/quickly-remove-google-frp-lock-on-galaxy-s24-by-drfone-android-unlock-remove-google-frp/"><u>Quickly Remove Google FRP Lock on Galaxy S24</u></a></li> <li><a href="https://location-fake.techidaily.com/3utools-virtual-location-not-working-on-apple-iphone-13-fix-now-drfone-by-drfone-virtual-ios/"><u>3uTools Virtual Location Not Working On Apple iPhone 13? Fix Now | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/unlock-iphone-11-pro-with-forgotten-passcode-different-methods-you-can-try-drfone-by-drfone-ios/"><u>Unlock iPhone 11 Pro With Forgotten Passcode Different Methods You Can Try | Dr.fone</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/can-i-use-itools-gpx-file-to-catch-the-rare-pokemon-on-itel-p55plus-drfone-by-drfone-virtual-android/"><u>Can I use iTools gpx file to catch the rare Pokemon On Itel P55+ | Dr.fone</u></a></li> <li><a href="https://blog-min.techidaily.com/how-to-repair-corrupt-mp4-and-avi-files-of-phantom-v-flip-by-stellar-video-repair-mobile-video-repair/"><u>How to Repair corrupt MP4 and AVI files of Phantom V Flip?</u></a></li> </ul></div>
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:quiz_app/Data/questions.dart'; import 'package:quiz_app/questions_summary.dart'; import 'package:quiz_app/quiz.dart'; class ResultsScreen extends StatelessWidget { const ResultsScreen({super.key, required this.chosenAnswers, required this.restartQuiz}); final List<String> chosenAnswers; final void Function() restartQuiz; List<Map<String, Object>> getSummaryData(){ final List<Map<String, Object>> summary = []; for(var i = 0; i< chosenAnswers.length; i++) { summary.add({ //below 4 lines become 1 map object and not 4 map objects. 1 element of a map can store multiple data about 1 question like ‘question_index’, ‘question’, ‘user_answer’, etc 'question_index': i, //Key:Value pair 'question': questions[i].text, 'user_answer':chosenAnswers[i], 'correct_answer':questions[i].answers[0] }); } return summary; } @override Widget build(BuildContext context) { final summaryData= getSummaryData(); final numTotalQuestions = questions.length; final numCorrectQuestions = summaryData.where((element) => element['user_answer']==element['correct_answer']).length; //'where' is used to filter the list return SizedBox( width: double.infinity, child: Container( margin: const EdgeInsets.all(40), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text("You answered $numCorrectQuestions out of $numTotalQuestions questions correctly!", textAlign: TextAlign.center, style: GoogleFonts.lato( fontWeight: FontWeight.bold, fontSize: 20, color: const Color.fromARGB(255, 255, 255, 255) ),), const SizedBox(height: 30), QuestionsSummary(summaryData), const SizedBox(height: 30,), TextButton.icon( onPressed: restartQuiz, icon: const Icon(Icons.refresh), label: const Text("Restart Quiz")) ], ), ), ); } }
package com.example.rail3.model; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private double price; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ivtmg_id", nullable = false) private Ivtmg ivtmg; // Constructors public Product() { } public Product(String name, double price, Ivtmg ivtmg) { this.name = name; this.price = price; this.ivtmg = ivtmg; } // Getters and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Ivtmg getIvtmg() { return ivtmg; } public void setIvtmg(Ivtmg ivtmg) { this.ivtmg = ivtmg; } }
<!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>Veterinary Landing Page</title> <!-- google font css starts --> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,300;1,400;1,500;1,600;1,700;1,800&family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Raleway:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800&display=swap" rel="stylesheet"> <!-- font awesome cdn starts --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"> <!-- bootstarp css starts --> <link rel="stylesheet" href="css/bootstrap.css"> <!-- aniamtion css starts --> <!-- <link rel="stylesheet" href="css/slick.css"> <link rel="stylesheet" href="css/animate.min.css"> --> <link rel="stylesheet" href="css/venobox.min.css"> <!-- style css starts --> <link rel="stylesheet" href="css/style.css"> <!-- media/responsive css starts --> <link rel="stylesheet" href="css/responsive.css"> </head> <body> <!-- navabr part starts --> <nav class="navbar navbar-expand-lg navbar-light"> <div class="container"> <a class="navbar-brand" href="index.html"> <img src="images/logo.png" alt="logo.png"> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <i class="fa fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ms-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active popin-med fs-20 text-white text-capitalize mb-0" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link popin-med fs-20 text-white text-capitalize mb-0" href="#">about</a> </li> <li class="nav-item"> <a class="nav-link popin-med fs-20 text-white text-capitalize mb-0" href="#">service</a> </li> <li class="nav-item"> <a class="nav-link popin-med fs-20 text-white text-capitalize mb-0" href="#">contact</a> </li> </ul> <form class="d-flex"> <input class="form-control rounded-0 popin-reg fs-15 text-capitalize" type="search" placeholder="Search" aria-label="Search"> <button class="btn rounded-0 btn-outline-success" type="submit"><i class="fas fa-search"></i></button> </form> </div> </div> </nav> <!-- navabr part ends --> <!-- banner part starts --> <section id="banner"> <div class="container"> <div class="row"> <div class="col-lg-8 col-md-6 col-sm-6 col-12"> <div class="banner-text"> <h4 class="popin-sbold text-white mb-0">First I wanted to be a veterinarian</h4> <p class="popin-reg text-white mb-0">Lorem Ipsum available but the majority have suffered alteration in some form, by injected humour randomised words.</p> <a href="#" class="cta-btn btn btn-outline-light text-capitalize text-white popin-sbold fs-16">contact us</a> <a href="#" class="cta-btn btn btn-outline-light text-capitalize text-white popin-sbold fs-16">our service</a> </div> </div> <div class="col-lg-4 col-md-6 col-sm-6 col-12"> <div class="banner-img"> <a href="#"><img src="images/banner.png" alt="banner.png" class="w-100"></a> </div> </div> </div> </div> </section> <!-- banner part ends --> <!-- about part starts --> <section id="about"> <div class="container"> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-12"> <div class="about-text"> <h4 class="popin-sbold mb-0">As a veterinarian and lover of animals.</h4> <p class="popin-reg mb-0">Lorem Ipsum available but the majoty suffered alteration in some form, by humour randomised words.</p> <a href="#" class="btn text-capitalize popin-sbold fs-16">our service</a> </div> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-12"> <div class="about-box"></div> <div class="about-img"> <a href="#"><img src="images/about.png" alt="about.png" class="w-100"></a> <div class="video-icon"> <a href="https://www.youtube.com/watch?v=WiVQ3Ds8YHc" class="venobox" data-autoplay="true" data-vbtype="video"> <i class="fa-solid fa-play"></i> </a> </div> </div> </div> </div> </div> </section> <!-- about part ends --> <!-- service part starts --> <section id="service"> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-12"> <div class="service-head"> <h4 class="popin-bold text-capitalize mb-0 text-center text-white">title here</h4> <p class="popin-reg mb-0 text-center text-white"> Lorem Ipsum available, but the majority have suffered alteration in some form.</p> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-12"> <div class="service-img"> <img src="images/service1.png" alt="service1.png"> <h4 class="popin-sbold text-capitalize mb-0 text-center text-white">veterinarian</h4> <p class="popin-reg mb-0 text-center text-white"> Lorem Ipsum available, but the majority have suffered alteration in some.</p> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-12"> <div class="service-img"> <img src="images/service2.png" alt="service2.png"> <h4 class="popin-bold text-capitalize mb-0 text-center text-white">Vaccination Care</h4> <p class="popin-reg mb-0 text-center text-white"> Lorem Ipsum available, but the majority have suffered alteration in some.</p> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-12"> <div class="service-img"> <img src="images/service3.png" alt="service3.png"> <h4 class="popin-bold text-capitalize mb-0 text-center text-white">dental care</h4> <p class="popin-reg mb-0 text-center text-white"> Lorem Ipsum available, but the majority have suffered alteration in some.</p> </div> </div> </div> </div> </section> <!-- service part ends --> <!-- video part starts --> <section id="video"> <div class="container"> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-12"> <div class="video-box"></div> <div class="video-img"> <a href="#"><img src="images/video.png" alt="video.png" class="w-100"></a> <div class="video-icon"> <a href="https://www.youtube.com/watch?v=WiVQ3Ds8YHc" class="venobox" data-autoplay="true" data-vbtype="video"> <i class="fa-solid fa-play"></i> </a> </div> </div> </div> <div class="col-lg-6 col-md-6 col-sm-6 col-12"> <div class="video-text text-end"> <h4 class="popin-sbold text-end mb-0">As a veterinarian and lover of animals.</h4> <p class="popin-reg text-end mb-0">Lorem Ipsum available but the majoty suffered alteration in some form, by humour randomised words.</p> <a href="#" class="btn text-capitalize text-end popin-sbold fs-16">our service</a> </div> </div> </div> </div> </section> <!-- video part ends --> <!-- title part starts --> <section id="title"> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-12"> <div class="title-head"> <h4 class="popin-bold text-capitalize mb-0 text-center text-white">title here</h4> <p class="popin-reg mb-0 text-center text-white"> Lorem Ipsum available, but the majority have suffered alteration in some form.</p> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-12"> <div class="title-img"> <img src="images/title1.png" alt="title1.png" class="w-100"> <a href="#" class="btn btn-outline-light text-capitalize text-white popin-sbold fs-16">buy now</a> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-12"> <div class="title-img"> <img src="images/title2.png" alt="title2.png" class="w-100"> <a href="#" class="btn btn-outline-light text-capitalize text-white popin-sbold fs-16">buy now</a> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-12"> <div class="title-img"> <img src="images/title3.png" alt="title3.png" class="w-100"> <a href="#" class="btn btn-outline-light text-capitalize text-white popin-sbold fs-16">buy now</a> </div> </div> </div> </div> </section> <!-- title part ends --> <!-- team part ends --> <section id="team"> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-12"> <div class="team-head"> <h4 class="popin-bold text-capitalize mb-0 text-center">the vetcare team</h4> <p class="popin-reg mb-0 text-center"> Lorem Ipsum available, but the majority have suffered alteration in some form.</p> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-12"> <div class="team-img"> <img src="images/team1.png" alt="team1.png" class="w-100"> <h4 class="popin-bold text-capitalize mb-0 text-center">Jennifer Mullen</h4> <p class="popin-reg mb-0 text-center text-uppercase"> veterinary</p> <div class="social-links text-center"> <a href="https://www.instagram.com/" target="_blank"><i class="fa-brands fa-instagram"></i></a> <a href="https://www.facebook.com/" target="_blank"><i class="fa-brands fa-facebook"></i></a> <a href="https://twitter.com/" target="_blank"><i class="fa-brands fa-twitter"></i></a> <a href="https://www.whatsapp.com/" target="_blank"><i class="fa-brands fa-whatsapp"></i></a> </div> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-12"> <div class="team-img"> <img src="images/team2.png" alt="team2.png" class="w-100"> <h4 class="popin-bold text-capitalize mb-0 text-center">Sheeren Collins</h4> <p class="popin-reg mb-0 text-center text-uppercase">administration</p> <div class="social-links text-center"> <a href="https://www.instagram.com/" target="_blank"><i class="fa-brands fa-instagram"></i></a> <a href="https://www.facebook.com/" target="_blank"><i class="fa-brands fa-facebook"></i></a> <a href="https://twitter.com/" target="_blank"><i class="fa-brands fa-twitter"></i></a> <a href="https://www.whatsapp.com/" target="_blank"><i class="fa-brands fa-whatsapp"></i></a> </div> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-12"> <div class="team-img"> <img src="images/team3.png" alt="team3.png" class="w-100"> <h4 class="popin-bold text-capitalize mb-0 text-center">Jennifer Mullen</h4> <p class="popin-reg mb-0 text-center text-uppercase">veterinary</p> <div class="social-links text-center"> <a href="https://www.instagram.com/" target="_blank"><i class="fa-brands fa-instagram"></i></a> <a href="https://www.facebook.com/" target="_blank"><i class="fa-brands fa-facebook"></i></a> <a href="https://twitter.com/" target="_blank"><i class="fa-brands fa-twitter"></i></a> <a href="https://www.whatsapp.com/" target="_blank"><i class="fa-brands fa-whatsapp"></i></a> </div> </div> </div> </div> </div> </section> <!-- team part ends --> <!-- funfact part starts --> <section id="funfact"> <div class="container"> <div class="row"> <div class="col-lg-4 col-md-4 col-sm-4 col-6"> <div class="funfact-item"> <a href="#" class="text-center text-white"><i class="fa-brands fa-gratipay"></i></a> <p class="popin-med text-white text-center mb-0 counter">34793</p> <h4 class="popin-bold text-white text-center text-capitalize mb-0">happy clients</h4> </div> </div> <div class="col-lg-4 col-md-4 col-sm-4 col-6"> <div class="funfact-item"> <a href="#" class="text-center text-white"><i class="fa-brands fa-gratipay"></i></a> <p class="popin-med text-white text-center mb-0 counter">45382</p> <h4 class="popin-bold text-white text-center text-capitalize mb-0">department</h4> </div> </div> <div class="col-lg-4 col-md-4 col-sm-4 col-6"> <div class="funfact-item"> <a href="#" class="text-center text-white"><i class="fa-brands fa-gratipay"></i></a> <p class="popin-med text-white text-center mb-0 counter">54762</p> <h4 class="popin-bold text-white text-center text-capitalize mb-0">Vaccination</h4> </div> </div> </div> </div> </section> <!-- funfact part ends --> <!-- post part starts --> <section id="post"> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-12"> <div class="post-head"> <h4 class="popin-bold text-capitalize mb-0 text-center">recent posts</h4> <p class="popin-reg mb-0 text-center"> Lorem Ipsum available, but the majority have suffered alteration in some form.</p> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-12"> <div class="post-item"> <div class="post-img"> <img src="images/post1.png" alt="post1.png"> </div> <div class="post-text"> <h4 class="popin-bold mb-0">As a veterinarian and lover of animals</h4> <h6 class="popin-reg mb-0 text-uppercase">february 09,2020</h6> <p class="popin-reg mb-0">Lorem Ipsum available, but the majo rity have suffered alteration in some words which look.</p> <h3 class="popin-reg mb-0 text-uppercase">read more +</h3> </div> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-12"> <div class="post-item"> <div class="post-img"> <img src="images/post2.png" alt="post2.png"> </div> <div class="post-text"> <h4 class="popin-bold mb-0">As a veterinarian and lover of animals</h4> <h6 class="popin-reg mb-0 text-uppercase">february 10,2020</h6> <p class="popin-reg mb-0">Lorem Ipsum available, but the majo rity have suffered alteration in some words which look.</p> <h3 class="popin-reg mb-0 text-uppercase">read more +</h3> </div> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-12"> <div class="post-item"> <div class="post-img"> <img src="images/post3.png" alt="post3.png"> </div> <div class="post-text"> <h4 class="popin-bold mb-0">As a veterinarian and lover of animals</h4> <h6 class="popin-reg mb-0 text-uppercase">february 11,2020</h6> <p class="popin-reg mb-0">Lorem Ipsum available, but the majo rity have suffered alteration in some words which look.</p> <h3 class="popin-reg mb-0 text-uppercase">read more +</h3> </div> </div> </div> </div> </div> </section> <!-- post part ends --> <!-- footer part starts --> <section id="footer"> <div class="container"> <div class="row"> <div class="col-lg-3 col-md-4 col-sm-6 col-6"> <div class="footer-about"> <h4 class="mb-0 text-white popin-sbold fs-35 text-capitalize">about</h4> <ul class="ps-0 mb-0 text-white popin-reg fs-18 text-capitalize"> <li>history</li> <li>our team</li> <li>brand guidelines</li> <li>terms & condition</li> <li>privacy policy</li> </ul> </div> </div> <div class="col-lg-3 col-md-4 col-sm-6 col-6"> <div class="footer-service"> <h4 class="mb-0 text-white popin-sbold fs-35 text-capitalize">services</h4> <ul class="ps-0 mb-0 text-white popin-reg fs-18 text-capitalize"> <li>how to order</li> <li>our product</li> <li>order status</li> <li>promo</li> <li>payment method</li> </ul> </div> </div> <div class="col-lg-6 col-md-4 col-sm-6 col-12"> <div class="footer-title text-lg-end"> <h4 class=" text-white popin-sbold fs-35 text-capitalize">title here</h4> <p class="mb-0 text-white popin-reg fs-20">Lorem Ipsum available, but the majorit.</p> <form class="d-flex"> <input class="form-control rounded-0 popin-reg fs-15 text-capitalize" type="search"> <button class="btn rounded-0 btn-outline-success" type="submit"><i class="fas fa-paper-plane"></i></button> </form> <div class="social-links text-lg-end"> <a href="https://www.instagram.com/" target="_blank"><i class="fa-brands fa-instagram"></i></a> <a href="https://www.facebook.com/" target="_blank"><i class="fa-brands fa-facebook"></i></a> <a href="https://twitter.com/" target="_blank"><i class="fa-brands fa-twitter"></i></a> <a href="https://www.whatsapp.com/" target="_blank"><i class="fa-brands fa-whatsapp"></i></a> </div> </div> </div> </div> </div> </section> <!-- footer part ends --> <script src="js/jquery-2.2.4.min.js"></script> <script src="js/bootstrap.bundle.min.js"></script> <script src="js/typed.min.js"></script> <script src="js/parallax.min.js"></script> <script src="js/tilt.jquery.min.js"></script> <script src="js/wow.min.js"></script> <script src="js/venobox.min.js"></script> <script src="js/mixitup.min.js"></script> <script src="js/slick.min.js"></script> <script src="js/waypoints.min.js"></script> <script src="js/jquery.counterup.min.js"></script> <script src="js/custom.js"></script> </body> </html>
= Importing DataWeave Libraries :page-deployment-options: cloud-ide, desktop-ide // :page-aliases: import-dataweave-library.adoc include::reuse::partial$beta-banner.adoc[tag="anypoint-code-builder"] //LOGO (web, desktop, or both) // include::partial$acb-ide-logos.adoc[tags="both-ides"] Use Anypoint Code Builder to import DataWeave libraries from Exchange into your Mule application. A DataWeave library is a reusable package of DataWeave modules and mapping files, and resource files, such as JSON, XML, and CSV. == Before You Begin * xref:start-acb.adoc[Set up and access the web or desktop IDE]. * xref:int-create-integrations.adoc[Create an integration]. == Import a DataWeave Library You can import a DataWeave library the same way you import any other asset from Exchange: . Open your integration project in Anypoint Code Builder. // Pointer to Command Palette include::partial$acb-reusable-steps.adoc[tags="open-command-palette"] . Enter `import` and select the following command: + [source,command] -- MuleSoft: Import Asset from Exchange -- . Select *DataWeave Library*. + To search for a library, type the search term and press Enter. For example, enter *DataWeave*: + image::int-dw-libraries.png["Search for DataWeave libraries"] . Select the DataWeave library from the *Assets From Exchange* menu. . Select a version of the DataWeave library. + The status bar shows the progress. When complete, Anypoint Code Builder shows a message that the dependency was successfully added to the project.
import React, { useState } from 'react'; import { useDispatch } from 'react-redux'; import { addProduct } from '../redux/actions/productActions'; const CreateProduct = () => { const [name, setName] = useState(''); const [description, setDescription] = useState(''); const [price, setPrice] = useState(''); const dispatch = useDispatch(); const handleSubmit = (e) => { e.preventDefault(); const newProduct = { name, description, price: parseFloat(price), }; dispatch(addProduct(newProduct)); setName(''); setDescription(''); setPrice(''); }; return ( <div> <h1>Create Product</h1> <form onSubmit={handleSubmit}> <label> Name: <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> </label> <label> Description: <input type="text" value={description} onChange={(e) => setDescription(e.target.value)} /> </label> <label> Price: <input type="number" value={price} onChange={(e) => setPrice(e.target.value)} /> </label> <button type="submit">Create</button> </form> </div> ); }; export default CreateProduct;
$(function() { let currentURL = window.location.href; /** * Evento para mostrar el formulario de crear un nuevo modulo */ $(document).on("click", ".newMensaje", function(e) { e.preventDefault(); $('#tituloModal').html('Nuevo Mensaje'); $('#action').removeClass('updateMensaje'); $('#action').addClass('saveMensaje'); let url = currentURL + '/mensajes/create'; $.get(url, function(data, textStatus, jqXHR) { $('#modal').modal('show'); $("#modal-body").html(data); }); }); /** * Evento para guardar el nuevo modulo */ $(document).on('click', '.saveMensaje', function(event) { event.preventDefault(); let nombre = $("#nombre").val(); let mensaje = $("#mensaje").val(); let _token = $("input[name=_token]").val(); let url = currentURL + '/mensajes'; $.post(url, { nombre: nombre, mensaje: mensaje, _token: _token }, function(data, textStatus, xhr) { $('.viewResult').html(data); }).done(function() { $('.modal-backdrop ').css('display', 'none'); $('#modal').modal('hide'); Swal.fire( 'Correcto!', 'El registro ha sido guardado.', 'success' ) }).fail(function(data) { printErrorMsg(data.responseJSON.errors); }); }); /** * Evento para mostrar el formulario de edicion de un canal */ $(document).on("click", ".editMensaje", function(e) { e.preventDefault(); $('#tituloModal').html('Editar Mensaje'); $('#action').removeClass('saveMensaje'); $('#action').addClass('updateMensaje'); let id = $("#idSeleccionado").val(); let url = currentURL + "/mensajes/" + id + "/edit"; $.get(url, function(data, textStatus, jqXHR) { $('#modal').modal('show'); $("#modal-body").html(data); }); }); /** * Evento para mostrar el formulario editar modulo */ $(document).on('click', '#table-mensajes tbody tr', function(event) { event.preventDefault(); let id = $(this).data("id"); $(".editMensaje").slideDown(); $(".deleteMensaje").slideDown(); $("#idSeleccionado").val(id); $("#table-mensajes tbody tr").removeClass('table-primary'); $(this).addClass('table-primary'); }); /** * Evento para editar el modulo */ $(document).on('click', '.updateMensaje', function(event) { event.preventDefault(); let nombre = $("#nombre").val(); let mensaje = $("#mensaje").val(); let id = $("#idSeleccionado").val(); let _token = $("input[name=_token]").val(); let _method = "PUT"; let url = currentURL + '/mensajes/' + id; $.ajax({ url: url, type: 'POST', data: { nombre: nombre, mensaje: mensaje, _token: _token, _method: _method }, success: function(result) { $('.viewResult').html(result); $('.viewCreate').slideUp(); } }).done(function(data) { $('.modal-backdrop ').css('display', 'none'); $('#modal').modal('hide'); Swal.fire( 'Correcto!', 'El registro ha sido actualizado.', 'success' ) }).fail(function(data) { printErrorMsg(data.responseJSON.errors); }); }); /** * Evento para eliminar el modulo */ $(document).on('click', '.deleteMensaje', function(event) { event.preventDefault(); Swal.fire({ title: '¿Estas seguro?', text: "Deseas eliminar el registro seleccionado!", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Si, Eliminar!', cancelButtonText: 'Cancelar' }).then((result) => { if (result.value) { let id = $("#idSeleccionado").val(); let _token = $("input[name=_token]").val(); let _method = "DELETE"; let url = currentURL + '/mensajes/' + id; $.ajax({ url: url, type: 'POST', data: { _token: _token, _method: _method }, success: function(result) { $('.viewResult').html(result); $('.viewCreate').slideUp(); Swal.fire( 'Eliminado!', 'El registro ha sido eliminado.', 'success' ) } }); } }); }); /** * Evento para mostrar los permisos por menu */ $(document).on('click', '.modulo', function() { var id = $(this).data("value"); if ($(this).prop('checked')) { $("#sub_cat_" + id).slideDown(); } else { $("#sub_cat_" + id).slideUp(); } }); /** * Funcion para mostrar los errores de los formularios */ function printErrorMsg(msg) { $(".print-error-msg").find("ul").html(''); $(".print-error-msg").css('display', 'block'); $(".form-control").removeClass('is-invalid'); for (var clave in msg) { $("#" + clave).addClass('is-invalid'); if (msg.hasOwnProperty(clave)) { $(".print-error-msg").find("ul").append('<li>' + msg[clave][0] + '</li>'); } } } });