text stringlengths 184 4.48M |
|---|
// Functions for generating data
// Returns vanilla data with 3 circular normals
function threenorm(n) {
var rnorm = d3.random.normal();
var data = new Array(n);
for (var i = 0; i < n; i++) {
var j = Math.floor(Math.random() * 3);
if (j % 3 == 0) {
mux = -6;
muy = -6;
} else if (j % 3 == 1) {
mux = 6;
muy = -6;
} else {
mux = 0;
muy = 6;
}
data[i] = { x: rnorm() + mux, y: rnorm() + muy, cluster: 0 };
}
return data;
}
// Uniformly
function uniform(n) {
var data = new Array(n);
for (var i = 0; i < n; i++) {
data[i] = {
x: Math.random() * 20 - 10,
y: Math.random() * 20 - 10,
cluster: 0,
};
}
return data;
}
// Returns a smiley face :)
function smiley(n) {
var data = new Array(n);
var i = 0;
while (i < n) {
var x = Math.random() * 20 - 10;
var y = Math.random() * 20 - 10;
// Smiley params
var a = 6;
var b = 8;
var d = 4;
var c = 0.15;
var C = c - a / (b * b);
// The border
if (x * x + y * y < 100 && x * x + y * y > 81) {
data[i] = { x: x, y: y, cluster: 0 };
i += 1;
}
// Left eye
else if ((x + 4) * (x + 4) + (y - 4) * (y - 4) < 1) {
data[i] = { x: x, y: y, cluster: 0 };
i += 1;
}
// Right eye
else if ((x - 4) * (x - 4) + (y - 4) * (y - 4) < 1) {
data[i] = { x: x, y: y, cluster: 0 };
i += 1;
}
// Smile
else if (x > -b && x < b && y > c * x * x - a && y < C * x * x - d) {
data[i] = { x: x, y: y, cluster: 0 };
i += 1;
}
}
return data;
}
// returns a smiley face with 10% pimples
function pimples(n) {
var face = smiley(n - Math.floor(n * 0.1));
var pimples = uniform(Math.floor(n * 0.1));
// Not shuffled, though...
var res = face.concat(pimples);
return res;
}
// Packed circles
function circle_pack(n) {
var r = 3;
var R = r * 1.05; // a little extra space
var root3 = Math.sqrt(3);
var circles = [
{ x: -2 * R, y: 0 },
{ x: 0, y: 0 },
{ x: 2 * R, y: 0 },
{ x: -R, y: root3 * R },
{ x: R, y: root3 * R },
{ x: -R, y: -root3 * R },
{ x: R, y: -root3 * R },
];
var data = new Array(n);
var i = 0;
while (i < n) {
var x = Math.random() * 20 - 10;
var y = Math.random() * 20 - 10;
for (var j = 0; j < circles.length; j++) {
if (
Math.sqrt(
Math.pow(x - circles[j].x, 2) + Math.pow(y - circles[j].y, 2)
) < r
) {
data[i] = { x: x, y: y, cluster: 0 };
i += 1;
}
}
}
return data;
}
// Varying density
function density_bars(n) {
var data = new Array(n);
for (var i = 0; i < n; i++) {
var u = Math.floor(8 * Math.random());
var y = Math.random() * 8 - 4;
var x;
if (u == 0) {
x = (Math.random() * 20) / 3 - 10;
} else if (u <= 6) {
x = (Math.random() * 20) / 3 - 10 + 20 / 3;
} else {
x = (Math.random() * 20) / 3 - 10 + 40 / 3;
}
data[i] = { x: x, y: y, cluster: 0 };
}
return data;
}
// DBSCAN Rings
function dbscan_rings() {
var centers = new Array(0);
var rings = new Array(0);
var rows = 6;
var cols = 5;
for (var row = 0; row < rows; row++) {
for (var col = 0; col < cols; col++) {
var MinPoints = row;
var eps = 1.25 - col * 0.25;
var x0 = -15 + (30 / (rows + 1)) * (row + 1);
var y0 = -12 + (24 / (cols + 1)) * (col + 1);
centers.push({ x: x0, y: y0, cluster: 0 });
for (var i = 0; i < MinPoints; i++) {
var x = x0 + eps * Math.sin((2 * Math.PI * i) / MinPoints);
var y = y0 + eps * Math.cos((2 * Math.PI * i) / MinPoints);
rings.push({ x: x, y: y, cluster: 0 });
}
}
}
return { centers: centers, rings: rings };
}
function dbscan_all() {
var res = dbscan_rings();
return res.centers.concat(res.rings);
}
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o) {
//v1.0
for (
var j, x, i = o.length;
i;
j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x
);
return o;
}
// DBSCAN Border points
function dbscan_borders() {
return shuffle([
{ cluster: 0, x: 0, y: 0 }, // center point
{ cluster: 0, x: -1.8, y: 0 }, // left point
{ cluster: 0, x: -2.3, y: 0 }, // left point "buddies"
{ cluster: 0, x: -2.3, y: 0.5 },
{ cluster: 0, x: -2.3, y: -0.5 },
{ cluster: 0, x: 1.8, y: 0 }, // right point
{ cluster: 0, x: 2.3, y: 0 }, // right point "buddies"
{ cluster: 0, x: 2.3, y: 0.5 },
{ cluster: 0, x: 2.3, y: -0.5 },
]);
} |
/******************************************************************************/
/* */
/* gstlearn C++ Library */
/* */
/* Copyright (c) (2023) MINES Paris / ARMINES */
/* Authors: gstlearn Team */
/* Website: https://gstlearn.org */
/* License: BSD 3-clause */
/* */
/******************************************************************************/
#pragma once
#include "gstlearn_export.hpp"
#include "geoslib_define.h"
#include "Db/DbGrid.hpp"
#include "Skin/ISkinFunctions.hpp"
#include "Basic/AStringable.hpp"
#include "Simulation/ACalcSimulation.hpp"
class Skin;
class MatrixRectangular;
/**
* Multivariate multiphase propagation into a set of components
* constrained by initial conditions and fluid densities
*
* \remark Directions are ordered as follows :
* \remark 0: +X; 1: -X; 2: +Y; 3: -Y; 4: +Z(up); 5: -Z(down)
* \remark The coding of the matrix is:
* \remark facies + nfacies * fluid
* \remark Facies: 0 (Shale), 1 to nfacies, -1 (Cork)
* \remark Fluids: 0 (undefined), 1 to nfluids, -1 (No Fluid)
* \remark Fluids should be ordered by increasing weight
* \remark A Permeability variable is a value (>=1) which divides
* \remark the velocities. This variable is optional.
* \remark A Porosity variable is a value (in [0,1]) which multiplies
* \remark the volumes. This variable is optional.
* \remark Volume_max represents the volumic part of the invaded area:
* \remark it is always <= number of cells invaded.
*/
class GSTLEARN_EXPORT CalcSimuEden: public ACalcSimulation, public AStringable, public ISkinFunctions
{
public:
CalcSimuEden(int nfacies = 0,
int nfluids = 0,
int niter = 1,
int nbsimu = 0,
int seed = 4324324,
bool verbose = false);
CalcSimuEden(const CalcSimuEden &r) = delete;
CalcSimuEden& operator=(const CalcSimuEden &r) = delete;
virtual ~CalcSimuEden();
/// Interface to AStringable
virtual String toString(const AStringFormat* strfmt = nullptr) const override;
/// Interface to ISkinFunctions
int isAlreadyFilled(int ipos) const override;
int isToBeFilled(int ipos) const override;
double getWeight(int ipos, int idir) const override;
void setIndFacies(int indFacies) { _indFacies = indFacies; }
void setIndFluid(int indFluid) { _indFluid = indFluid; }
void setIndPerm(int indPerm) { _indPerm = indPerm; }
void setIndPoro(int indPoro) { _indPoro = indPoro; }
void setSpeeds(const VectorInt &speeds) { _speeds = speeds; }
void setNumberMax(double numberMax) { _numberMax = numberMax; }
void setShowFluid(bool showFluid) { _showFluid = showFluid; }
void setVolumeMax(double volumeMax) { _volumeMax = volumeMax; }
private:
virtual bool _check() override;
virtual bool _preprocess() override;
virtual bool _run() override;
virtual bool _postprocess() override;
virtual void _rollback() override;
bool _simulate();
bool _fluid_check(void);
int _getWT(int ifacies, int ifluid, int perm, int idir);
int _getFACIES(int iech) const;
int _getFLUID(int iech) const;
int _getFLUID_OLD(int iech) const;
int _getPERM(int iech) const;
double _getDATE(int iech);
double _getPORO(int iech) const;
void _setFLUID(int iech, int ifluid);
void _setFACIES(int iech, int ifacies);
void _setFACIES_CORK(int iech);
void _setDATE(int iech, int idate);
void _printParams(bool verbose);
void _statsDefine(void);
void _statsReset();
void _statsInit();
void _setStatNumber(int ifacies, int ifluid, int value);
void _setStatVolume(int ifacies, int ifluid, double value);
void _addStatNumber(int ifacies, int ifluid, int value);
void _addStatVolume(int ifacies, int ifluid, double value);
void _checkInconsistency(bool verbose);
int _getStatNumber(int ifacies, int ifluid) const;
double _getStatVolume(int ifacies, int ifluid) const;
int _checkMax(double number_max, double volume_max);
int _fluidModify(Skin *skin, int ipos, int *ref_fluid_loc);
void _statsPrint(const char *title);
void _statsEmpty(const char *title);
void _calculateCumul(void);
void _updateResults(int reset_facies, int show_fluid);
void _normalizeCumul(int niter);
int _countAlreadyFilled() const;
int _countIsToBeFilled() const;
private:
bool _verbose;
/// 1 for modifying the value of the cells to show
///\li the initial valid fluid information
///\li the cork (different from shale)
bool _showFluid;
int _iptrStatFluid;
int _iptrStatCork;
int _iptrFluid;
int _iptrDate;
int _niter; /// Number of iterations
int _nfacies; /// number of facies (facies 0 excluded)
int _nfluids; /// number of fluids
VectorInt _speeds; /// array containing the travel speeds
double _numberMax; /// Maximum count of cells invaded (or TEST)
double _volumeMax; /// Maximum volume invaded (or TEST)
int _indFacies; /// Rank of the variable containing the Facies
int _indFluid; /// Rank of the variable containing the Fluid
int _indPerm; /// Rank of the variable containing the Permeability
int _indPoro; /// Rank of the variable containing the Porosity
int _indDate;
int _nxyz;
int _ncork;
VectorInt _numbers;
VectorDouble _volumes;
};
GSTLEARN_EXPORT int fluid_propagation(DbGrid *dbgrid,
const String& name_facies,
const String& name_fluid,
const String& name_perm,
const String& name_poro,
int nfacies,
int nfluids,
int niter = 1,
const VectorInt& speeds = VectorInt(),
bool show_fluid = false,
double number_max = TEST,
double volume_max = TEST,
int seed = 321321,
bool verbose = false,
const NamingConvention& namconv = NamingConvention("Eden")); |
<navbar></navbar>
<div class="container">
<div class="row">
<h1>myXPulse: Manage my profile</h1>
</div>
<div class="row">
<table class="table table-hover">
<thead>
<tr>
<th scope="col"></th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">username: </th>
<td>{{user.username}}</td>
<td>
<button class="btn btn-info" data-toggle="modalUN" data-target="#modalUN" (click)="modalUN.show()" mdbTooltip="Not case sensitive!" placement="top">Change
username</button>
<button class="btn btn-warning" data-toggle="modalPW" data-target="#modalPW" (click)="modalPW.show()">Change
password</button>
</td>
</tr>
<tr>
<th scope="row">First Name: </th>
<td>{{user.firstname}}</td>
<td>
<button class="btn btn-outline-success" data-toggle="modalFN" data-target="#modalFN"
(click)="modalFN.show()">Edit</button>
</td>
</tr>
<tr>
<th scope="row">Last Name: </th>
<td>{{user.lastname}}</td>
<td>
<button class="btn btn-outline-success" data-toggle="modalLN" data-target="#modalLN"
(click)="modalLN.show();">Edit</button>
</td>
</tr>
<tr [ngClass]="{
'table-secondary': user.role == 'Regular',
'table-info': user.role == 'VIP',
'table-primary': user.role == 'Administrator',
'table-danger': user.role == 'Owner',
'table-default': user.role == null}">
<th scope="row">Role</th>
<td>{{user.role}}</td>
<td>
<button *ngIf="user.role == 'Regular'" type="button" class="btn btn-success">Upgrade to VIP</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div mdbModal #modalFN="mdbModal" class="modal fade" id="firstNameModal" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-notify modal-success" role="document" style="width:80%;">
<div class="modal-content">
<div class="modal-header text-center">
<h4 class="modal-title white-text w-100 font-weight-bold py-2">Change First Name:</h4>
<button type="button" class="close" data-dismiss="modalFN" (click)="modalFN.hide()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="md-form mb-5">
<form class="container aligned" [formGroup]="firstNameForm" (ngSubmit)="updateFirstName();modalFN.hide()">
<div class="form-group">
<label class="sr-only" for="oldFirstName">Current First Name:</label>
<h5 class="mb-2 mr-sm-2">Current First Name:</h5>
<p class="inputreadonly">{{user.firstname}}</p>
</div>
<div class="form-group">
<h5 class="mb-2 mr-sm-2">New First Name:</h5>
<label class="sr-only" for="newFirstName"></label>
<input type="text" class="form-control mb-2 mr-sm-2" placeholder="" formControlName="newFirstName">
</div>
<div class="modal-footer">
<button class="btn btn-primary">Update</button>
<button type="button" class="btn btn-secondary" (click)="modalFN.hide()"
data-dismiss="modalFN">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div mdbModal #modalLN="mdbModal" class="modal fade" id="lastNameModal" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-notify modal-success" role="document" style="width:80%;">
<div class="modal-content">
<div class="modal-header text-center">
<h4 class="modal-title white-text w-100 font-weight-bold py-2">Change Last Name:</h4>
<button type="button" class="close" data-dismiss="modalLN" (click)="modalLN.hide()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="md-form mb-5">
<form class="container aligned" [formGroup]="lastNameForm" (ngSubmit)="updateLastName();modalLN.hide()">
<div class="form-group">
<label class="sr-only" for="oldLastName">Current Last Name:</label>
<h5 class="mb-2 mr-sm-2">Current Last Name:</h5>
<p class="inputreadonly">{{user.lastname}}</p>
</div>
<div class="form-group">
<h5 class="mb-2 mr-sm-2">New Last Name:</h5>
<label class="sr-only" for="newLastName"></label>
<input type="text" class="form-control mb-2 mr-sm-2" placeholder="" formControlName="newLastName">
</div>
<div class="modal-footer">
<button class="btn btn-primary">Update</button>
<button type="button" class="btn btn-secondary" (click)="modalLN.hide()"
data-dismiss="modalLN">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div mdbModal #modalUN="mdbModal" class="modal fade" id="UserNameModal" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-notify modal-info" role="document" style="width:80%;">
<div class="modal-content">
<div class="modal-header text-center">
<h4 class="modal-title white-text w-100 font-weight-bold py-2">Change Username:</h4>
<button type="button" class="close" data-dismiss="modalUN" (click)="modalUN.hide()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="md-form mb-5">
<form class="container aligned" [formGroup]="UserNameForm" (ngSubmit)="changeUsername();modalUN.hide()">
<div class="form-group">
<label class="sr-only" for="oldUserName">Current Username:</label>
<h5 class="mb-2 mr-sm-2">Current Username Name:</h5>
<p class="inputreadonly">{{user.username}}</p>
</div>
<div class="form-group">
<h5 class="mb-2 mr-sm-2">New Username:</h5>
<label class="sr-only" for="newUserName"></label>
<input type="text" class="form-control mb-2 mr-sm-2" placeholder="" formControlName="newUserName">
</div>
<div class="form-group">
<h5 class="mb-2 mr-sm-2">Insert Password for Confirmation:</h5>
<label class="sr-only" for="passwdConfirm"></label>
<input type="password" class="form-control mb-2 mr-sm-2" placeholder="" formControlName="passwdConfirm">
</div>
<div class="modal-footer">
<button class="btn btn-primary">Update</button>
<button type="button" class="btn btn-secondary" (click)="modalUN.hide()"
data-dismiss="modalUN">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div mdbModal #modalPW="mdbModal" class="modal fade" id="PasswordModal" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-notify modal-warning" role="document" style="width:80%;">
<div class="modal-content">
<div class="modal-header text-center">
<h4 class="modal-title white-text w-100 font-weight-bold py-2">Change Password:</h4>
<button type="button" class="close" data-dismiss="modalPW" (click)="modalPW.hide()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="md-form mb-5">
<form class="container aligned" [formGroup]="PasswordForm" id="PasswordForm" (ngSubmit)="changePassword();modalPW.hide()">
<div class="form-group">
<label class="sr-only" for="oldPassword">Current Password:</label>
<h5 class="mb-2 mr-sm-2">Insert Current Password:</h5>
<input type="password" class="form-control mb-2 mr-sm-2" required minlength="4" placeholder="" formControlName="oldPassword">
</div>
<div class="form-group">
<h5 class="mb-2 mr-sm-2">Insert New Password:</h5>
<label class="sr-only" for="newPassword"></label>
<input type="password" class="form-control mb-2 mr-sm-2" required minlength="4" placeholder="" formControlName="newPassword">
</div>
<div class="form-group">
<h5 class="mb-2 mr-sm-2">Confirm New Password:</h5>
<label class="sr-only" for="newPasswordConfirm"></label>
<input type="password" class="form-control mb-2 mr-sm-2" required minlength="4" placeholder=""
formControlName="newPasswordConfirm">
</div>
<div class="modal-footer">
<button class="btn btn-primary" [disabled]="!(PasswordForm.valid)">Update</button>
<button type="button" class="btn btn-secondary" (click)="modalPW.hide()"
data-dismiss="modalPW">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div> |
<?php
namespace App\Http\Livewire\Admin\Store;
use App\Models\Country;
use App\Models\Store;
use App\Models\StoreBranch;
use App\Models\StoreBranchImage;
use App\Models\StoreDate;
use App\Traits\UploadTrait;
use Exception;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithFileUploads;
class UpdateStore extends Component {
use WithFileUploads, UploadTrait;
public $currentStep = 1;
public $successMsg = '';
public $store = [];
public $currentStore;
// ############## step 1 properties
public $keys;
public $categories;
public $image, $identity_image, $name, $country_code, $phone, $identity_number, $email, $password, $is_blocked, $speciality_id;
// ################### step 3 properties
public $comerical_record, $detection_price, $lat, $lng, $address, $day, $from, $to, $storeName, $opening_certificate_pdf, $opening_certificate_image;
public $images = [];
public $workTimes = [];
public $branches = [];
public $currentBranches = [];
public $deletedBranches = [];
public function mount() { //// used to get data used in the blade
$this->keys = Country::get();
$this->currentStore = Store::with('branches', 'branches.images', 'branches.dates')->findOrFail(request()->id);
$this->name = $this->currentStore->name;
$this->country_code = $this->currentStore->country_code;
$this->phone = $this->currentStore->phone;
$this->identity_number = $this->currentStore->identity_number;
$this->email = $this->currentStore->email;
$this->is_blocked = $this->currentStore->is_blocked;
foreach ($this->currentStore->branches as $branch) {
$this->currentBranches[] = [
'id' => $branch->id,
'images' => [],
'view_images' => $branch->images->pluck('image')->toArray(),
'lat' => $branch->lat,
'lng' => $branch->lng,
'address' => $branch->address,
'detection_price' => $branch->detection_price,
'comerical_record' => $branch->comerical_record,
'name' => $branch->name,
'work_times' => $branch->dates,
'opening_certificate_image' => $branch->opening_certificate_image,
];
}
}
protected $listeners = ['changeMap' => 'changeMap'];
public function changeMap($lat, $lng, $address) {
$this->lat = $lat;
$this->lng = $lng;
$this->address = $address;
}
public function updating() {
$this->successMsg = '';
}
protected function uploadFile($file, $directory) {
if ($file) {
$rondomName = time() . '_' . bin2hex(random_bytes(15)) . '.' . $file->getClientOriginalExtension();
$file->storeAs($directory, $rondomName);
return $rondomName;
}
return null;
}
protected function updateFile($key, $directory) {
if ($file = $this->uploadFile($this->store[$key], 'images/' . $directory)) {
$this->deleteFile($this->currentStore->getRawOriginal($key), $directory);
$this->store[$key] = $file;
}
}
public function firstStepSubmit() {
$rules = [
'image' => 'nullable|image',
'identity_image' => 'nullable|image',
'name' => 'required|max:255',
'country_code' => 'required',
'phone' => 'required|min:8|max:11|unique:users,phone',
'identity_number' => 'required|min:10',
'email' => 'required|unique:users,email',
'password' => 'nullable|min:6',
'is_blocked' => 'required',
];
$this->store = $this->validate($rules);
$this->currentStep = 2;
}
// start branch section ######################################################################################
// images
public function deleteBranchImage($index) {
unset($this->images[$index]);
}
// end branch section ######################################################################################
// start times section ######################################################################################
public function saveTime() {
$validatedData = $this->validate([
'day' => 'required|in:saturday,sunday,monday,tuesday,wednesday,thursday,friday',
'from' => 'required',
'to' => 'required',
]);
$this->workTimes[$this->day] = [
'day' => $this->day,
'from' => $this->from,
'to' => $this->to,
];
$this->day = null;
$this->from = null;
$this->to = null;
}
public function deleteWorkingTime($key) {
unset($this->workTimes[$key]);
}
public function editWorkingTime($key) {
$this->day = $this->workTimes[$key]['day'];
$this->from = $this->workTimes[$key]['from'];
$this->to = $this->workTimes[$key]['to'];
unset($this->workTimes[$key]);
}
// end times section ######################################################################################
public function saveBranch() {
$validatedData = $this->validate([
'images' => 'required|array',
'images.*' => 'image',
'comerical_record' => 'required|min:10',
'storeName' => 'required',
'workTimes' => 'required|array',
'workTimes.*.day' => 'required',
'workTimes.*.from' => 'required',
'workTimes.*.to' => 'required',
'lat' => 'required',
'lng' => 'required',
'address' => 'required',
'storeName' => 'required',
'opening_certificate_pdf' => 'required',
'opening_certificate_image' => 'required|image',
]);
$this->branches[] = [
'name' => $this->storeName,
'images' => $this->images,
'lat' => $this->lat,
'lng' => $this->lng,
'address' => $this->address,
'comerical_record' => $this->comerical_record,
'detection_price' => $this->detection_price,
'work_times' => $this->workTimes,
'opening_certificate_pdf' => $this->opening_certificate_pdf,
'opening_certificate_image' => $this->opening_certificate_image,
];
$this->lat = $this->lng = $this->opening_certificate_pdf = $this->opening_certificate_image = $this->address = $this->comerical_record = $this->storeName = null;
$this->images = $this->workTimes = [];
}
public function deleteBranch($index) {
unset($this->branches[$index]);
}
public function deleteCurrentBranch($branch_id) {
if (count($this->currentBranches) + count($this->branches) > 1) {
$this->deletedBranches[$branch_id] = $branch_id;
}
}
public function undoDeleteBranch($branch_id) {
unset($this->deletedBranches[$branch_id]);
}
public function editBranch($index) {
$branch = $this->branches[$index];
$this->storeName = $branch['name'];
$this->lat = $branch['lat'];
$this->lng = $branch['lng'];
$this->address = $branch['address'];
$this->comerical_record = $branch['comerical_record'];
$this->detection_price = $branch['detection_price'];
$this->images = $branch['images'];
$this->workTimes = $branch['work_times'];
$this->opening_certificate_pdf = $branch['opening_certificate_pdf'];
$this->opening_certificate_image = $branch['opening_certificate_image'];
$this->emit('updateMap');
unset($this->branches[$index]);
}
public function store() {
$this->validate([
'branches' => 'nullable|array',
]);
if ($this->speciality_id !== null) {
$this->store['category_id'] = $this->speciality_id;
}
DB::beginTransaction();
// dd($this->labData);
try {
$this->updateFile('image', 'stores');
$this->updateFile('identity_image', 'stores');
$this->currentStore->update($this->store);
// add the branches of the lab
foreach ($this->branches as $branch) {
$branch['opening_certificate_pdf'] = $this->uploadFile($branch['opening_certificate_pdf'], 'images/storebranch');
$branch['opening_certificate_image'] = $this->uploadFile($branch['opening_certificate_image'], 'images/storebranch');
$newBranch = StoreBranch::create($branch + (['store_id' => $this->currentStore->id]));
// save work times of the branch
$branchWorkTimes = [];
foreach ($branch['work_times'] as $workTime) {
$branchWorkTimes[] = [
'store_id' => $this->currentStore->id,
'store_branch_id' => $newBranch->id,
'day' => $workTime['day'],
'from' => $workTime['from'],
'to' => $workTime['to'],
];
}
StoreDate::insert($branchWorkTimes);
// save branch images
$branchImages = [];
foreach ($branch['images'] as $branchImage) {
$branchImages[] = [
'image' => $this->uploadFile($branchImage, 'images/storeimages'),
'store_id' => $this->currentStore->id,
'store_branch_id' => $newBranch->id,
];
}
StoreBranchImage::insert($branchImages);
} /// end add branches
if (count($this->deletedBranches) > 0) {
$this->currentStore->branches->whereIn('id', $this->deletedBranches)->each(function ($branch) {
$branch->images->each->delete();
$branch->delete();
});
}
DB::commit();
return redirect()->route('admin.stores.all')->with(['success' => __('admin.update_successfullay')]);
} catch (Exception $e) {
DB::rollBack();
dd($e);
}
}
public function back($step) {
$this->currentStep = $step;
}
public function render() {
return view('livewire.admin.store.update-store');
}
} |
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { Ng2SearchPipeModule } from 'ng2-search-filter';
import { FullCalendarModule } from '@fullcalendar/angular'; // must go before plugins
import dayGridPlugin from '@fullcalendar/daygrid'; // a plugin!
import interactionPlugin from "@fullcalendar/interaction"; // a plugin!
import {ModalModule} from "ngx-bootstrap/modal";
import { AppComponent } from './app.component';
import { BodyComponent } from './body/body.component';
import { SidenavComponent } from './sidenav/sidenav.component';
import { HomeComponent } from './home/home.component';
import { ReportComponent } from './report/report.component';
import { CalendarComponent } from './calendar/calendar.component';
import { FriendsComponent } from './friends/friends.component';
import { ProfileComponent } from './profile/profile.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { ForgotPasswordComponent } from './forgot-password/forgot-password.component';
import {MatCardModule} from "@angular/material/card";
import {FormsModule} from "@angular/forms";
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { WorkspaceComponent } from './workspace/workspace.component';
import { BoardComponent } from './board/board.component';
import {ActivateAccountComponent} from "./activate-account/activate-account.component";
import { ListComponent } from './list/list.component';
import { CardComponent } from './task/task.component';
import { NotActivatedComponent } from './not-activated/not-activated.component';
import { ResetPasswordComponent } from './reset-password/reset-password.component';
import { RequestInterceptInterceptor } from './interceptors/request-intercept.interceptor';
import { ResponseInterceptInterceptor } from './interceptors/response-intercept.interceptor';
import { FavoriteComponent } from './favorite/favorite.component';
import { ChatComponent } from './chat/chat.component';
import { ActivityComponent } from './activity/activity.component';
import { MdbModalModule } from 'mdb-angular-ui-kit/modal';
import { FavBoardComponent } from './fav-board/fav-board.component';
import { FavWorkspaceComponent } from './fav-workspace/fav-workspace.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { NoDataComponent } from './no-data/no-data.component';
import {BsDropdownModule} from "ngx-bootstrap/dropdown";
import {NgxSpinnerModule} from "ngx-spinner";
import { CommentComponent } from './comment/comment.component';
import { CommentsComponent } from './comments/comments.component';
import { CommentFormComponent } from './commentForm/commentForm.component';
FullCalendarModule.registerPlugins([ // register FullCalendar plugins
dayGridPlugin,
interactionPlugin
]);
@NgModule({
declarations: [
AppComponent,
BodyComponent,
SidenavComponent,
HomeComponent,
HomeComponent,
ReportComponent,
CalendarComponent,
FriendsComponent,
ProfileComponent,
LoginComponent,
RegisterComponent,
ForgotPasswordComponent,
WorkspaceComponent,
BoardComponent,
ActivateAccountComponent,
ListComponent,
CardComponent,
NotActivatedComponent,
ResetPasswordComponent,
FavoriteComponent,
ChatComponent,
ActivityComponent,
FavBoardComponent,
FavWorkspaceComponent,
PageNotFoundComponent,
NoDataComponent,
CommentComponent,
CommentsComponent,
CommentFormComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
ReactiveFormsModule,
MatCardModule,
FormsModule,
HttpClientModule,
MdbModalModule,
Ng2SearchPipeModule,
FullCalendarModule,
ModalModule.forRoot(),
BsDropdownModule,
NgxSpinnerModule,
],
providers: [
{
provide : HTTP_INTERCEPTORS , useClass : RequestInterceptInterceptor,multi : true
},
{
provide : HTTP_INTERCEPTORS , useClass : ResponseInterceptInterceptor,multi : true
}
],
bootstrap: [AppComponent]
})
export class AppModule { } |
from steps.step import Step
from utils import external_project as ext
from utils import command
from utils.log import log
from steps.windows.folders import KnownFolder
from pathlib import Path
class IconsStep(Step):
def __init__(self):
super().__init__("Icons")
self._icons_dir = Path(__file__).parent / "icons"
self._merge_commands = False
def express_dependencies(self, dependency_dispatcher):
dependency_dispatcher.add_packages("windows-handies")
known_folders = dependency_dispatcher.get_known_folders()
self._root_folder = known_folders.get(KnownFolder.Root)
self._multimedia_folder = known_folders.get(KnownFolder.Multimedia)
self._programs_folder = known_folders.get(KnownFolder.Programs)
self._hw_tools_folder = known_folders.get(KnownFolder.HwTools)
def perform(self):
self.download_icons()
self.setup_icons()
def download_icons(self):
log("Downloading icons")
ext.download_github_zip("PaiSetup", "WindowsIcons", self._icons_dir, False)
def setup_icons(self):
# Gather commands to execute
icon_commands = []
if self._root_folder:
icon_commands.append(f'Iconfigure.exe -y -f -l "{self._icons_dir}" -d "{self._root_folder}"')
if self._multimedia_folder:
icon_commands.append(f'Iconfigure.exe -y -f -l "{self._icons_dir}" -d "{self._multimedia_folder}"')
if self._programs_folder or self._hw_tools_folder:
icon_command = f'Iconfigure.exe -y -f -l "{self._icons_dir}" -r'
if self._programs_folder:
icon_command += f' -d "{self._programs_folder}"'
if self._hw_tools_folder:
icon_command += f' -d "{self._hw_tools_folder}"'
icon_commands.append(icon_command)
# Execute commands
log("Setting up icons")
if self._merge_commands:
command.run_powershell_command(icon_commands)
else:
for icon_command in icon_commands:
command.run_powershell_command([icon_command]) |
package com.example.myapplication
// imports all important classes
import android.icu.text.SimpleDateFormat
import android.icu.util.Calendar
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import java.util.Locale
class JournalEntriesAdapter(
private val entries: MutableList<JournalEntry>, // list of journal entries
private val onDeleteClick: (String) -> Unit, // callback for delete clicks
private val onItemClick: (JournalEntry) -> Unit, // callback for item clicks
private var layoutType: String // layout to determine how many recyclerview items shown
) : RecyclerView.Adapter<JournalEntriesAdapter.ViewHolder>() {
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val titleTextView: TextView = view.findViewById(R.id.recent_entry_title)
val contentTextView: TextView = view.findViewById(R.id.recent_entry_summary)
private val deleteButton: ImageButton = view.findViewById(R.id.delete_entryBtn)
init {
deleteButton.setOnClickListener { // set a click listener on the delete button
val position = bindingAdapterPosition // get current position
if (position != RecyclerView.NO_POSITION) {
val entry = entries.getOrNull(position) // proceeds if the entry and its id are not null
entry?.id?.let { nonNullEntryId ->
onDeleteClick(nonNullEntryId) // call the delete click function
}
}
}
view.setOnClickListener {
val position = bindingAdapterPosition
if (position != RecyclerView.NO_POSITION) {
val entry = entries.getOrNull(position)
entry?.let { nonNullEntry ->
onItemClick(nonNullEntry) // call the item click function
}
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.recent_entry, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val entry = entries[position]
// sets title and content
holder.titleTextView.text = entry.title
holder.contentTextView.text = entry.content
// formats the current date and sets it to TextView for display
val currentDate = Calendar.getInstance().time
val dateFormat = SimpleDateFormat("dd MMMM yyyy", Locale.getDefault())
val formattedDate = dateFormat.format(currentDate)
holder.itemView.findViewById<TextView>(R.id.recent_entry_date).text = formattedDate
}
override fun getItemCount(): Int {
// returns the number of items based on the layout type
return when (layoutType) {
"activity_home_page" -> minOf(entries.size, 2) // limits to 2 on homepage (for recents)
"gallery_of_entries" -> entries.size // no minimum for gallery_of_entries, scroll
else -> entries.size
}
}
// updates the layout type
fun updateLayoutType(newLayoutType: String) {
layoutType = newLayoutType
notifyDataSetChanged()
}
// updates list of entries
fun updateEntries(newEntries: MutableList<JournalEntry>) {
entries.clear() // clears list
entries.addAll(newEntries) // adds new entries
notifyDataSetChanged()
}
} |
import { useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { useAuth } from '../../../../hooks/useAuth'
import api from '../../../../services/api.service'
import { FriendProps } from '../../../../interfaces'
import { Button } from '../../../../components/Button'
import { FriendsContainer } from './styles'
import { NoProfileImage } from '../../../../components/NoProfileImage'
export function FriendsTab() {
const { name } = useParams() as { name: string; tab: string }
const { user } = useAuth()
const [tab, setTab] = useState(0)
const [friends, setFriends] = useState<FriendProps[]>([])
const [paddingFriends, setPaddingFriends] = useState<FriendProps[]>([])
const [isTheUserAuthenticated] = useState(user?.name === name)
console.log(isTheUserAuthenticated)
useEffect(() => {
load()
async function load() {
try {
const response = await api.get(`/user/${name}/friends`)
const data = response.data as FriendProps[]
setFriends(data)
} catch (error) {}
}
}, [name])
useEffect(() => {
load()
async function load() {
try {
const response = await api.get(`/me/paddingfriends`)
const data = response.data as FriendProps[]
setPaddingFriends(data)
} catch (error) {}
}
}, [])
async function acceptFriend(friendName: string) {
try {
await api.post(`/me/paddingfriends`, {
name: friendName,
})
const newFriend = paddingFriends.find(
(content) => content.name === friendName
)
if (newFriend) {
setFriends([...friends, newFriend])
}
setPaddingFriends(
paddingFriends.filter((content) => content.name !== friendName)
)
} catch (error) {
alert('An error occurred, try later')
console.error(error)
}
}
async function rejectFriend(friendName: string) {
try {
await api.delete('/me/paddingfriends', {
data: { name: friendName },
})
setPaddingFriends(
paddingFriends.filter((content) => content.name !== friendName)
)
} catch (error) {
alert('An error occurred, try later')
console.error(error)
}
}
return (
<FriendsContainer>
<nav>
<ul>
<li className={`${tab === 0 && 'seleted'}`} onClick={() => setTab(0)}>
Todos os amigos ({friends.length})
</li>
{isTheUserAuthenticated && (
<li
className={`${tab === 1 && 'seleted'}`}
onClick={() => setTab(1)}
>
Pendente ({paddingFriends.length})
</li>
)}
</ul>
</nav>
<div className="list">
{tab === 0 &&
friends.map((friend) => (
<div className="friendCard" key={friend.id}>
{friend.icon ? (
<img src={friend.icon} alt={`${friend.icon} icon`} />
) : (
<NoProfileImage
name={friend.displayName}
width={48}
height={48}
/>
)}
<Link to={`/user/${friend.name}`} className="name">
{friend.displayName}
</Link>
<div></div>
</div>
))}
{tab === 1 &&
paddingFriends.map((friend) => (
<div className="friendCard paddingFriendCard" key={friend.id}>
<img
src="https://assets.faceit-cdn.net/avatars/f6df2599-8174-467b-a4e9-fdfe0e40a719_1615691262786.jpg"
alt=""
/>
<Link to={`/user/${friend.name}`} className="name">
{friend.displayName}
</Link>
<div className="actions">
<Button onClick={() => acceptFriend(friend.name)} opaque>
aceitar
</Button>
<Button onClick={() => rejectFriend(friend.name)} opaque>
remover
</Button>
</div>
</div>
))}
</div>
</FriendsContainer>
)
} |
const date = new Date()
const years = []
const months = []
const days = []
const outtype = ["早饭", "午饭", "晚饭", "零食", "饮料酒水", "购物", "交通", "教育", "娱乐", "红包礼物", "水电费", "网费", "话费", "医疗", "投资", "其他"]
const intype = ["工资", "投资收入", "红包", "借入", "二手闲置", "其他"]
for (let i = 1990; i <= date.getFullYear(); i++) {
years.push(i)
}
for (let i = 1; i <= 12; i++) {
months.push(i)
}
for (let i = 1; i <= 31; i++) {
days.push(i)
}
// pages/addrecord/addrecord.js
Page({
/**
* 页面的初始数据
*/
data: {
openid: "",
useinfo: {},
account: [],
accountid: "",
accountName: "",
oldaccountid: "",
accountbalance: 0,
ios: [{
value: "out",
name: "支出",
checked: "true"
},
{
value: "in",
name: "收入",
}
],
io: "out",
years: years,
year: date.getFullYear(),
months: months,
month: 1,
days: days,
day: 1,
datavalue: [9999, 0, 0],
messageremind: "请输入备注,默认为无",
balanceremind: "请输入记账金额",
balance: 0,
types: outtype,
type: "早饭",
message: "无",
},
//获取账户列表
getaccount: function () {
wx.cloud.database().collection('account').get()
.then(res => {
this.setData({
account: res.data,
accountid: res.data[0]._id,
accountbalance: res.data[0].accountbalance,
accountName: res.data[0].accountname
})
}).catch(res => {})
},
// 获取输入
iochange: function (e) {
this.setData({
io: e.detail.value,
})
if (e.detail.value == "in") {
this.setData({
types: intype,
type: "工资"
})
} else {
this.setData({
types: outtype,
type: "早餐"
})
}
},
accountChange: function (e) {
const val = e.detail.value
this.setData({
accountid: this.data.account[val]._id,
accountbalance: this.data.account[val].accountbalance,
accountName: this.data.account[val].accountname
})
},
typeChange: function (e) {
const val = e.detail.value
this.setData({
type: this.data.types[val],
})
},
dataChange: function (e) {
const val = e.detail.value
this.setData({
year: this.data.years[val[0]],
month: this.data.months[val[1]],
day: this.data.days[val[2]]
})
},
oninputmessage: function (event) {
this.setData({
message: event.detail.value
})
},
oninputbalance: function (event) {
this.setData({
balance: event.detail.value
})
},
// 提示内容
onfocusmessage: function (e) {
this.setData({
messageremind: ""
})
},
onblurmessage: function (e) {
this.setData({
messageremind: "请输入备注,默认为无"
})
},
onfocusbalance: function (e) {
this.setData({
balanceremind: ""
})
},
onblurbalance: function (e) {
this.setData({
balanceremind: "请输入记账金额"
})
},
//添加记账
addrecord: function () {
var recordaccountid = this.data.accountid
var recordaccountname = this.data.accountName
var recordyear = this.data.year
var recordmonth = this.data.month
var recordday = this.data.day
var recordtype = this.data.type
var recordbalance = (this.data.io == "in") ? this.data.balance : -this.data.balance
var recordmessage = this.data.message
var recorddata = String(recordyear) + "-" + (String(recordmonth).length == 1 ? ("0" + String(recordmonth)) : String(recordmonth)) + "-" + (String(recordday).length == 1 ? ("0" + String(recordday)) : String(recordday))
if (recordaccountid === "") {
wx.showToast({
title: '请先创建账户',
icon: 'error'
})
return;
}
if (isNaN(recordbalance)) {
wx.showToast({
title: '金额应该是数字',
icon: 'error'
})
return;
}
wx.showLoading({
title: '添加中',
})
wx.cloud.database().collection('record').add({
data: {
recordaccountid: recordaccountid,
recorddata: recorddata,
recordtype: recordtype,
recordbalance: recordbalance,
recordmessage: recordmessage,
recordaccountname: recordaccountname
},
success: res => {
var newbalance = Number(this.data.accountbalance) + Number(recordbalance)
wx.cloud.database().collection('account').doc(this.data.accountid).update({
data: {
accountbalance: newbalance
},
success: res => {},
fail: res => {},
})
wx.hideLoading({
success: (res) => {
wx.showToast({
title: '添加成功',
})
},
})
wx.navigateBack({
delta: 1
})
},
fail: res => {
console.log('添加失败', res)
wx.hideLoading({
success: (res) => {
wx.showToast({
title: '添加失败',
icon: 'error'
})
},
})
}
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
this.getaccount()
this.setData({
openid: wx.getStorageSync('openid'),
useinfo: wx.getStorageSync('userinfo'),
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
}) |
import React, { useEffect } from "react";
import { useContext } from "react";
import appIcon from "../../assets/vid.png";
import { useParams, useLocation } from "react-router";
import { useNavigate } from "react-router-dom";
import "../../styles/video.css";
import videoContext from "../../Context/videoContext";
import { useState } from "react";
import { BallTriangle } from "react-loader-spinner";
import { ToastContainer, toast } from "react-toastify";
import AddPlaylistModal from "../AddPlaylistModal";
import Comments from "../Comments";
const VideoPlayer = () => {
const { videoId } = useParams();
const { pathname } = useLocation();
const navigate = useNavigate();
const [likeCount, setLikeCount] = useState(0);
const [isLikeVideo, setIsLikeVideo] = useState(false);
const [currVideo, setCurrVideo] = useState([]);
const [isAddToWatchLater, setIsAddToWatchLater] = useState(false);
const [likeLoader, setLikeLoader] = useState(false);
const [modalShow, setModalShow] = useState(false);
const {
jwttoken,
getVideoBasedOnId,
likeVideos,
addToWatchLaterVideo,
userFromDb,
loader,
isShowErrorMsg,
} = useContext(videoContext);
useEffect(() => {
const temp = async () => {
if (!jwttoken) navigate("/login");
if (isShowErrorMsg) navigate("/login");
else {
const response = await getVideoBasedOnId(videoId);
setCurrVideo(response?.data.video);
if (isAddedToWatchLaterByUser !== undefined) setIsAddToWatchLater(true);
if (isLikedByUser !== undefined) setIsLikeVideo(true);
}
};
temp();
}, [userFromDb]);
useEffect(() => {
setLikeCount(currVideo?.likes);
}, [currVideo]);
useEffect(() => {
if (isShowErrorMsg) navigate("/404");
}, [isShowErrorMsg]);
const isAddedToWatchLaterByUser = userFromDb?.data.user.watchlist.find(
(video) => video._id === videoId
);
const isLikedByUser = userFromDb?.data.user.likedVideos.find(
(video) => video._id === videoId
);
const likeVideo = async () => {
setLikeLoader(true);
const response = await likeVideos(videoId);
setLikeLoader(false);
if (response.data?.message === "video liked") {
setIsLikeVideo(true);
setLikeCount(likeCount + 1);
} else if (response.data?.message === "video disliked") {
setIsLikeVideo(false);
setLikeCount(likeCount - 1);
}
};
const addToWatchLater = async () => {
const response = await addToWatchLaterVideo(videoId);
if (response.data?.message === "Video added to watch later") {
toast.success(response.data?.message);
setIsAddToWatchLater(true);
} else if (response.data?.message === "Video removed from watch later") {
toast.success(response.data?.message);
setIsAddToWatchLater(false);
}
};
return (
<div className="mainPage">
{loader ? (
<div className="loaderWrapper">
<BallTriangle color="white" />
</div>
) : (
<>
{" "}
<div className="videoPlayerWrapper">
<iframe
allow="fullscreen;"
title={currVideo?.name}
src={`https://www.youtube.com/embed/${videoId}?mute=0`}
></iframe>
<br />
<small>
{currVideo?.category?.map((category) => (
<span key={category}>#{category} </span>
))}
</small>
<h5>{currVideo?.name}</h5>
<div className="actionBtns">
<small>{currVideo?.date}</small>
<div>
<button onClick={likeVideo} disabled={loader}>
{isLikeVideo ? (
<i className="fa fa-thumbs-up fa-x highlighted"></i>
) : (
<i className="fa fa-thumbs-up fa-x"></i>
)}{" "}
<span>
{likeLoader ? (
<span>
<i className="fa fa-spinner fa-pulse fa-x"></i>
</span>
) : (
<span>{likeCount} Likes</span>
)}{" "}
</span>
</button>
{/* new code */}
<button onClick={() => setModalShow(true)}>
<i className="fa fa-bookmark fa-x"></i>{" "}
<span>Save to playlist</span>
</button>
<AddPlaylistModal
videoId={videoId}
show={modalShow}
onHide={() => setModalShow(false)}
/>
{/* ends */}
<button onClick={addToWatchLater}>
{isAddToWatchLater ? (
<>
<i className="fa fa-clock-o fa-x highlighted"></i>{" "}
<span>Added to watched later</span>
</>
) : (
<>
<i className="fa fa-clock-o fa-x"></i>{" "}
<span>Watch later</span>
</>
)}
</button>
<button
onClick={() => {
toast.success("Video link copied to clipboard.");
navigator.clipboard.writeText(
`devplays-shub78910.herokuapp.com${pathname}`
);
}}
>
<i className="fa fa-copy fa-x"></i> Copy link
</button>
</div>
</div>{" "}
<hr />
<div className="d-flex align-items-center justify-content-between">
<div className="d-flex align-items-center">
<img className="hero" src={appIcon} alt="appLogo" />
<h6 className="mx-2">{currVideo?.creator}</h6>
</div>
<div>
<button className="SubscribeBtn">Subscribe</button>
</div>
</div>
{/* comments */}
<div>
<Comments
currVideo={currVideo}
setCurrVideo={setCurrVideo}
videoId={videoId}
/>
</div>
</div>
</>
)}
<ToastContainer
position="bottom-right"
autoClose={3000}
closeOnClick
draggable
pauseOnHover
/>
</div>
);
};
export default VideoPlayer; |
package tk.springmvc.controller;
import com.google.protobuf.ByteString;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
@Controller
@RequestMapping("/upload")
public class FileUploadController {
private static String uploadPath = "/fileupload";
@GetMapping
public String getUpload(){
return "upload";
}
@PostMapping
public String postUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, ModelMap model) throws IOException {
String path = request.getServletContext().getRealPath(uploadPath);
uploadSingleFile(file,path);
model.addAttribute("msg","File is uploaded!");
return "upload";
}
@GetMapping("/batch")
public String getBatchUpload(){
return "batchUpload";
}
@PostMapping("/batch")
public String postBatchUpload(@RequestParam("files") CommonsMultipartFile[] files, HttpServletRequest request, ModelMap model) throws IOException {
String path = request.getServletContext().getRealPath(uploadPath);
for(int i=0;i<files.length;i++){
uploadSingleFile(files[i],path);
}
model.addAttribute("msg","Files are uploaded!");
return "batchUpload";
}
private int uploadSingleFile(CommonsMultipartFile file, String path) throws IOException {
String filename = file.getOriginalFilename();
try(InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(new File(path,filename));){
byte[] buffer = new byte[400];
int len=0;
while((len=is.read(buffer)) != -1){
os.write(buffer);
}
}catch (Exception e){
return -1;
}
return 0;
}
} |
package net.minecraft.resources;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.DynamicOps;
import com.mojang.serialization.Lifecycle;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderGetter;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderOwner;
import net.minecraft.core.Registry;
import net.minecraft.util.ExtraCodecs;
public class RegistryOps<T> extends DelegatingOps<T> {
private final RegistryOps.RegistryInfoLookup lookupProvider;
private static RegistryOps.RegistryInfoLookup memoizeLookup(final RegistryOps.RegistryInfoLookup var0) {
return new RegistryOps.RegistryInfoLookup() {
private final Map<ResourceKey<? extends Registry<?>>, Optional<? extends RegistryOps.RegistryInfo<?>>> lookups = new HashMap();
public <T> Optional<RegistryOps.RegistryInfo<T>> lookup(ResourceKey<? extends Registry<? extends T>> var1) {
Map var10000 = this.lookups;
RegistryOps.RegistryInfoLookup var10002 = var0;
Objects.requireNonNull(var10002);
return (Optional)var10000.computeIfAbsent(var1, var10002::lookup);
}
};
}
public static <T> RegistryOps<T> create(DynamicOps<T> var0, final HolderLookup.Provider var1) {
return create(var0, memoizeLookup(new RegistryOps.RegistryInfoLookup() {
public <E> Optional<RegistryOps.RegistryInfo<E>> lookup(ResourceKey<? extends Registry<? extends E>> var1x) {
return var1.lookup(var1x).map((var0) -> {
return new RegistryOps.RegistryInfo(var0, var0, var0.registryLifecycle());
});
}
}));
}
public static <T> RegistryOps<T> create(DynamicOps<T> var0, RegistryOps.RegistryInfoLookup var1) {
return new RegistryOps(var0, var1);
}
private RegistryOps(DynamicOps<T> var1, RegistryOps.RegistryInfoLookup var2) {
super(var1);
this.lookupProvider = var2;
}
public <E> Optional<HolderOwner<E>> owner(ResourceKey<? extends Registry<? extends E>> var1) {
return this.lookupProvider.lookup(var1).map(RegistryOps.RegistryInfo::owner);
}
public <E> Optional<HolderGetter<E>> getter(ResourceKey<? extends Registry<? extends E>> var1) {
return this.lookupProvider.lookup(var1).map(RegistryOps.RegistryInfo::getter);
}
public static <E, O> RecordCodecBuilder<O, HolderGetter<E>> retrieveGetter(ResourceKey<? extends Registry<? extends E>> var0) {
return ExtraCodecs.retrieveContext((var1) -> {
if (var1 instanceof RegistryOps) {
RegistryOps var2 = (RegistryOps)var1;
return (DataResult)var2.lookupProvider.lookup(var0).map((var0x) -> {
return DataResult.success(var0x.getter(), var0x.elementsLifecycle());
}).orElseGet(() -> {
return DataResult.error(() -> {
return "Unknown registry: " + var0;
});
});
} else {
return DataResult.error(() -> {
return "Not a registry ops";
});
}
}).forGetter((var0x) -> {
return null;
});
}
public static <E, O> RecordCodecBuilder<O, Holder.Reference<E>> retrieveElement(ResourceKey<E> var0) {
ResourceKey var1 = ResourceKey.createRegistryKey(var0.registry());
return ExtraCodecs.retrieveContext((var2) -> {
if (var2 instanceof RegistryOps) {
RegistryOps var3 = (RegistryOps)var2;
return (DataResult)var3.lookupProvider.lookup(var1).flatMap((var1x) -> {
return var1x.getter().get(var0);
}).map(DataResult::success).orElseGet(() -> {
return DataResult.error(() -> {
return "Can't find value: " + var0;
});
});
} else {
return DataResult.error(() -> {
return "Not a registry ops";
});
}
}).forGetter((var0x) -> {
return null;
});
}
public interface RegistryInfoLookup {
<T> Optional<RegistryOps.RegistryInfo<T>> lookup(ResourceKey<? extends Registry<? extends T>> var1);
}
public static record RegistryInfo<T>(HolderOwner<T> a, HolderGetter<T> b, Lifecycle c) {
private final HolderOwner<T> owner;
private final HolderGetter<T> getter;
private final Lifecycle elementsLifecycle;
public RegistryInfo(HolderOwner<T> var1, HolderGetter<T> var2, Lifecycle var3) {
this.owner = var1;
this.getter = var2;
this.elementsLifecycle = var3;
}
public HolderOwner<T> owner() {
return this.owner;
}
public HolderGetter<T> getter() {
return this.getter;
}
public Lifecycle elementsLifecycle() {
return this.elementsLifecycle;
}
}
} |
import { Resolver, Query, Mutation, Args, Int, ResolveField, Parent } from '@nestjs/graphql';
import { MaintenanceService } from './maintenance.service';
import { MaintenanceObjectType } from './entities/maintenance.entity';
import { CreateMaintenanceInput } from './dto/create-maintenance.input';
import { UpdateMaintenanceInput } from './dto/update-maintenance.input';
import { VehicleObjectType } from 'src/vehicle/entities/vehicle.entity';
import { VehicleService } from 'src/vehicle/vehicle.service';
import { SummaryObjectType } from './entities/dashbaord.entity';
import { VehicleStatus } from '@prisma/client';
@Resolver(() => MaintenanceObjectType)
export class MaintenanceResolver {
constructor(
private readonly maintenanceService: MaintenanceService,
private readonly vehicleService: VehicleService,
) { }
@Mutation(() => MaintenanceObjectType)
createMaintenance(@Args('createMaintenanceInput') createMaintenanceInput: CreateMaintenanceInput) {
return this.maintenanceService.create(createMaintenanceInput);
}
@Query(() => [MaintenanceObjectType], { name: 'maintenances' })
findAll(
@Args('incoming', { type: () => Boolean, nullable: true }) incoming?: boolean,
@Args('name', { type: () => String, nullable: true }) name?: string,
) {
return this.maintenanceService.find(incoming || false, name);
}
@Query(() => MaintenanceObjectType, { name: 'maintenance' })
findOne(@Args('id', { type: () => Int }) id: number) {
return this.maintenanceService.getRecordById(id);
}
@ResolveField('vehicle', () => VehicleObjectType)
async vehicle(@Parent() record: MaintenanceObjectType) {
const { vehicleId } = record
return this.vehicleService.getByVehicleId(vehicleId)
}
@Mutation(() => MaintenanceObjectType)
updateMaintenance(@Args('updateMaintenanceInput') updateMaintenanceInput: UpdateMaintenanceInput) {
return this.maintenanceService.update(updateMaintenanceInput.id, updateMaintenanceInput);
}
@Mutation(() => MaintenanceObjectType)
removeMaintenance(@Args('id', { type: () => Int }) id: number) {
return this.maintenanceService.remove(id);
}
@Query(() => SummaryObjectType)
summary() {
return {
vehicleCount: this.vehicleService.getVehicleCount(),
activeVehicleCount: this.vehicleService.getVehicleCount(VehicleStatus.ONLINE),
maintenanceVehicleCount: this.vehicleService.getVehicleCount(VehicleStatus.MAINTENANCE),
}
}
} |
import React from "react";
import recipes from "./recipe.json";
import { Rating } from "semantic-ui-react";
import Link from "next/link";
import { Button } from "semantic-ui-react";
import "semantic-ui-css/semantic.min.css";
import styles from "@/styles/recipe.module.scss";
const RecipeDetails = ({ recipe }) => {
const recipeId = parseInt(recipe.id);
const selectedRecipe = recipes.find((r) => r.id === recipeId);
if (!selectedRecipe) {
return <div className={styles.recipe}>Recipe not found</div>;
}
return (
<>
<main className={styles.main}>
<section className={styles.section1}>
<img
src={selectedRecipe.image}
alt={selectedRecipe.name}
className={styles.food_image}
/>
<h1>{selectedRecipe.name}</h1>
<Rating
icon="star"
defaultRating={selectedRecipe.rating}
maxRating={5}
disabled
size="massive"
/>
<p>{selectedRecipe.information}</p>
<img
src={selectedRecipe.time}
alt="prep_time"
className={styles.time}
/>
</section>
<section className={styles.section2}>
<img src="../images/ingredients_logo.png" alt="ingredients_logo" />
<h1>Ingredients</h1>
<ul className={styles.list}>
{selectedRecipe.ingredients.map((ingredient, index) => (
<li key={index}>{ingredient}</li>
))}
</ul>
</section>
<section className={styles.section3}>
<img src="../images/procedure_logo.png" alt="procedure_logo" />
<h1>Procedure</h1>
<ol className={styles.list}>
{selectedRecipe.procedure.map((step, index) => (
<li key={index}>{step}</li>
))}
</ol>
<img src="../images/nutritionlogo.png" alt="nutritionlogo" />
<h1>Nutrition</h1>
<p>
Calories: {selectedRecipe.nutrition.calories}| Fat:{" "}
{selectedRecipe.nutrition.fat}| Carbohydrates:{" "}
{selectedRecipe.nutrition.carbohydrates}| Protein:{" "}
{selectedRecipe.nutrition.protein}| Fiber:{" "}
{selectedRecipe.nutrition.fiber}
</p>
<Link href="/" passHref>
<Button color="yellow" floated="right" size="huge">
Back to Home page
</Button>
</Link>
</section>
</main>
</>
);
};
export default RecipeDetails; |
# Data postman level 2
หากเราต้องการที่จะ ทดสอบ Test scenario เดียวจำนวนมากกว่า 1 ครั้งโดยใช้ data ที่ต่างกัน สามารถทำได้ 2 วิธี
1 คือ สร้าง collection ใหม่แล้วแก้ไขข้อมูล วิธีนี้จะมีข้อเสียที่จะต้องสร้าง collection มากตาม data ที่ต้องการทดสอบ
2 สร้างไฟล์ data แล้วนำมาใช้ Run collection บน postman วิธีนี้สามารถใช้ 1 collection ในการ run ซ้ำตามจำนวนชุดของข้อมูลในไฟล์ Data ได้
postman สามารถรับค่า data ได้จากไฟล์ 2 แบบ
1. ไฟล์ .json
ตัวอย่างไฟล์ .json
```sh
[
{
"q": "Bicycle",
"offset": 0,
"limit": 20,
"productId": 1,
"quantity": 1,
"burnPoint": 0,
"subTotalPrice": 4314.6,
"discountPrice": 0,
"totalPrice": 4364.6,
"shippingMethodId": 1,
"shippingAddress": "189/413หมู่2",
"shippingSubDistrict": "แพรกษาใหม่",
"shippingDistrict": "เมืองสมุทรปราการ",
"shippingProvince": "สมุทรปราการ",
"shippingZipCode": "10280",
"recipientFirstName": "พงศกร",
"recipientLastName": "รุ่งเรืองทรัพย์",
"recipientPhoneNumber": "090912799",
"paymentMethodId": 1,
"cardName": "พงศกรรุ่งเรืองทรัพย์",
"cardNumber": "4719700591590995",
"expireDate": "02/26",
"cvv": "75",
"otp": 124532,
"refOtp": "AXYZ",
"expected": {
"responseTime": 500,
"productName": "Balance Training Bicycle",
"productPrice": 119.95,
"productPriceThb": 4314.6,
"productPriceFullThb": 4314.597182,
"total": 29,
"productImage": "/Balance_Training_Bicycle.png",
"trackingNumberPrefix": "KR-"
}
}
]
```
2. ไฟล์ .csv
ตัวอย่างไฟล์ .csv
```sh
"q","offset","limit"
"Bicycle",0,20
```
หากต้องการนำ data จากไฟล์ ข้างนอกมาใช้งานใน body สามารถทำได้โดย
1. แทนค่า value ด้วยตัวแปลของค่าที่ต้องการเอามาแทนและตั้งค่าตัวแปลนั้นเป็น variable

2. เมื่อเราจะใช้งาน data จากไฟล์อื่นเราไม่สามารถ run ด้วยวิธีปกติได้ต้อง run collection เท่านั้น เมื่อกด run collection ให้ไปที่ select file ตรง data จากนั้นให้เลือกไฟล์ data ที่ต้องการใช้งาน

3. เราสามารถกด preview เพื่อดู data ที่เราเอาเข้ามาใช้งานได้
 |
const mongoose = require('mongoose');
const Order = require('./models/order');
const Item = require('./models/product');
mongoose.connect('mongodb://localhost:27017/products', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("Mongo connection is open")
})
.catch(err => {
console.log("Mongo connection error.")
console.log(err)
})
const seedItems = [
{
"item name": "Bread",
"desc": "Sweet Bread",
"price": 10,
"currency": "dollar",
"expiry date": "01-12-2020",
"quantity": "1pkt"
},
{
"item name": "Salt",
"desc": "iodised salt",
"price": 5,
"currency": "dollar",
"expiry date": "01-12-2021",
"quantity": "1kg"
},
{
"item name": "Sugar",
"desc": "",
"price": 15,
"currency": "dollar",
"expiry date": "01-12-2021",
"quantity": "1kg"
},
{
"item name": "Sunflower Oil",
"desc": "oil",
"price": 35,
"currency": "dollar",
"expiry date": "01-12-2020",
"quantity": "1L"
},
{
"item name": "Rice",
"desc": "bolied rice",
"price": 100,
"currency": "dollar",
"expiry date": "01-12-2021",
"quantity": "20KG"
},
{
"item name": "Milk",
"desc": "",
"price": 5,
"currency": "dollar",
"expiry date": "15-11-2020",
"quantity": "1pkt"
}
]
Item.remove()
Item.insertMany(seedItems)
.then(res => {
console.log('Loading the items');
console.log(res)
})
.catch(e => {
console.log(e)
})
const seedOrderItems1 = [
{
"item name": "Bread",
"desc": "Sweet Bread",
"price": 10,
"currency": "dollar",
"expiry date": "01-12-2020",
"quantity": "1pkt"
},
{
"item name": "Salt",
"desc": "iodised salt",
"price": 5,
"currency": "dollar",
"expiry date": "01-12-2021",
"quantity": "1kg"
},
{
"item name": "Sugar",
"desc": "",
"price": 15,
"currency": "dollar",
"expiry date": "01-12-2021",
"quantity": "1kg"
},
{
"item name": "Sunflower Oil",
"desc": "oil",
"price": 35,
"currency": "dollar",
"expiry date": "01-12-2020",
"quantity": "1L"
},
{
"item name": "Rice",
"desc": "bolied rice",
"price": 100,
"currency": "dollar",
"expiry date": "01-12-2021",
"quantity": "20KG"
},
{
"item name": "Milk",
"desc": "",
"price": 5,
"currency": "dollar",
"expiry date": "15-11-2020",
"quantity": "1pkt"
}
]
const seedOrderItems2 = [
{
"item name": "Bread",
"desc": "Sweet Bread",
"price": 10,
"currency": "dollar",
"expiry date": "01-12-2020",
"quantity": "1pkt"
},
{
"item name": "Salt",
"desc": "iodised salt",
"price": 5,
"currency": "dollar",
"expiry date": "01-12-2021",
"quantity": "1kg"
}
]
const seedOrders = [{
"order id": 1,
"userr id": 3811,
"order date": "18-10-2020",
"order total": 170,
"data": seedOrderItems1
},
{
"order id": 2,
"userr id": 3812,
"order date": "28-10-2020",
"order total": 15,
"data": seedOrderItems2
}]
Order.remove()
Order.insertMany(seedOrders)
.then(res => {
console.log('Loading the orders');
console.log(res)
})
.catch(e => {
console.log(e)
}) |
# ubuntu 环境下 的 ROS 工程中 设计绑定设备的串口号
1. 确保设备已经连接到计算机上,并且确定设备文件路径,例如 /dev/ttyUSB0
```shell
$ ls /dev
```
```shell
# Intel D435i 相机串口
$ lsusb
Bus 001 Device 006: ID 8086:0b3a Intel Corp. Intel(R) RealSense(TM) Depth Camera 435i
```
2. 创建规则文件,例如 htc-robot-device.rules
3. 在规则文件中添加内容
模版
KERNEL=="ttyUSB*", ATTRS{idVendor}=="<YOUR_VENDOR_ID>", ATTRS{idProduct}=="<YOUR_PRODUCT_ID>", SYMLINK+="ttyACM%n", OWNER="<YOUR_USERNAME>"
参数说明
KERNEL=="ttyUSB*": 指定设备的内核名称以匹配所有 ttyUSB 开头的串口设备
ATTRS{idVendor}=="8086": 指定设备的供应商 ID 为"8086",用于唯一标识设备的制造商
ATTRS{idProduct}=="0b3a": 指定设备的产品 ID 为"0b3a",用于唯一标识设备的产品类型
ATTRS{serial}=="0001": 指定设备的序列号为"0001",用于唯一标识设备的序列号
MODE:="0777": 设置设备文件权限为 0777,允许任何用户对设备进行读写操作
GROUP:="dialout": 将设备文件的所有权组设置为"dialout",使"dialout"组的用户具有对设备的访问权限
SYMLINK+="htc_camera": 创建一个名为"htc_camera"的符号链接,指向与匹配的设备文件相关联
\> /etc/udev/rules.d/htc-robot-device.rules.rules: 将规则写入/etc/udev/rules.d/目录下的 htc-robot-device.rules 文件中。
```shell
# 示例&解析
KERNEL=="ttyUSB*", ATTRS{idVendor}=="8086", ATTRS{idProduct}=="0b3a", SYMLINK+="intel_d435i"
KERNEL=="ttyUSB*", ATTRS{idVendor}=="0e0f", ATTRS{idProduct}=="0003", ATTRS{serial}=="0003", MODE:="0777", GROUP:="dialout", SYMLINK+="imu"
```
```shell
service udev reload
sleep 2
service udev restart
``` |
import 'package:autoagro_firebase/language/locale.dart';
import 'package:autoagro_firebase/provider/auth_provider.dart';
// import 'package:autoagro_firebase/screen/login/login_page.dart';
import 'package:autoagro_firebase/screen/login/options_page.dart';
import 'package:autoagro_firebase/screen/login/splash_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'firebase_options.dart';
import 'screen/diseaseDetection/disease_detection.dart';
import 'screen/iotPage/iot_page.dart';
import 'screen/login/get_started.dart';
// import 'screen/login/otp.dart';
import 'screen/login/phone.dart';
import 'screen/login/reg_page.dart';
import 'screen/login/welcome_screen.dart';
import 'screen/toolRenting/tool_renting.dart';
import 'screen/weather/weather_page.dart';
import 'widgets/home_appbar_navbar.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => AuthProvider()),
],
child: GetMaterialApp(
translations: LocaleStrings(),
locale: Locale('en', 'US'),
debugShowCheckedModeBanner: false,
home: SplashScreen(),
routes: {
"/welcome": (context) => WelcomeScreen(),
"/login": (context) => PhoneReg(),
"/getStared": (context) => GetStarted(),
"/options": (context) => OptionPage(),
// "/otp" :(context) => Otp(verificationId: verificationId),
"/register": (context) => RegisterPage(),
"/home": (context) => HomePage(),
"/disease": (context) => DiseaseDetection(),
"/iot": (context) => IoTPage(),
"/toolRenting": (context) => ToolRentingPage(),
"/weather": (context) => WeatherPage(),
},
),
);
}
} |
import React from "react";
import { GlobalProvider } from "../../context/GlobalProvider";
import Item from "../Item/Item";
const ItemList = ({ products }) => {
const { buscar } = GlobalProvider()
let arr = [];
if (buscar.length > 0) {
if (products.length > 0) {
let busqueda = buscar.toLowerCase()
for (const product of products) {
let nombre = product.title.toLowerCase()
if (nombre.indexOf(busqueda) !== -1) {
arr.push(product)
}
}
}
products = arr
}
return (
<div style={{ display: "flex", flexFlow: 'row wrap', justifyContent: 'space-evenly', marginBottom: '50px' }}>
{products.length > 0 ?
products.map((item, index) => (
<Item
key={index}
id={item.id}
nameItem={item.title}
img={
item.images
}
price={item.price}
></Item>
)) : (
<div style={{
margin: '20%',
display: 'flex',
width: ' 20%',
border: '1px solid rgb(214, 147, 58)',
borderRadius: '10px',
height: '40%',
backgroundColor: 'white',
padding: '10px',
}}>
<h3>No hay productos</h3>
</div>
)
}
</div >
);
};
export default ItemList; |
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import { computed, onMounted, ref, watch } from 'vue'
import { QFile } from 'quasar'
import CollectionName from 'file-uploader/enums/collection-name'
import { useFileUploadStore } from 'file-uploader/stores/file-upload-store'
import QFileParams from 'src/interfaces/quasar/q-file-params'
import FileUploadInfoInterface from 'file-uploader/interfaces/file-upload-info-interface'
import BaseModelInterface from 'src/interfaces/models/base-model-interface'
import ModelWithFilesInterface from 'src/interfaces/models/model-with-files-interface'
import FileStatus from 'file-uploader/enums/file-status'
import ApiFileInterface from 'src/interfaces/Api/file-interface'
import ImagesUrl from 'src/enums/images-url'
interface Props {
modelValue?: number[]
modelData?: BaseModelInterface & ModelWithFilesInterface
isReady: boolean
label: string
fileUploaderOptions?: QFileParams
}
const props = defineProps<Props>()
const emit = defineEmits<{
(e: 'update:modelValue', value: number[]): void
(e: 'update:isReady', value: boolean): void
}>()
const fileUploadStore = useFileUploadStore()
const fileInput = ref<InstanceType<typeof QFile>>()
onMounted(() => {
const fileIds = (props.modelData?.files || []).map(({ id }) => id)
emit('update:modelValue', fileIds)
})
const uploadFiles = ref<FileUploadInfoInterface[]>([])
const _isShowReadyFiles = ref(false)
watch(
uploadFiles,
() => {
const ids: number[] = []
let ready = true
uploadFiles.value.forEach((uploadFile) => {
if (!uploadFile.isFinishedUpload) {
ready = false
}
if (!uploadFile.id) {
return
}
if (props.modelValue?.includes(uploadFile.id)) {
return
}
ids.push(uploadFile.id)
})
if (ids.length > 0) {
const newValue = [...(props.modelValue || [])]
newValue.push(...ids)
emit('update:modelValue', newValue)
}
emit('update:isReady', ready)
},
{ deep: true }
)
const hasUploadFiles = computed(() => uploadFiles.value.length > 0)
const hasReadyFiles = computed(() => readyFiles.value.length > 0)
const isShowReadyFiles = computed(() => _isShowReadyFiles.value && hasReadyFiles.value)
const readyFiles = computed(() => {
return (props.modelData?.files || []).sort((a, b) => {
if (a.type?.indexOf('image/') === 0 && b.type?.indexOf('image/') !== 0) {
return -1
} else if (a.type?.indexOf('image/') !== 0 && b.type?.indexOf('image/') === 0) {
return 1
} else {
return 0
}
})
})
const readyFileIsDeleted = computed(
() => (file: ApiFileInterface) => !props.modelValue?.includes(file.id)
)
const onChooseFiles = (files: File[]) => {
files.forEach((file) => {
let collectionName
if (/^video/gi.test(file.type)) {
collectionName = CollectionName.VIDEO
} else if (/^image/gi.test(file.type)) {
collectionName = CollectionName.IMAGE
} else {
collectionName = CollectionName.FILE
}
if (collectionName) {
const uploadFile = fileUploadStore.addFileToUploadQueue(file, collectionName)
uploadFiles.value.push(uploadFile)
}
})
fileUploadStore.startUpload()
}
const getReadyFileImageSrc = computed(() => (file: ApiFileInterface) => {
let url: string | undefined
if (file.type?.indexOf('image/') === 0 && file.status === FileStatus.FINISHED) {
url = file.url
}
return url || ImagesUrl.EMPTY_IMAGE
})
const deleteFile = (file: ApiFileInterface) => {
const newValue = (props.modelValue || []).filter((id) => id !== file.id)
emit('update:modelValue', newValue)
}
const rollbackFile = (file: ApiFileInterface) => {
const newValue = props.modelValue || []
if (newValue.includes(file.id)) {
return
}
newValue.push(file.id)
emit('update:modelValue', newValue)
}
const openChooseFileDialog = () => {
;(fileInput.value?.$el as HTMLInputElement).click()
}
const { t } = useI18n()
</script>
<template>
<q-card>
<q-card-section class="row justify-between">
<div class="text-h6">{{ label }}</div>
<div class="row items-center justify-between tw-gap-8px tw-w-full md:tw-w-max">
<q-btn
v-if="readyFiles.length > 0"
color="primary"
no-caps
unelevated
flat
class="tw-px-0 md: tw-px-12px"
@click="_isShowReadyFiles = !_isShowReadyFiles"
>
<span v-if="isShowReadyFiles">
{{ t('models.base.form.fileUploader.hideReadyFiles') }}
</span>
<span v-else>{{ t('models.base.form.fileUploader.showReadyFiles') }}</span>
</q-btn>
<q-btn color="primary" no-caps unelevated @click="openChooseFileDialog">
{{ t('models.base.add') }}
</q-btn>
</div>
</q-card-section>
<q-separator v-if="isShowReadyFiles || hasUploadFiles" />
<q-card-section v-if="hasUploadFiles">
<q-linear-progress
v-for="uploadFile in uploadFiles"
:key="uploadFile.file.name"
:value="uploadFile.progress / 100"
color="primary"
class="q-mt-sm"
size="25px"
>
<div class="absolute-full flex flex-center">
<q-badge color="primary" :label="`${uploadFile.progress}% - ${uploadFile.file.name}`" />
</div>
</q-linear-progress>
</q-card-section>
<q-card-section v-if="isShowReadyFiles" class="tw-grid tw-gap-12px files-container">
<q-card
v-for="readyFile in readyFiles"
:key="`file_${readyFile.id}`"
class="tw-w-full tw-max-h-250 md:tw-max-h-300px tw-flex tw-flex-col"
>
<q-img :src="getReadyFileImageSrc(readyFile)" class="tw-w-full tw-flex-shrink-1">
<div v-if="readyFileIsDeleted(readyFile)" class="absolute-top">
<div class="text-h6 text-red text-center">
{{ t('models.base.form.fileUploader.fileOnDeleting') }}
</div>
</div>
<div class="absolute-bottom">
<div v-if="readyFile.status !== FileStatus.FINISHED" class="text-h6">
{{ t(`fileUploaderModule.enums.fileStatuses.${readyFile.status}`) }}
</div>
<div class="text-subtitle1 tw-line-clamp-1">{{ readyFile.original_filename }}</div>
</div>
</q-img>
<q-card-actions class="tw-grow">
<q-btn
v-if="!readyFileIsDeleted(readyFile)"
flat
class="tw-w-full"
@click="deleteFile(readyFile)"
>
{{ t('models.base.form.fileUploader.delete') }}
</q-btn>
<q-btn v-else flat class="tw-w-full" @click="rollbackFile(readyFile)">
{{ t('models.base.form.fileUploader.rollback') }}
</q-btn>
</q-card-actions>
</q-card>
</q-card-section>
<q-file
ref="fileInput"
v-bind="fileUploaderOptions"
class="hidden"
@update:model-value="onChooseFiles"
/>
</q-card>
</template>
<style lang="scss" scoped>
.files-container {
grid-template-columns: repeat(1, minmax(0, 1fr));
@media (min-width: 768px) {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
@media (min-width: 1024px) {
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
}
}
</style> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.wrap{
border: 1px solid #111;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="src/react.js"></script>
<script src="src/react-dom.js"></script>
<!-- 解析jsx语法 -->
<script src="src/browser.min.js"></script>
<script type="text/babel">
var container = document.getElementById('container');
//refenrence 引用
var MyComponent = React.createClass({
handleClick: function() {
//真实的DOM元素
var oTextInput = this.refs.myTextInput;
var button = this.refs.button;
button.style.background = 'blue';
oTextInput.focus();
oTextInput.style.background = 'red';
},
render: function() {
return (
<div>
<input type="text" ref="myTextInput" />
<input ref="button" type="button" value="Focus the text input" onClick={this.handleClick} />
</div>
);
}
});
ReactDOM.render(
<MyComponent />,
container
);
</script>
</body>
</html> |
public class GenshinImpact {
public String nama;
public int level;
public int adventureRank;
public boolean isAlive; // tambahan variabel boolean
public GenshinImpact(){
}
public GenshinImpact(String nama, int level, int adventureRank) {
this.nama = nama;
this.level = level;
this.adventureRank = adventureRank;
this.isAlive = true; // set awal nilai isAlive menjadi true
}
public void tampilkanSpek() {
System.out.println("Nama: " + nama);
System.out.println("Level: " + level);
System.out.println("Adventure Rank: " + adventureRank);
System.out.println("Status: " + (isAlive ? "hidup" : "mati")); // menampilkan status karakter
System.out.println();
}
public void naikLevel() {
level++;
System.out.println("Level " + nama + " naik menjadi " + level);
}
public void battle(int damage) {
System.out.println(nama + " menerima " + damage + " damage");
if (damage >= 100) {
isAlive = false; // set nilai isAlive menjadi false jika damage >= 100
System.out.println(nama + " mati dalam pertarungan");
} else {
System.out.println(nama + " masih hidup");
}
}
public static void main(String[] args) {
GenshinImpact karakter1 = new GenshinImpact("Aether", 20, 30);
GenshinImpact karakter2 = new GenshinImpact("Lumine", 20, 30);
//GenshinImpact karakter3 = new GenshinImpact();
karakter1.tampilkanSpek();
karakter2.tampilkanSpek();
karakter1.naikLevel();
karakter2.battle(20);
karakter2.battle(80);
karakter2.battle(120);
karakter1.tampilkanSpek();
karakter2.tampilkanSpek();
}
} |
package classes;
import exception.MovimentoInvalidoException;
public class Robo {
protected int x, y;
protected String color;
protected int qtdMov = 0;
protected int qtdMovInv = 0;
protected int nextMove;
public Robo(String color){
this.color = color;
this.x = 4;
this.y = 0;
this.nextMove = 0;
}
public void mover(String movement) throws MovimentoInvalidoException{
if(movement.equals("up")){
if(x - 1 < 0) throw new MovimentoInvalidoException();
x--;
}
else if(movement.equals("down")){
if(x + 1 >= 5) throw new MovimentoInvalidoException();
x++;
}
else if(movement.equals("right")){
if(y + 1 >= 5) throw new MovimentoInvalidoException();
y++;
}
else if(movement.equals("left")){
if(y - 1 < 0) throw new MovimentoInvalidoException();
y--;
}
}
public void mover(int movement) throws MovimentoInvalidoException{
if(movement == 1){
if(this.x - 1 < 0){
qtdMovInv++;
throw new MovimentoInvalidoException();
}
this.x--;
qtdMov++;
}
else if(movement == 2){
if(this.x + 1 >= 5){
qtdMovInv++;
throw new MovimentoInvalidoException();
}
this.x++;
qtdMov++;
}
else if(movement == 3){
if(this.y + 1 >= 5){
qtdMovInv++;
throw new MovimentoInvalidoException();
}
this.y++;
qtdMov++;
}
else if(movement == 4){
if(this.y - 1 < 0){
qtdMovInv++;
throw new MovimentoInvalidoException();
}
this.y--;
qtdMov++;
}
}
public boolean AlimentoEncontrado(int alimentoX, int alimentoY){
if(this.x == alimentoX && this.y == alimentoY){
return true;
}
return false;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getNextMove() {
return nextMove;
}
public int getQtdMov() {
return qtdMov;
}
public int getQtdMovInv() {
return qtdMovInv;
}
} |
import './style.css';
import * as d3 from 'd3';
import { Continents, Data, DataItem, YearData } from './types/Data';
import fetchD3Data from './fetchD3Data';
import d3Tip from 'd3-tip';
let interval: any;
const margin = { top: 10, right: 10, bottom: 150, left: 100 };
const height = 400 - margin.top - margin.bottom;
const width = 600 - margin.left - margin.right;
const canvas = d3.select('#chart-area')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom);
const continentColor = d3.scaleOrdinal(d3.schemeSet1)
const gLobalGroup = canvas.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`)
// @ts-ignore
const tip = d3Tip()
.attr('class', 'd3-tip')
.html((d: MouseEvent) => {
// @ts-ignore
const data = d.target.__data__ as DataItem;
let text = `<strong>Country:</strong> <span style='color:red'>${data.country}</span><br>`;
text += `<strong>Continent:</strong> <span style='color:red;text-transform:capitalize'>${data.continent}</span><br>`;
text += `<strong>Life Expectancy:</strong> <span style='color:red'>${d3.format(".2f")(data.life_exp)}</span><br>`;
text += `<strong>GDP Per Capita:</strong> <span style='color:red'>${d3.format("$,.0f")(data.income)}</span><br>`;
text += `<strong>Population:</strong> <span style='color:red'>${d3.format(",.0f")(data.population)}</span><br>`;
return text;
})
gLobalGroup.call(tip);
const continents = Object.values(Continents);
const legend = gLobalGroup.append('g')
.attr('transform', `translate(${width - 10}, ${height - 125})`);
continents.forEach((continent, i) => {
const legendRow = legend.append('g')
.attr('transform', `translate(0, ${i * 20})`);
legendRow.append('rect')
.attr('width', 10)
.attr('height', 10)
.attr('fill', continentColor(continent));
legendRow.append('text')
.attr('x', -10)
.attr('y', 10)
.attr('text-anchor', 'end')
.style('text-transform', 'capitalize')
.text(continent);
});
// X label
gLobalGroup.append("text")
.attr("y", height + 50)
.attr("x", width / 2)
.attr("font-size", "20px")
.attr("text-anchor", "middle")
.text("GDP Per Capita ($)")
gLobalGroup.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -40)
.attr("x", -170)
.attr("font-size", "20px")
.attr("text-anchor", "middle")
.text("Life Expectancy (Years)")
//time label
const timeLabel = gLobalGroup.append("text")
.attr("y", height - 10)
.attr("x", width - 40)
.attr("font-size", "40px")
.attr("opacity", "0.4")
.attr("text-anchor", "middle")
.text("1800")
const xAxisGroup = gLobalGroup.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate( 0, ' + height + ')');
const yAxisGroup = gLobalGroup.append('g')
.attr('class', 'y axis');
const data: Data = await fetchD3Data();
const minYear = d3.min(data, (d) => d.year)!;
const maxYear = d3.max(data, (d) => d.year)!;
let currentYear: number = minYear;
// @ts-ignore
$('#date-slider').slider({
max: maxYear,
min: minYear,
step: 1,
// @ts-ignore
slide: function (event: any, ui: { value: number }) {
currentYear = ui.value;
const yearData: YearData = data.find((d) => d.year === currentYear)!;
update(yearData);
}
});
const x = d3.scaleLog()
.base(10)
.range([0, width])
.domain([142, 150000])
// .paddingInner(0.3)
// .paddingOuter(0.2);
const y = d3.scaleLinear()
// .base(10)
.domain([0, 90])
.range([height, 0]);
const xAxisCall = d3.axisBottom(x)
.tickValues([400, 4000, 40000])
.tickFormat(d3.format('$'));
const yAxisCall = d3.axisLeft(y)
.ticks(10)
.tickFormat((d) => d.toString());
const area = d3.scaleLinear()
.range([25 * Math.PI, 1500 * Math.PI])
.domain([2000, 1400000000])
xAxisGroup
.call(xAxisCall)
.selectAll('text')
.attr("y", "10")
.attr("x", "-5")
.attr("text-anchor", "end")
.attr("transform", "rotate(-40)");
yAxisGroup
.attr("class", "y axis")
.call(yAxisCall);
const step = () => {
if (currentYear === maxYear) {
currentYear = currentYear;
} else {
currentYear++;
}
const yearData: YearData = data.find((d) => d.year === currentYear)!;
update(yearData)
}
document.getElementById('play-button')!.addEventListener('click', () => {
if (interval) {
clearInterval(interval);
interval = null;
document.getElementById('play-button')!.innerText = 'Play';
} else {
interval = setInterval(step, 150);
document.getElementById('play-button')!.innerText = 'Pause';
}
});
document.getElementById('reset-button')!.addEventListener('click', () => {
currentYear = minYear;
clearInterval(interval);
interval = null;
const yearData: YearData = data.find((d) => d.year === currentYear)!;
update(yearData)
document.getElementById('play-button')!.innerText = 'Play';
});
const yearData: YearData = data.find((d) => d.year === minYear)!;
update(yearData);
document.getElementById('continent-select')!.addEventListener('change', () => {
const yearData: YearData = data.find((d) => d.year === currentYear)!;
update(yearData);
});
function update(data: YearData) {
const currentYear: number = data.year;
const countries: DataItem[] = data.countries;
const continent = document.getElementById('continent-select') as HTMLSelectElement;
const filteredCountries = countries.filter((d) => continent.value === 'all' || d.continent === continent.value);
const transition = d3.transition().duration(100);
/**
* D3 Update Pattern
*/
// JOIN new data with old elements.
const circles = gLobalGroup.selectAll('circle')
.data(filteredCountries, (d: any) => d.country);
// EXIT old elements not present in new data.
circles.exit().remove();
// ENTER new elements present in new data...
circles.enter().append("circle")
.attr("fill", (d) => continentColor(d.continent))
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
.merge(circles as any)
.transition(transition)
.attr("r", (d) => Math.sqrt(area(d.population) / Math.PI))
.attr("cx", (d) => x(d.income))
.attr("cy", (d) => y(d.life_exp));
timeLabel.text(currentYear.toString());
$('#year')[0].innerText = currentYear.toString();
// @ts-ignore
$('#date-slider').slider('value', currentYear);
} |
/****************************************************************************
** @license
** This demo file is part of yFiles for HTML 2.6.0.4.
** Copyright (c) 2000-2024 by yWorks GmbH, Vor dem Kreuzberg 28,
** 72070 Tuebingen, Germany. All rights reserved.
**
** yFiles demo files exhibit yFiles for HTML functionalities. Any redistribution
** of demo files in source code or binary form, with or without
** modification, is not permitted.
**
** Owners of a valid software license for a yFiles for HTML version that this
** demo is shipped with are allowed to use the demo source code as basis
** for their own yFiles for HTML powered applications. Use of such programs is
** governed by the rights and conditions as set out in the yFiles for HTML
** license agreement.
**
** THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESS OR IMPLIED
** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
** NO EVENT SHALL yWorks BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***************************************************************************/
import { IGraph } from 'yfiles'
import { NodeData, type SerializableNodeData } from './NodeData'
import { EdgeData, type SerializableEdgeData } from './EdgeData'
export type SerializableGraphData = {
nodes: Array<SerializableNodeData>
edges: Array<SerializableEdgeData>
}
type GraphDataOptions = {
nodeDataItems: Array<NodeData>
edgeDataItems: Array<EdgeData>
}
/**
* A simple, minimal data structure that can be used for exporting Graph data
* and re-creating the Graph.
*/
export class GraphData {
private nodeDataItems: GraphDataOptions['nodeDataItems']
private edgeDataItems: GraphDataOptions['edgeDataItems']
/**
* Creates GraphData from an actual node. We exclude the validator function,
* if present as it cannot be serialized, and it will be automatically set
* on node re-creation anyway.
*/
static fromGraph(graph: IGraph): GraphData {
const nodes = graph.nodes.toArray()
const edges = graph.edges
.toArray()
.map(
edge =>
[
edge,
nodes.findIndex(node => node === edge.sourceNode),
nodes.findIndex(node => node === edge.targetNode)
] as const
)
const nodeDataItems = nodes.map(NodeData.fromGraphItem)
const edgeDataItems = edges.map(edge => EdgeData.fromGraphItem(...edge))
return new GraphData({ nodeDataItems, edgeDataItems })
}
/**
* Converts an arbitrary piece of data to GraphData after validation.
*/
static fromJSONData(data: unknown): GraphData {
this.validate(data)
const nodeDataItems = data.nodes.map(NodeData.fromJSONData)
const edgeDataItems = data.edges.map(EdgeData.fromJSONData)
return new GraphData({ nodeDataItems, edgeDataItems })
}
/**
* Checks if an arbitrary piece of data (as it comes from a JSON source)
* conforms to the format required by GraphData.
*/
static validate(data: unknown): asserts data is SerializableGraphData {
if (data) {
return
}
throw new Error('Malformed graph data')
}
constructor({ nodeDataItems, edgeDataItems }: GraphDataOptions) {
this.nodeDataItems = nodeDataItems
this.edgeDataItems = edgeDataItems
}
/**
* Applies data to the actual Graph after clearing it.
*/
applyToGraph(graph: IGraph): void {
graph.clear()
const nodes = this.nodeDataItems.map(n => n.createGraphItem(graph))
this.edgeDataItems.forEach(e => e.createGraphItem(graph, ...e.matchPorts(nodes)))
}
/**
* Converts GraphData to a JSON string.
*/
toJSON(): string {
const data: SerializableGraphData = {
nodes: this.nodeDataItems.map(n => n.toJSONData()),
edges: this.edgeDataItems.map(e => e.toJSONData())
}
return JSON.stringify(data, null, 2)
}
} |
using AdaptiveCards;
using AriBotV4.AppSettings;
using AriBotV4.Enums;
using AriBotV4.Models;
using AriBotV4.Models.MyCarte;
using AriBotV4.Services;
using Azure.AI.TextAnalytics;
using LuisEntityHelpers;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.AI.Luis;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace AriBotV4.Common
{
public class Utility
{
// Generate random messages
public static string GenerateRandomMessages(string[] messages)
{
try
{
Random rnd = new Random();
int r = rnd.Next(messages.Count());
return ((string)messages[r]);
}
catch (Exception ex) { return string.Empty; }
}
// Get https,http,www url
public static string GetUrlFromString(string rawString)
{
try
{
var linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
foreach (Match match in linkParser.Matches(rawString))
{
return match.Value;
}
return string.Empty;
}
catch (Exception ex)
{
return string.Empty;
}
}
// valid user inout
public static async Task<bool> ValidateUserInput(PromptValidatorContext<string> promptContext, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(promptContext.Recognized.Value))
{
return false;
}
else
{
return true;
}
}
// Get keyword from sentence
public static async Task<List<string>> KeyPhraseExtractionExample(TextAnalyticsClient client, string query)
{
var response = await client.ExtractKeyPhrasesAsync(query);
List<string> keywords = new List<string>();
// Printing key phrases
foreach (string keyphrase in response.Value)
{
keywords.Add(keyphrase);
}
if(keywords.Count == 0)
{
keywords.Add(query);
}
return await Task.Run(() => keywords);
}
// Get project settings
public static string GetProjectSettings(int projectCode)
{
string projectSettings = string.Empty;
if (projectCode == 0)
projectSettings = "TaskSpurToggleSettings";
else if (projectCode == 1)
projectSettings = "MyCarteToggleSettings";
else if (projectCode == 2)
projectSettings = "IntellegoToggleSettings";
return projectSettings;
}
// Get QnA results
public static QnAMaker GetQnaSearchResult(string query, BotStateService _botStateService)
{
try
{
var qnaMakerHost = _botStateService._qnaSettings.QnAMakerHost;
var qnaMakerKBId = _botStateService._qnaSettings.QnAMakerId;
var qnaMakerEndPointKey = _botStateService._qnaSettings.QnAMakerEndPointKey;
var qnaMakerFormatJson = _botStateService._qnaSettings.QnAMakerFormatJson;
var client = new RestClient(qnaMakerHost + "/knowledgebases/" + qnaMakerKBId + "/generateAnswer");
var qnaRequest = new RestRequest(Method.POST);
qnaRequest.AddHeader("authorization", "EndpointKey " + qnaMakerEndPointKey);
qnaRequest.AddParameter(qnaMakerFormatJson, "{\"question\": \"" + query + "\"}", ParameterType.RequestBody);
var qnaResponse = client.Execute(qnaRequest);
var qnaSearchList = JsonConvert.DeserializeObject<QnAMaker>(qnaResponse.Content);
if (qnaSearchList.Answers.Count > 0)
{
return qnaSearchList;
// var qnaFirstAnswer = qnaSearchList.Answers[0].Answer;
//// var qnaScore = qnaSearchList.Answers[0].Score;
// //if (!qnaFirstAnswer.ToLower().Equals(qnaMakerAnswerNotFound) && qnaScore >= _botStateService._qnaSettings.ScorePercentage)
// return qnaSearchList;
// else
// {
// qnaSearchList.Answers[0].Answer = qnaMakerAnswerNotFound;
// qnaSearchList.Answers[0].Source = "Editorial";
// return qnaSearchList;
// }
}
return null;
}
catch
{
return null;
}
}
// Get Common QnA results
public static QnAMaker GetCommonQnaSearchResult(string query, QnASettings _qnaSettings)
{
try
{
var qnaMakerHost = _qnaSettings.QnAMakerHost;
var qnaMakerKBId = _qnaSettings.QnAMakerId;
var qnaMakerEndPointKey = _qnaSettings.QnAMakerEndPointKey;
var qnaMakerFormatJson = _qnaSettings.QnAMakerFormatJson;
var client = new RestClient(qnaMakerHost + "/knowledgebases/" + qnaMakerKBId + "/generateAnswer");
var qnaRequest = new RestRequest(Method.POST);
qnaRequest.AddHeader("authorization", "EndpointKey " + qnaMakerEndPointKey);
qnaRequest.AddParameter(qnaMakerFormatJson, "{\"question\": \"" + query + "\"}", ParameterType.RequestBody);
var qnaResponse = client.Execute(qnaRequest);
var qnaSearchList = JsonConvert.DeserializeObject<QnAMaker>(qnaResponse.Content);
if (qnaSearchList.Answers.Count > 0)
{
return qnaSearchList;
// var qnaFirstAnswer = qnaSearchList.Answers[0].Answer;
//// var qnaScore = qnaSearchList.Answers[0].Score;
// //if (!qnaFirstAnswer.ToLower().Equals(qnaMakerAnswerNotFound) && qnaScore >= _botStateService._qnaSettings.ScorePercentage)
// return qnaSearchList;
// else
// {
// qnaSearchList.Answers[0].Answer = qnaMakerAnswerNotFound;
// qnaSearchList.Answers[0].Source = "Editorial";
// return qnaSearchList;
// }
}
return null;
}
catch
{
return null;
}
}
// Get Common Luis results
public static async Task<LuisHelper> GetCommonLuisSearchResult(string query, LuisSettings _luisSettings, WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
try
{
var luisAppId = _luisSettings.LuisAppId;
var luisAPIKey = _luisSettings.LuisAPIKey;
var luisAPIHostName = _luisSettings.LuisAPIHostName;
var luisRecognizer = new LuisRecognizer(new LuisApplication(
luisAppId,
luisAPIKey,
$"https://{luisAPIHostName}.api.cognitive.microsoft.com"),
new LuisPredictionOptions { IncludeAllIntents = true, IncludeInstanceData = true },
true);
RecognizerResult recognizerResult = new RecognizerResult();
LuisHelper luisResponse = new LuisHelper();
// First, we use the dispatch model to determine which cognitive service (LUIS or Qna) to use
try
{
recognizerResult = await luisRecognizer.RecognizeAsync(stepContext.Context, cancellationToken);
var jsonObj = JsonConvert.SerializeObject(recognizerResult);
luisResponse = JsonConvert.DeserializeObject<LuisHelper>(jsonObj);
//Convert
}
catch (Exception ex)
{
}
//stepContext.EndDialogAsync(null, cancellationToken);
//// Top intent tell us which cognitive service to use
//LuisModel.Intent topIntent = new LuisModel.Intent();
//if (luisResponse != null)
// topIntent = luisResponse.TopIntent().intent;
return luisResponse;
}
catch
{
return null;
}
}
public static SearchType GetSearchType(LuisModel luisResponse, QnAMaker qnAMaker)
{
if ((qnAMaker != null && qnAMaker.Answers[0].Score == 100) || (qnAMaker != null && qnAMaker.Answers[0].Score >= 95 && qnAMaker.Answers[0].Score > luisResponse.TopIntent().score))
return SearchType.QnA;
else if ((luisResponse != null && luisResponse.TopIntent().intent != LuisModel.Intent.None && luisResponse.TopIntent().score == 100) || (luisResponse != null && luisResponse.TopIntent().intent != LuisModel.Intent.None && luisResponse.TopIntent().score >= 95 && qnAMaker.Answers[0].Score < luisResponse.TopIntent().score))
return SearchType.LUIS;
else
return SearchType.General;
}
// Validate task name
public static async Task<bool> ValidateTaskName(PromptValidatorContext<string> promptContext, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(promptContext.Recognized.Value))
{
return false;
}
else
{
return true;
}
}
// Validate start time and end time
public static Attachment GetSelectedCard(string answer)
{
int length = answer.Split(';').Length;
switch (length)
{
case 4: return GetHeroCard(answer);
case 6: return GetVideoCard(answer);
default: return GetHeroCard(answer);
}
}
public static Attachment GetHeroCard(string answer)
{
string[] qnaAnswerData = answer.Split(';');
string title = qnaAnswerData[0].Trim();
string description = qnaAnswerData[1].Trim();
string url = qnaAnswerData[2].Trim();
string imageUrls = qnaAnswerData[3].Trim();
string[] imageUrlList;
var cardImages = new List<CardImage>();
if (imageUrls.Contains(','))
{
imageUrlList = imageUrls.Split(',');
foreach (var imageUrl in imageUrlList)
{
if (!String.IsNullOrEmpty(imageUrl))
{
cardImages.Add(new CardImage(url = imageUrl));
}
}
}
else
{
cardImages.Add(new CardImage(url = imageUrls));
}
HeroCard hCard = new HeroCard
{
Title = title,
Subtitle = description,
};
hCard.Buttons = new List<CardAction>
{
new CardAction(ActionTypes.OpenUrl, "Learn More", value:url)
};
hCard.Images = cardImages;
return hCard.ToAttachment();
}
public static Attachment GetVideoCard(string answer)
{
string[] qnaAnswerData = answer.Split(';');
string title = qnaAnswerData[0].Trim();
string subTitle = qnaAnswerData[1].Trim();
string description = qnaAnswerData[2].Trim();
string thumbImageUrl = qnaAnswerData[3].Trim();
string mediaUrl = qnaAnswerData[4].Trim();
string url = qnaAnswerData[5].Trim();
VideoCard vCard = new VideoCard
{
Title = title,
Subtitle = subTitle,
Text = description,
};
vCard.Image = new ThumbnailUrl
{
Url = thumbImageUrl
};
vCard.Media = new List<MediaUrl>
{
new MediaUrl()
{
Url = mediaUrl
}
};
vCard.Buttons = new List<CardAction>
{
new CardAction()
{
Title = "Learn More",
Type = ActionTypes.OpenUrl,
Value = url
}
};
return vCard.ToAttachment();
}
public static Attachment CreateAdapativecard()
{
AdaptiveCard card = new AdaptiveCard();
// Specify speech for the card.
card.Speak = "I'm AVA bot";
// Body content
card.Body.Add(new AdaptiveImage()
{
Url = new Uri("https://media.istockphoto.com/vectors/chat-bot-using-laptop-computer-robot-virtual-assistance-of-website-or-vector-id1177016383?k=20&m=1177016383&s=612x612&w=0&h=BM-W0s-Snd16CrVOkY9V4eccAfZilpx4NZx-e19Wsvg="),
Size = AdaptiveImageSize.Small,
Style = AdaptiveImageStyle.Person,
AltText = "I'm at LIG"
});
// Add text to the card.
card.Body.Add(new AdaptiveTextBlock()
{
Text = ".Net (C#) Developer",
Size = AdaptiveTextSize.Large,
Weight = AdaptiveTextWeight.Bolder
});
// Add text to the card.
card.Body.Add(new AdaptiveTextBlock()
{
Text = "ia@lig.com"
});
// Add text to the card.
card.Body.Add(new AdaptiveTextBlock()
{
Text = "923xxxxxx761"
});
// Create the attachment with adapative card.
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = card
};
return attachment;
}
}
} |
import { Matrix4, Vector2 } from "three";
import { MaterialBase } from "../MaterialBase"
import { MeshBVHUniformStruct, UIntVertexAttributeTexture } from "three-mesh-bvh";
// utils
import { renderStructsGLSL } from './glsl/renderStructs.glsl'
import { cameraUtilsGLSL } from './glsl/cameraUtils.glsl'
import { traceSceneGLSL } from "./glsl/traceScene.glsl";
import { getSurfaceRecordGLSL } from './glsl/getSurfaceRecord.glsl';
import { directLightContributionGLSL } from "./glsl/directLightContribution.glsl";
// uniform
import { EquirectHdrInfoUniform } from '../../uniforms/EquirectHdrInfoUniform';
import { MaterialsTexture } from '../../uniforms/MaterialsTexture.js';
import { PhysicalCameraUniform } from "../../uniforms/PhysicalCameraUniform";
import { AttributesTextureArray } from "../../uniforms/AttributesTextureArray";
// struct
import { equirectStructGLSL } from '../../shader/struct/equirectStruct.glsl';
import { lightsStructGLSL } from '../../shader/struct/lightsStruct.glsl'
import { materialStructGLSL } from '../../shader/struct/materialStruct.glsl';
import { bsdfSamplingGLSL } from '../../shader/bsdf/bsdfSampling.glsl';
import { pcgGLSL } from "../../shader/rand/pcg.glsl";
import { sobolCommonGLSL, sobolSamplingGLSL } from "../../shader/rand/sobol.glsl";
// sampling
import { equirectSamplingGLSL } from '../../shader/sampling/equirectSampling.glsl';
import { lightSamplingGLSL } from '../../shader/sampling/lightSampling.glsl';
import { shapeSamplingGLSL } from '../../shader/sampling/shapeSampling.glsl';
// common
import { intersectShapesGLSL } from '../../shader/common/intersectShapes.glsl';
import { mathGLSL } from '../../shader/common/math.glsl';
import { utilsGLSL } from '../../shader/common/utils.glsl';
import { fresnelGLSL } from '../../shader/common/fresnel.glsl';
import { arraySamplerTexelFetchGLSL } from '../../shader/common/arraySamplerTexelFetch.glsl';
export class PhysicalPathTracingMaterial extends MaterialBase {
constructor(params = {}) {
super({
transparent: true,
depthWrite: false,
defines: {
FEATURE_MIS: 1, // MIS采样
FEATURE_RUSSIAN_ROULETTE: 1, // 俄罗斯轮盘
FEATURE_DOF: 1, // 背景虚化
FEATURE_BACKGROUND_MAP: 0, // 环境贴图
CAMERA_TYPE: 0, // 相机类型:0投影、1正交
},
uniforms: {
resolution: { value: new Vector2() },
bounces: { value: 10 }, // 最大弹射次数
transmissiveBounces: { value: 10 }, // 最大投射弹射次数
physicalCamera: { value: new PhysicalCameraUniform() },
bvh: { value: new MeshBVHUniformStruct() },
attributesArray: { value: new AttributesTextureArray() },
materialIndexAttribute: { value: new UIntVertexAttributeTexture() }, // 材质顶点索引
materials: { value: new MaterialsTexture() },
environmentIntensity: { value: 1.0 }, // 环境光强度
environmentRotation: { value: new Matrix4() }, // 环境贴图旋转矩阵
envMapInfo: { value: new EquirectHdrInfoUniform() }, // 环境贴图信息
opacity: { value: 0 },
},
vertexShader: `
varying vec2 vUv;
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
vUv = uv;
}
`,
fragmentShader: `
#define INFINITY 1e20
precision highp isampler2D;
precision highp usampler2D;
precision highp sampler2DArray;
#include<common>
varying vec2 vUv
// bvh
// random
${pcgGLSL}
${sobolCommonGLSL}
${sobolSamplingGLSL}
// common
${arraySamplerTexelFetchGLSL}
${fresnelGLSL}
${utilsGLSL}
${mathGLSL}
${intersectShapesGLSL}
// sampling
${lightSamplingGLSL}
${shapeSamplingGLSL}
${equirectSamplingGLSL}
${bsdfSamplingGLSL}
// struct
${lightsStructGLSL}
${equirectStructGLSL}
${materialStructGLSL}
// environment
uniform EquirectHdrInfo envMapInfo;
uniform mat4 environmentRotation;
uniform float environmentIntensity;
// light
uniform sampler2DArray iesProfiles;
uniform LightsInfo lights;
// background
uniform float backgroundBlur;
uniform float backgroundAlpha;
#if FEATURE_BACKGROUND_MAP
uniform sampler2D backgroundMap;
#endif
// camera
uniform mat4 cameraWorldMatrix;
uniform mat4 invProjectionMatrix;
// geometry
uniform sampler2DArray attributesArray;
uniform usampler2D materialIndexAttribute;
// path tracer
uniform int bounces;
uniform int transmissiveBounces;
uniform int seed;
// image
uniform vec2 resolution;
uniform float opacity;
// rotation
mat3 envRotation;
mat3 invEnvRotation;
// global
float lightsDenom;
// 采样环境贴图
vec3 sampleBackground(vec3 direction,vec2 uv){
vec3 sampleDir=normalize(direction+sampleHemisphere(direction,uv)*.5*backgroundBlur);
#if FEATURE_BACKGROUND_MAP
return sampleEquirectColor(backgroundMap,sampleDir);
#else
return environmentIntensity*sampleEquirectColor(envMapInfo.map,sampleDir);
#endif
}
${renderStructsGLSL}
${cameraUtilsGLSL}
${traceSceneGLSL}
${getSurfaceRecordGLSL}
${directLightContributionGLSL}
void main(){
// init random
rng_initialize(gl_FragCoord.xy,seed);
sobolPixelIndex=(uint(gl_FragCoord.x)<<16)|uint(gl_FragCoord.y);
sobolPathIndex=uint(seed);
// ray from camera
Ray ray=getCameraRay();
// rotate environment
envRotation=mat3(environmentRotation);
invEnvRotation=inverse(envRotation);
lightsDenom=environmentIntensity==0.&&lights.count!=0u?float(lights.count):float(lights.count+1u);
gl_FragColor=vec4(0,0,0,1);
// surface
SurfaceHit surfaceHit;
LightRecord lightRec;
ScatterRecord scatterRec;
// path tracing state
RenderState state=initRenderState();
state.transmissiveTraversals=transmissiveBounces;
// main process
for(int i=0;i<bounces;i++){
// sobolBounceIndex++;
state.depth++;
state.traversals=bounces-i;
state.firstRay=i==0&&state.transmissiveTraversals==transmissiveBounces;
// 光线求交
int hitType=traceScene(ray,bvh,lights,state.fogMaterial,surfaceHit,lightRec);
// 命中光源
if(hitType==LIGHT_HIT){
// 透射
if(state.firstRay||state.transmissiveRay){
gl_FragColor.rgb+=lightRec.emission*state.throughputColor;
}
else{
#if FEATURE_MIS
// 对于精确光源,不使用MIS
if(lightRec.type==SPOT_LIGHT_TYPE||lightRec.type==DIR_LIGHT_TYPE||lightRec.type==POINT_LIGHT_TYPE){
gl_FragColor.rgb+=lightRec.emission*state.throughputColor;
}else{
float misWeight=misHeuristic(scatterRec.pdf,lightRec.pdf/lightsDenom);
gl_FragColor.rgb+=lightRec.emission*state.throughputColor*misWeight;
}
#else
gl_FragColor.rgb+=lightRec.emission*state.throughputColor;
#endif
}
break;
}
// 没命中(命中背景)
else if(hitType==NO_HIT){
if(state.firstRay||state.transmissiveRay){
gl_FragColor.rgb+=sampleBackground(envRotation*ray.direction,sobol2(2))*state.throughputColor;
gl_FragColor.a=backgroundAlpha;
}
else{
#if FEATURE_MIS
// 获取环境的pdf
vec3 envColor;
float envPdf=sampleEquirect(envMapInfo,envRotation*ray.direction,envColor);
envPdf/=lightsDenom;
float misWeight=misHeuristic(scatterRec.pdf,envPdf);
gl_FragColor.rgb+=environmentIntensity*envColor*state.throughputColor*misWeight;
#else
gl_FragColor.rgb+=environmentIntensity*sampleEquirectColor(envMapInfo.map,envRotation*ray.direction)*state.throughputColor;
#endif
}
break;
}
// 获取交点材质
uint materialIndex=uTexelFetch1D(materialIndexAttribute,surfaceHit.faceIndices.x).r;
Material material=readMaterialInfo(materials,materialIndex);
// 哑光材质
if(material.matte&&state.firstRay){
gl_FragColor=vec4(0.);
break;
}
// 阴影射线命中不会产生阴影的材质
if(!material.castShadow&&state.isShadowRay){
ray.origin=stepRayOrigin(ray.origin,ray.direction,-surfaceHit.faceNormal,surfaceHit.dist);
continue;
}
SurfaceRecord surf;
// 透明材质,防止无限弹射
if(getSurfaceRecord(material,surfaceHit,attributesArray,state.accumulatedRoughness,surf)==SKIP_SURFACE){
i-=sign(state.transmissiveTraversals);
state.transmissiveTraversals-=sign(state.transmissiveTraversals);
ray.origin=stepRayOrigin(ray.origin,ray.direction,-surfaceHit.faceNormal,surfaceHit.dist);
continue;
}
scatterRec=bsdfSample(-ray.direction,surf);
state.isShadowRay=scatterRec.specularPdf<sobol(4);
bool isBelowSurface=!surf.volumeParticle&&dot(scatterRec.direction,surf.faceNormal)<0.;
vec3 hitPoint=stepRayOrigin(ray.origin,ray.direction,isBelowSurface?-surf.faceNormal:surf.faceNormal,surfaceHit.dist);
#if FEATURE_MIS
gl_FragColor.rgb+=directLightContribution(-ray.direction,surf,state,hitPoint);
#endif
// 随着光线反射次数增多,其贡献越小
if(!surf.volumeParticle&&!isBelowSurface){
vec3 halfVector=normalize(-ray.direction+scatterRec.direction);
state.accumulatedRoughness+=max(
sin(acosApprox(dot(halfVector,surf.normal))),
sin(acosApprox(dot(halfVector,surf.clearcoatNormal)))
);
state.transmissiveRay=false
}
// 颜色累加
gl_FragColor.rgb+=(surf.emission*state.throughputColor);
// 剪枝
if(scatterRec.pdf<=0.||!isDirectionValid(scatterRec.direction,surf.normal,surf.faceNormal)){
break;
}
// 透射
bool isTransmissiveRay=!surf.volumeParticle&&dot(scatterRec.direction,surf.faceNormal*surfaceHit.side)<0.;
if((isTransmissiveRay||isBelowSurface)&&stae.transmissiveTraversals>0){
state.transmissiveTraversals--;
i--;
}
// 颜色衰减
if(!surf.frontFace){
state.throughputColor*=transmissionAttenuation(surfaceHit.dist,surf.attenuationColor,surf.attenuationDistance);
}
// 俄罗斯轮盘赌
#if FEATURE_RUSSIAN_ROULETTE
uint minBounces=3u;
float depthProb=float(state.depth<minBounces);
float rrProb=luminance(state.throughputColor*scatterRec.color/scatterRec.pdf);
rrProb/=luminance(state.throughputColor);
rrProb=sqrt(rrProb);
rrProb=max(rrProb,depthProb);
rrProb=min(rrProb,1.);
if(sobol(8)>rrProb){
break;
}
state.throughputColor*=min(1./rrProb,20.);
#endif
// 影响颜色
state.throughputColor*=scatterRec.color/scatterRec.pdf;
// 判断颜色是否合法,(运算过程中可能出现NaN和Infinity)
if(any(isnan(state.throughputColor))||any(isinf(state.throughputColor))){
break;
}
// 下一次反射
ray.direction=scatterRec.direction;
ray.origin=hitPoint;
}
gl_FragColor.a*=opacity;
}
`
})
this.setValues(params)
}
onBeforeRender() {
// 背景虚化
this.setDefine('FEATURE_DOF', this.physicalCamera.bokehSize === 0 ? 0 : 1);
// 环境贴图
this.setDefine('FEATURE_BACKGROUND_MAP', this.backgroundMap ? 1 : 0);
}
} |
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:sachintha_uee/models/supply_model.dart';
import 'package:sachintha_uee/utils/constants.dart';
import 'package:sachintha_uee/utils/custom_states.dart';
import 'package:sachintha_uee/utils/index.dart';
import 'package:sachintha_uee/views/factory/order_view_factory.dart';
class Requests extends StatelessWidget {
const Requests({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text(
"Requests",
style: TextStyle(
color: Colors.black,
),
),
backgroundColor: Colors.grey[100],
elevation: 0,
),
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection("orders").snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
return snapshot.data == null
? const SizedBox()
: snapshot.data!.docs.isEmpty
? const Center(
child: Text("No requests"),
)
: ListView(
padding: const EdgeInsets.all(defaultPadding),
children: snapshot.data!.docs.map(
(e) {
SupplyModel supplyModel =
SupplyModel.fromDocumentSnapshot(e);
return Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
padding: const EdgeInsets.all(defaultPadding / 2),
margin: const EdgeInsets.only(bottom: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
'Request ID : ${supplyModel.id!}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 16,
),
),
),
Chip(
backgroundColor:
orderStates[supplyModel.status],
label: Text(
supplyModel.status,
style: const TextStyle(
color: Colors.white,
),
),
)
],
),
const SizedBox(
height: 4,
),
Text(
supplyModel.address,
style: const TextStyle(
fontSize: 14, color: Color(0xFF828282)),
),
const SizedBox(
height: 4,
),
MaterialButton(
color: Colors.black,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
onPressed: () {
context.navigator(
context,
OrderViewFactory(
supplyModel: supplyModel));
},
child: const Text(
"View Details",
style: TextStyle(
color: Colors.white,
),
),
)
],
),
);
},
).toList(),
);
},
),
);
}
} |
use crate::Bytes;
/// # Invariant
///
/// * `self.ptr` is always a valid pointer to a slice of bytes of len at least
/// `self.len`.
/// * `self.pos < self.len`
pub struct BytesIter {
ptr: *const u8,
len: usize,
pos: usize,
_b: Bytes,
}
impl BytesIter {
#[inline]
fn new(bytes: Bytes) -> BytesIter {
// SAFETY + INVARIANT:
// The `bytes` variable is stored in `self` to avoid the memory free.
let ptr = unsafe { bytes.ptr() };
let len = bytes.len();
BytesIter {
ptr,
len,
pos: 0,
_b: bytes,
}
}
/// Return the current position in the bytes buffer.
#[inline]
pub fn pos(&self) -> usize {
self.pos
}
/// The remaining len in the iterator.
#[inline]
pub fn len(&self) -> usize {
self.len - self.pos
}
/// Check if the iterator is empty or not.
#[inline]
pub fn is_empty(&self) -> bool {
self.pos >= self.len
}
/// Peek the byte at the current position.
///
/// # Example
///
/// ```
/// use bytes::Bytes;
///
/// let b = Bytes::from_static(b"a byte slice");
/// let iter = b.into_iter();
///
/// assert_eq!(iter.peek(), Some(b'a'));
/// ```
#[inline]
pub fn peek(&self) -> Option<u8> {
if !self.is_empty() {
// SAFETY:
// `self` is not empty
unsafe { Some(*self.ptr.add(self.pos)) }
} else {
None
}
}
/// Peek the byte at the nth position from the current position.
///
/// # Example
///
/// ```
/// use bytes::Bytes;
///
/// let b = Bytes::from_static(b"a byte slice");
/// let iter = b.into_iter();
///
/// assert_eq!(iter.peek_nth(0), Some(b'a'));
/// assert_eq!(iter.peek_nth(3), Some(b'y'));
/// ```
#[inline]
pub fn peek_nth(&self, n: usize) -> Option<u8> {
let pos = self.pos + n;
if pos < self.len {
// SAFETY:
// `pos < self.len`
unsafe { Some(*self.ptr.add(pos)) }
} else {
None
}
}
/// Peek a slice of bytes from `self.pos` to `self.pos + n`.
/// If `self.pos + n >= self.len` then `Option::None` is returned.
///
/// # Example
///
/// ```
/// use bytes::Bytes;
/// let b = Bytes::from_static(b"a bytes slice");
/// let iter = b.into_iter();
///
/// assert_eq!(iter.peek_n(7), Some(&b"a bytes"[..]));
/// ```
#[inline]
pub fn peek_n(&self, n: usize) -> Option<&[u8]> {
let end = self.pos + n;
if end < self.len {
Some(&self._b[self.pos..end])
} else {
None
}
}
/// Take the next bytes from `self.pos` to `self.pos + n`.
/// If `self.pos + n >= self.len` then `Option::None` is returned.
///
/// # Example
///
/// ```
/// use bytes::Bytes;
///
/// let b = Bytes::from_static(b"a bytes slice");
/// let mut iter = b.into_iter();
///
/// assert_eq!(iter.next_n(7), Some(&b"a bytes"[..]));
/// assert_eq!(iter.next(), Some(b' '));
/// ```
#[inline]
pub fn next_n(&mut self, n: usize) -> Option<&[u8]> {
let end = self.pos + n;
if end < self.len {
let b = Some(&self._b[self.pos..end]);
self.pos += n;
b
} else {
None
}
}
/// Advance the position cursor of `n`.
///
/// # Safety
///
/// You must ensures that `self.pos + n < self.len` in order to keep `Self`
/// invariant.
///
/// # Example
///
/// ```
/// use bytes::Bytes;
///
/// let b = Bytes::from_static(b"a bytes slice");
/// let mut iter = b.into_iter();
///
/// unsafe { iter.advance(6) };
/// assert_eq!(iter.next(), Some(b's'));
/// ```
#[inline]
pub unsafe fn advance(&mut self, n: usize) {
debug_assert!(
self.pos + n < self.len,
"position out of bounds, self.pos ({}) >= self.len ({})",
self.pos + n,
self.len
);
self.pos += n;
}
/// Advance the position cursor of 1. This is strictly equivalent to
/// `advance(1)`.
///
/// # Safety
///
/// You must ensures that `self.pos + 1 < self.len` in order to keep `Self`
/// invariant.
///
/// # Example
///
/// ```
/// use bytes::Bytes;
///
/// let b = Bytes::from_static(b"a bytes slice");
/// let mut iter = b.into_iter();
///
/// unsafe { iter.bump() };
/// assert_eq!(iter.next(), Some(b' '));
/// ```
#[inline]
pub unsafe fn bump(&mut self) {
self.advance(1)
}
}
impl IntoIterator for Bytes {
type Item = u8;
type IntoIter = BytesIter;
#[inline]
fn into_iter(self) -> BytesIter {
BytesIter::new(self)
}
}
impl Iterator for BytesIter {
type Item = u8;
#[inline]
fn next(&mut self) -> Option<u8> {
if self.pos < self.len {
// SAFETY:
// `self.ptr` is valid by the `self` invariant and `self.pos < self.len`
let b = unsafe { Some(*self.ptr.add(self.pos)) };
self.pos += 1;
b
} else {
None
}
}
} |
/* @settings
name: Minimal
id: minimal-style
settings:
-
id: instructions
title: Welcome 👋
type: heading
level: 2
collapsed: true
description: Use the Minimal Theme Settings plugin to access hotkeys, adjust features, select fonts, and choose from preset color schemes. Use the settings below for more granular customization. Visit minimal.guide for documentation.
-
id: interface
title: Interface colors
type: heading
level: 2
collapsed: true
-
id: base
title: Base color
description: Defines all background and border colors unless overridden in more granular settings
type: variable-themed-color
format: hsl-split
default-light: '#'
default-dark: '#'
-
id: bg1
title: Primary background
description: Background color for the main window
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: bg2
title: Secondary background
description: Background color for left sidebar and menus
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: bg3
title: Active background
description: Background color for hovered buttons and currently selected file
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: ui1
title: Border color
type: variable-themed-color
description: For buttons, divider lines, and outlined elements
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: ui2
title: Highlighted border color
description: Used when hovering over buttons, dividers, and outlined elements
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: ui3
title: Active border color
description: Used when clicking buttons and outlined elements
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: accent-color
title: Accent color
type: heading
level: 2
collapsed: true
-
id: ax1
title: Accent color
type: variable-themed-color
description: Used primarily for links
format: hex
default-light: '#'
default-dark: '#'
-
id: ax2
title: Accent color (hover)
type: variable-themed-color
description: Used primarily for hovered links
format: hex
default-light: '#'
default-dark: '#'
-
id: ax3
title: Accent color interactive
type: variable-themed-color
description: Used for buttons, checklists, toggles
format: hex
default-light: '#'
default-dark: '#'
-
id: sp1
title: Text on accent
type: variable-themed-color
description: Used primarily for text on accented buttons
format: hex
default-light: '#'
default-dark: '#'
-
id: extended-palette
title: Extended colors
type: heading
level: 2
collapsed: true
-
id: color-red
title: Red
description: Extended palette colors are defaults used for progress bar status, syntax highlighting, colorful headings, and graph nodes
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: color-orange
title: Orange
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: color-yellow
title: Yellow
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: color-green
title: Green
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: color-cyan
title: Cyan
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: color-blue
title: Blue
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: color-purple
title: Purple
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: color-pink
title: Pink
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: active-line
title: Active line
type: heading
level: 2
collapsed: true
-
id: active-line-on
title: Highlight active line
description: Adds a background to current line in editor
type: class-toggle
default: false
-
id: active-line-bg
title: Active line background
description: Using a low opacity color is recommended to avoid conflicting with highlights
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: blockquotes
title: Blockquotes
type: heading
level: 2
collapsed: true
-
id: blockquote-color
title: Blockquote text color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: blockquote-background-color
title: Blockquote background color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: blockquote-border-color
title: Blockquote border color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: blockquote-border-thickness
title: Blockquote border thickness
type: variable-number-slider
format: px
default: 1
min: 0
max: 5
step: 1
-
id: blockquote-size
title: Blockquote font size
description: Accepts any CSS font-size value
type: variable-text
default: ''
-
id: blockquote-font-style
title: Blockquote font style
type: variable-select
allowEmpty: false
default: normal
options:
-
label: Normal
value: normal
-
label: Italic
value: italic
-
id: callouts
title: Callouts
type: heading
level: 2
collapsed: true
-
id: callouts-style
title: Callout style
type: class-select
allowEmpty: false
default: callouts-default
options:
-
label: Filled
value: callouts-default
-
label: Outlined
value: callouts-outlined
-
id: callout-blend-mode
title: Color blending
description: Blend the color of nested callouts
type: variable-select
allowEmpty: false
default: var(--highlight-mix-blend-mode)
options:
-
label: On
value: var(--highlight-mix-blend-mode)
-
label: Off
value: normal
-
id: canvas
title: Canvas
type: heading
level: 2
collapsed: true
-
id: canvas-dot-pattern
title: Canvas dot pattern
description: Color for background dot pattern
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: code-blocks
title: Code blocks
type: heading
level: 2
collapsed: true
-
id: code-size
title: Code font size
description: Accepts any CSS font-size value
type: variable-text
default: 13px
-
id: minimal-code-scroll
title: Scroll long lines
description: Turns off line wrap for code
type: class-toggle
default: false
-
id: code-background
title: Code background color
description: Background for code blocks
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: code-normal
title: Code text color
description: Color of code when syntax highlighting is not present
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: syntax-highlighting
title: Syntax highlighting
type: heading
level: 3
collapsed: false
-
id: code-comment
title: "Syntax: comments"
description: Syntax highlighting for comments
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: code-function
title: "Syntax: functions"
description: Syntax highlighting for functions
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: code-keyword
title: "Syntax: keywords"
description: Syntax highlighting for keywords
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: code-important
title: "Syntax: important"
description: Syntax highlighting for important text
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: code-operator
title: "Syntax: operators"
description: Syntax highlighting for operators
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: code-property
title: "Syntax: properties"
description: Syntax highlighting for properties
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: code-punctuation
title: "Syntax: punctuation"
description: Syntax highlighting for punctuation
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: code-string
title: "Syntax: strings"
description: Syntax highlighting for strings
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: code-tag
title: "Syntax: tags"
description: Syntax highlighting for tags
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: code-value
title: "Syntax: values"
description: Syntax highlighting for values
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: dataview
title: Dataview
type: heading
level: 2
collapsed: true
-
id: trim-cols
title: Trim Dataview columns
description: Disables word wrapping in table cells, and trims long text
type: class-toggle
default: true
-
id: max-col-width
title: Dataview maximum column width
description: Maximum width for Dataview columns, accepts any CSS width value
type: variable-text
default: 18em
-
id: embed-blocks
title: Embeds and transclusions
type: heading
level: 2
collapsed: true
-
id: embed-strict
title: Use strict embed style globally
description: Transclusions appear seamlessly in the flow of text. Can be enabled per file using the embed-strict helper class
type: class-toggle
default: false
-
id: graphs
title: Graphs
type: heading
level: 2
collapsed: true
-
id: graph-line
title: Line color
description: Changing graph colors requires closing and reopening graph panes or restarting Obsidian
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: graph-node
title: Node color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: graph-node-focused
title: Active node color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: graph-node-tag
title: Tag node color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: graph-node-attachment
title: Attachment node color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: graph-node-unresolved
title: Unresolved node color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: headings
title: Headings
type: heading
level: 2
collapsed: true
-
id: level-1-headings
title: Level 1 Headings
type: heading
level: 3
collapsed: true
-
id: h1-font
title: H1 font
description: Name of the font as it appears on your system
type: variable-text
default: ''
-
id: h1-size
title: H1 font size
description: Accepts any CSS font-size value
type: variable-text
default: 1.125em
-
id: h1-weight
title: H1 font weight
type: variable-number-slider
default: 600
min: 100
max: 900
step: 100
-
id: h1-color
title: H1 text color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: h1-variant
title: H1 font variant
type: variable-select
allowEmpty: false
default: normal
options:
-
label: Normal
value: normal
-
label: Small caps
value: small-caps
-
label: All small caps
value: all-small-caps
-
id: h1-style
title: H1 font style
type: variable-select
allowEmpty: false
default: normal
options:
-
label: Normal
value: normal
-
label: Italic
value: italic
-
id: h1-l
title: H1 divider line
description: Adds a border below the heading
type: class-toggle
default: false
-
id: level-2-headings
title: Level 2 Headings
type: heading
level: 3
collapsed: true
-
id: h2-font
title: H2 font
description: Name of the font as it appears on your system
type: variable-text
default: ''
-
id: h2-size
title: H2 font size
description: Accepts any CSS font-size value
type: variable-text
default: 1em
-
id: h2-weight
title: H2 font weight
type: variable-number-slider
default: 600
min: 100
max: 900
step: 100
-
id: h2-color
title: H2 text color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: h2-variant
title: H2 font variant
type: variable-select
allowEmpty: false
default: normal
options:
-
label: Normal
value: normal
-
label: Small caps
value: small-caps
-
label: All small caps
value: all-small-caps
-
id: h2-style
title: H2 font style
type: variable-select
allowEmpty: false
default: normal
options:
-
label: Normal
value: normal
-
label: Italic
value: italic
-
id: h2-l
title: H2 divider line
description: Adds a border below the heading
type: class-toggle
default: false
-
id: level-3-headings
title: Level 3 Headings
type: heading
level: 3
collapsed: true
-
id: h3-font
title: H3 font
description: Name of the font as it appears on your system
type: variable-text
default: ''
-
id: h3-size
title: H3 font size
description: Accepts any CSS font-size value
type: variable-text
default: 1em
-
id: h3-weight
title: H3 font weight
type: variable-number-slider
default: 600
min: 100
max: 900
step: 100
-
id: h3-color
title: H3 text color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: h3-variant
title: H3 font variant
type: variable-select
allowEmpty: false
default: normal
options:
-
label: Normal
value: normal
-
label: Small caps
value: small-caps
-
label: All small caps
value: all-small-caps
-
id: h3-style
title: H3 font style
type: variable-select
allowEmpty: false
default: normal
options:
-
label: Normal
value: normal
-
label: Italic
value: italic
-
id: h3-l
title: H3 divider line
description: Adds a border below the heading
type: class-toggle
default: false
-
id: level-4-headings
title: Level 4 Headings
type: heading
level: 3
collapsed: true
-
id: h4-font
title: H4 font
description: Name of the font as it appears on your system
type: variable-text
default: ''
-
id: h4-size
title: H4 font size
description: Accepts any CSS font-size value
type: variable-text
default: 0.9em
-
id: h4-weight
title: H4 font weight
type: variable-number-slider
default: 500
min: 100
max: 900
step: 100
-
id: h4-color
title: H4 text color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: h4-variant
title: H4 font variant
type: variable-select
allowEmpty: false
default: small-caps
options:
-
label: Normal
value: normal
-
label: Small caps
value: small-caps
-
label: All small caps
value: all-small-caps
-
id: h4-style
title: H4 font style
type: variable-select
allowEmpty: false
default: normal
options:
-
label: Normal
value: normal
-
label: Italic
value: italic
-
id: h4-l
title: H4 divider line
description: Adds a border below the heading
type: class-toggle
default: false
-
id: level-5-headings
title: Level 5 Headings
type: heading
level: 3
collapsed: true
-
id: h5-font
title: H5 font
description: Name of the font as it appears on your system
type: variable-text
default: ''
-
id: h5-size
title: H5 font size
description: Accepts any CSS font-size value
type: variable-text
default: 0.85em
-
id: h5-weight
title: H5 font weight
type: variable-number-slider
default: 500
min: 100
max: 900
step: 100
-
id: h5-color
title: H5 text color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: h5-variant
title: H5 font variant
type: variable-select
allowEmpty: false
default: small-caps
options:
-
label: Normal
value: normal
-
label: Small caps
value: small-caps
-
label: All small caps
value: all-small-caps
-
id: h5-style
title: H5 font style
type: variable-select
allowEmpty: false
default: normal
options:
-
label: Normal
value: normal
-
label: Italic
value: italic
-
id: h5-l
title: H5 divider line
description: Adds a border below the heading
type: class-toggle
default: false
-
id: level-6-headings
title: Level 6 Headings
type: heading
level: 3
collapsed: true
-
id: h6-font
title: H6 font
description: Name of the font as it appears on your system
type: variable-text
default: ''
-
id: h6-size
title: H6 font size
description: Accepts any CSS font-size value
type: variable-text
default: 0.85em
-
id: h6-weight
title: H6 font weight
type: variable-number-slider
default: 400
min: 100
max: 900
step: 100
-
id: h6-color
title: H6 text color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: h6-variant
title: H6 font variant
type: variable-select
allowEmpty: false
default: small-caps
options:
-
label: Normal
value: normal
-
label: Small caps
value: small-caps
-
label: All small caps
value: all-small-caps
-
id: h6-style
title: H6 font style
type: variable-select
allowEmpty: false
default: normal
options:
-
label: Normal
value: normal
-
label: Italic
value: italic
-
id: h6-l
title: H6 divider line
type: class-toggle
description: Adds a border below the heading
default: false
-
id: icons
title: Icons
type: heading
level: 2
collapsed: true
-
id: icon-muted
title: Icon opacity (inactive)
type: variable-number-slider
default: 0.5
min: 0.25
max: 1
step: 0.05
-
id: icon-color
title: Icon color
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: icon-color-hover
title: Icon color (hover)
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: icon-color-active
title: Icon color (active)
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: icon-color-focused
title: Icon color (focused)
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: images
title: Images
type: heading
level: 2
collapsed: true
-
id: image-muted
title: Image opacity in dark mode
description: Level of fading for images in dark mode. Hover over images to display at full brightness.
type: variable-number-slider
default: 0.7
min: 0.25
max: 1
step: 0.05
-
id: zoom-off
title: Disable image zoom
description: Turns off click + hold to zoom images
type: class-toggle
-
id: indentation-guides
title: Indentation guides
type: heading
level: 2
collapsed: true
-
id: ig-adjust-reading
title: Horizontal adjustment in reading mode
type: variable-number-slider
default: -0.65
min: -1.2
max: 0
step: 0.05
format: em
-
id: ig-adjust-edit
title: Horizontal adjustment in edit mode
type: variable-number-slider
default: -1
min: -10
max: 10
step: 1
format: px
-
id: indentation-guide-color
title: Indentation guide color
type: variable-themed-color
format: hex
opacity: true
default-light: '#'
default-dark: '#'
-
id: indentation-guide-color-active
title: Indentation guide color (active)
type: variable-themed-color
format: hex
opacity: true
default-light: '#'
default-dark: '#'
-
id: links
title: Links
type: heading
level: 2
collapsed: true
-
id: links-internal
title: Internal links
type: heading
level: 3
collapsed: true
-
id: link-color
title: Internal link color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: link-color-hover
title: Internal link color (hover)
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: link-unresolved-opacity
title: Unresolved link opacity
type: variable-number-slider
default: 0.7
min: 0.25
max: 1
step: 0.05
-
id: link-unresolved-color
title: Unresolved link color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: link-unresolved-decoration-color
title: Unresolved link underline color
type: variable-themed-color
format: hex
opacity: true
default-light: '#'
default-dark: '#'
-
id: links-external
title: External links
type: heading
level: 3
collapsed: true
-
id: link-external-color
title: External link color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: link-external-color-hover
title: External link color (hover)
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: lists
title: Lists and tasks
type: heading
level: 2
collapsed: true
-
id: checkbox-color
title: Checkbox color
description: Background color for completed tasks
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: checkbox-shape
title: Checkbox shape
type: class-select
allowEmpty: false
default: checkbox-circle
options:
-
label: Circle
value: checkbox-circle
-
label: Square
value: checkbox-square
-
id: minimal-strike-lists
title: Strike completed tasks
description: Adds strikethrough line and greyed text for completed tasks
type: class-toggle
default: false
-
id: list-spacing
title: List item spacing
description: Vertical space between list items in em units
type: variable-number-slider
default: 0.075
min: 0
max: 0.3
step: 0.005
format: em
-
id: list-indent
title: Nested list indentation
description: Horizontal space from left in em units
type: variable-number-slider
default: 2
min: 1
max: 3.5
step: 0.1
format: em
-
id: sidebars
title: Sidebars
type: heading
level: 2
collapsed: true
-
id: sidebar-lines-off
title: Disable sidebar relationship lines
description: Turns off lines in file navigation
type: class-toggle
-
id: sidebar-tabs-style
title: Sidebar tab style
type: class-select
allowEmpty: false
default: sidebar-tabs-default
options:
-
label: Index round
value: sidebar-tabs-index
-
label: Index square
value: sidebar-tabs-square
-
label: Modern compact
value: sidebar-tabs-default
-
label: Modern wide
value: sidebar-tabs-wide
-
label: Underline
value: sidebar-tabs-underline
-
id: mobile-left-sidebar-width
title: Mobile left sidebar width
description: Maximum width for pinned left sidebar on mobile
type: variable-number
default: 280
format: pt
-
id: mobile-right-sidebar-width
title: Mobile right sidebar width
description: Maximum width for pinned right sidebar on mobile
type: variable-number
default: 240
format: pt
-
id: tables
title: Tables
type: heading
level: 2
collapsed: true
-
id: table-text-size
title: Table font size
description: All of the following settings apply to all tables globally. To turn on these features on a per-note basis use helper classes. See documentation.
type: variable-text
default: 1em
-
id: maximize-tables-off
title: Maximize table width (beta)
description: Tables fill the width of the line
type: class-select
allowEmpty: false
default: maximize-tables
options:
-
label: Always
value: maximize-tables
-
label: Automatic
value: maximize-tables-auto
-
label: Never
value: maximize-tables-off
-
id: row-lines
title: Row lines
description: Display borders between table rows globally
type: class-toggle
default: false
-
id: col-lines
title: Column lines
description: Display borders between table columns globally
type: class-toggle
default: false
-
id: table-lines
title: Cell lines
description: Display borders around all table cells globally
type: class-toggle
default: false
-
id: row-alt
title: Striped rows
description: Display striped background in alternating table rows globally
type: class-toggle
default: false
-
id: col-alt
title: Striped columns
description: Display striped background in alternating table columns globally
type: class-toggle
default: false
-
id: table-tabular
title: Tabular figures
description: Use fixed width numbers in tables globally
type: class-toggle
default: false
-
id: table-numbers
title: Row numbers
description: Display row numbers in tables globally
type: class-toggle
default: false
-
id: table-nowrap
title: Disable line wrap
description: Turn off line wrapping in table cells globally
type: class-toggle
default: false
-
id: row-hover
title: Highlight active row
description: Highlight rows on hover
type: class-toggle
default: false
-
id: table-row-background-hover
title: Active row background
description: Background color for hovered tables rows
type: variable-themed-color
format: hex
opacity: true
default-light: '#'
default-dark: '#'
-
id: tabs
title: Tabs
type: heading
level: 2
collapsed: true
-
id: header-height
title: Tab bar height
type: variable-text
default: 40px
-
id: tabs-style
title: Tab style
type: class-select
allowEmpty: false
default: tabs-default
options:
-
label: Index round
value: tabs-default
-
label: Index square
value: tabs-square
-
label: Modern
value: tabs-modern
-
label: Underline
value: tabs-underline
-
id: minimal-tab-text-color
title: Tab text color
type: variable-themed-color
format: hex
opacity: true
default-light: '#'
default-dark: '#'
-
id: minimal-tab-text-color-active
title: Tab text color (active)
type: variable-themed-color
format: hex
opacity: true
default-light: '#'
default-dark: '#'
-
id: tab-stacks
title: Tab stacks
type: heading
level: 2
collapsed: true
-
id: tab-stacked-pane-width
title: Stacked width
type: variable-number
description: Width of a stacked tab in pixels
default: 700
format: px
-
id: tab-stacked-header-width
title: Spine width
type: variable-number
description: Width of the spine in pixels
default: 40
format: px
-
id: tab-stacked-spine-orientation
title: Spine text orientation
type: class-select
default: tab-stack-top
options:
-
label: Top
value: tab-stack-top
-
label: Top flipped
value: tab-stack-top-flipped
-
label: Bottom
value: tab-stack-bottom
-
label: Bottom flipped
value: tab-stack-bottom-flipped
-
label: Center
value: tab-stack-center
-
label: Center flipped
value: tab-stack-center-flipped
-
id: tags
title: Tags
type: heading
level: 2
collapsed: true
-
id: minimal-unstyled-tags
title: Plain tags
description: Tags will render as normal text, overrides settings below
type: class-toggle
default: false
-
id: tag-radius
title: Tag shape
type: variable-select
default: 14px
options:
-
label: Pill
value: 14px
-
label: Rounded
value: 4px
-
label: Square
value: 0px
-
id: tag-border-width
title: Tag border width
type: variable-select
default: 1px
options:
-
label: None
value: 0
-
label: Thin
value: 1px
-
label: Thick
value: 2px
-
id: tag-color
title: Tag text color
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: tag-background
title: Tag background color
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: tag-background-hover
title: Tag background color (hover)
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: text
title: Text
type: heading
level: 2
collapsed: true
-
id: tx1
title: Normal text color
type: variable-themed-color
description: Primary text color used by default across all elements
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: hl1
title: Selected text background
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: hl2
title: Highlighted text background
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: tx2
title: Muted text color
description: Secondary text such as sidebar note titles and table headings
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: tx3
title: Faint text color
description: tertiary text such as input placeholders, empty checkboxes, and disabled statuses
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: italic-color
title: Italic text color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: bold-color
title: Bold text color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: bold-weight
title: Bold text weight
type: variable-number-slider
default: 600
min: 100
max: 900
step: 100
-
id: spacing-p
title: Paragraph spacing
description: Space between paragraphs in reading mode
type: variable-text
default: 0.75em
-
id: titles
title: Titles
type: heading
level: 2
collapsed: true
-
id: tab-title-bar
title: Tab title bar
description: Tab title bar must be turned on in Appearance settings
type: heading
level: 3
collapsed: true
-
id: file-header-visibility
title: Tab title visibility
description: Visibility of the tab title text
type: class-select
default: minimal-tab-title-hover
options:
-
label: Hover only
value: minimal-tab-title-hover
-
label: Hidden
value: minimal-tab-title-hidden
-
label: Visible
value: minimal-tab-title-visible
-
id: file-header-font-size
title: Tab title font size
description: Accepts any CSS font-size value
type: variable-text
default: 0.9em
-
id: file-header-font-weight
title: Tab title font weight
type: variable-number-slider
default: 400
min: 100
max: 900
step: 100
-
id: file-header-justify
title: Tab title alignment
type: variable-select
default: center
options:
-
label: Center
value: center
-
label: Left
value: left
-
id: title-color
title: Tab title text color (active)
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: title-color-inactive
title: Tab title text color (inactive)
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: inline-title
title: Inline title
description: Inline titles must be turned on in Appearance settings
type: heading
level: 3
collapsed: true
-
id: inline-title-font
title: Inline title font
description: Name of the font as it appears on your system
type: variable-text
default: ''
-
id: inline-title-size
title: Inline title font size
description: Accepts any CSS font-size value
type: variable-text
default: 1.125em
-
id: inline-title-weight
title: Inline title font weight
type: variable-number-slider
default: 600
min: 100
max: 900
step: 100
-
id: inline-title-color
title: Inline title text color (active)
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: translucency
title: Translucency
type: heading
level: 2
collapsed: true
-
id: workspace-background-translucent
title: Translucent background color
type: variable-themed-color
opacity: true
format: hex
default-light: '#'
default-dark: '#'
-
id: window-frame
title: Window frame
type: heading
level: 2
collapsed: true
-
id: window-title-off
title: Hide window frame title
description: Hide title in the custom title bar
type: class-toggle
-
id: frame-background
title: Frame background
description: Requires colorful window frame
type: variable-themed-color
opacity: true
format: hsl-split
default-light: '#'
default-dark: '#'
-
id: frame-icon-color
title: Frame icon color
description: Requires colorful frame
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: titlebar-text-color-focused
title: Frame title color (focused)
description: Requires custom title bar
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: titlebar-text-color
title: Frame title color (inactive)
description: Requires custom title bar
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
-
id: titlebar-text-weight
title: Frame title font weight
description: Requires custom title bar
type: variable-number-slider
default: 600
min: 100
max: 900
step: 100
*/
/* @settings
name: Minimal Cards
id: minimal-cards-style
settings:
-
id: cards-min-width
title: Card minimum width
type: variable-text
default: 180px
-
id: cards-max-width
title: Card maximum width
description: Default fills the available width, accepts valid CSS units
type: variable-text
default: 1fr
-
id: cards-mobile-width
title: Card minimum width on mobile
type: variable-text
default: 120px
-
id: cards-padding
title: Card padding
type: variable-text
default: 1.2em
-
id: cards-image-height
title: Card maximum image height
type: variable-text
default: 400px
-
id: cards-border-width
title: Card border width
type: variable-text
default: 1px
-
id: cards-background
title: Card background color
type: variable-themed-color
format: hex
default-light: '#'
default-dark: '#'
*/
/* @settings
name: Minimal Mobile
id: minimal-mobile
settings:
-
id: mobile-toolbar-off
title: Disable toolbar
description: Turns off mobile toolbar
type: class-toggle
*/
/* @settings
name: Minimal Advanced Settings
id: minimal-advanced
settings:
-
id: styled-scrollbars
title: Styled scrollbars
description: Use styled scrollbars (replaces native scrollbars)
type: class-toggle
-
id: cursor
title: Cursor style
description: The cursor style for UI elements
type: variable-select
default: default
options:
-
label: Default
value: default
-
label: Pointer
value: pointer
-
label: Crosshair
value: crosshair
-
id: font-ui-small
title: Small font size
description: Font size in px of smaller text
type: variable-number
default: 13
format: px
-
id: font-ui-smaller
title: Smaller font size
description: Font size in px of smallest text
type: variable-number
default: 11
format: px
-
id: folding-offset
title: Folding offset
description: Width of the left margin used for folding indicators
type: variable-number-slider
default: 10
min: 0
max: 30
step: 1
format: px
*/ |
---
changelog:
- 2024-01-28, gpt-4-0125-preview, translated from English
date: 2024-01-28 22:08:18.799169-07:00
description: 'Hoe te: Om een HTTP-verzoek met basisverificatie te verzenden, gebruik
je doorgaans de module `Net::HTTP` in Ruby. Hier is een snel voorbeeld.'
lastmod: '2024-03-13T22:44:51.337747-06:00'
model: gpt-4-0125-preview
summary: Om een HTTP-verzoek met basisverificatie te verzenden, gebruik je doorgaans
de module `Net::HTTP` in Ruby.
title: Een HTTP-verzoek verzenden met basisauthenticatie
weight: 45
---
## Hoe te:
Om een HTTP-verzoek met basisverificatie te verzenden, gebruik je doorgaans de module `Net::HTTP` in Ruby. Hier is een snel voorbeeld:
```Ruby
require 'net/http'
require 'uri'
uri = URI('http://example.com')
gebruikersnaam = 'je_gebruikersnaam'
wachtwoord = 'je_wachtwoord'
verzoek = Net::HTTP::Get.new(uri)
verzoek.basic_auth(gebruikersnaam, wachtwoord)
reactie = Net::HTTP.start(uri.hostname, uri.port) {|http|
http.request(verzoek)
}
puts reactie.body
```
Als je deze code uitvoert met geldige inloggegevens, zul je de body van de reactie uitgeprint zien. Als de inloggegevens ongeldig zijn, krijg je een foutmelding.
## Diepere Duik
Basisverificatie heeft een lange geschiedenis als deel van webprotocollen, teruggaand tot de vroege RFC's die de werking van het internet definieerden. Het is een eenvoudige methode voor toegangscontrole: de gebruikersnaam en het wachtwoord worden gecodeerd met Base64 en in de HTTP-header doorgegeven.
Echter, basisverificatie verzendt inloggegevens in platte tekst (hoewel gecodeerd), dus het is niet veilig over HTTP. Het is beter om HTTPS te gebruiken om inloggegevens veilig te houden voor nieuwsgierige blikken.
Er zijn veiligere alternatieven zoals OAuth, dat vaak wordt gebruikt voor API-verificatie. OAuth staat gebruikers toe om toegang van derde partijen te autoriseren zonder inloggegevens te delen. Toch blijft basisverificatie in gebruik, vooral voor interne toepassingen en snelle en vuile scripting.
Een detail om op te merken is dat Ruby's `Net::HTTP` Basic Auth niet native behandelt totdat je expliciet de `basic_auth` methode gebruikt. Het is ook cruciaal om mogelijke uitzonderingen en foutresponsen die kunnen resulteren uit het HTTP-verzoek te behandelen.
## Zie Ook
- Ruby standaardbibliotheek `Net::HTTP` documentatie: https://ruby-doc.org/stdlib-3.0.0/libdoc/net/http/rdoc/Net/HTTP.html
- RFC 7617, 'The 'Basic' HTTP Authentication Scheme': https://tools.ietf.org/html/rfc7617
- Een introductie tot OAuth voor authenticatie: https://oauth.net/2/
- Meer over Ruby en HTTP-verzoeken: https://www.rubyguides.com/2019/08/ruby-http-request/ |
//你的笔记本键盘存在故障,每当你在上面输入字符 'i' 时,它会反转你所写的字符串。而输入其他字符则可以正常工作。
//
// 给你一个下标从 0 开始的字符串 s ,请你用故障键盘依次输入每个字符。
//
// 返回最终笔记本屏幕上输出的字符串。
//
//
//
// 示例 1:
//
// 输入:s = "string"
//输出:"rtsng"
//解释:
//输入第 1 个字符后,屏幕上的文本是:"s" 。
//输入第 2 个字符后,屏幕上的文本是:"st" 。
//输入第 3 个字符后,屏幕上的文本是:"str" 。
//因为第 4 个字符是 'i' ,屏幕上的文本被反转,变成 "rts" 。
//输入第 5 个字符后,屏幕上的文本是:"rtsn" 。
//输入第 6 个字符后,屏幕上的文本是: "rtsng" 。
//因此,返回 "rtsng" 。
//
//
// 示例 2:
//
// 输入:s = "poiinter"
//输出:"ponter"
//解释:
//输入第 1 个字符后,屏幕上的文本是:"p" 。
//输入第 2 个字符后,屏幕上的文本是:"po" 。
//因为第 3 个字符是 'i' ,屏幕上的文本被反转,变成 "op" 。
//因为第 4 个字符是 'i' ,屏幕上的文本被反转,变成 "po" 。
//输入第 5 个字符后,屏幕上的文本是:"pon" 。
//输入第 6 个字符后,屏幕上的文本是:"pont" 。
//输入第 7 个字符后,屏幕上的文本是:"ponte" 。
//输入第 8 个字符后,屏幕上的文本是:"ponter" 。
//因此,返回 "ponter" 。
//
//
//
// 提示:
//
//
// 1 <= s.length <= 100
// s 由小写英文字母组成
// s[0] != 'i'
//
//
// Related Topics 字符串 模拟 👍 7 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String finalString(String s) {
char[] charArray = s.toCharArray();
int index = 0;
// 遍历
for (int i = 0; i < charArray.length; i++) {
// 不为i复制
if (charArray[i] != 'i') {
charArray[index++] = charArray[i];
continue;
}
// 否则,反转i之前的字符
reverse(charArray, index - 1);
}
return String.valueOf(charArray, 0, index);
}
// 反转从0到index的字符
private void reverse(char[] charArray, int index) {
for (int i = 0; i < index; i++) {
char temp = charArray[i];
charArray[i] = charArray[index];
charArray[index] = temp;
index--;
}
}
}
//leetcode submit region end(Prohibit modification and deletion) |
import type { ActionArgs, LoaderArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Form, useActionData, useLoaderData, useNavigation, isRouteErrorResponse, useRouteError, } from "@remix-run/react";
import invariant from "tiny-invariant";
import { createPost, updatePost, getPost } from "~/models/post.server";
import { requireUserId, getUserId } from "~/session.server";
export async function loader({ request, params }: LoaderArgs) {
const userId = await requireUserId(request);
invariant(params.slug , "slug not found");
if (params.slug === "new") {
return json({ post: null });
}
const post = await getPost({ slug: params.slug, userId });
if (!post) {
throw new Response("Not Found", { status: 404 });
}
return json({ post });
}
export const action = async ({ request, params }: ActionArgs) => {
const userId = await requireUserId(request);
const formData = await request.formData();
const intent = formData.get("intent");
const slug = intent !== "update" ? formData.get("slug") : params.slug;
const imageUrl = formData.get("imageUrl");
const title = formData.get("title");
const body = formData.get("body");
const errors = {
title: title ? null : "Title is required",
slug: slug ? null : "Slug is required",
body: body ? null : "Body is required",
imageUrl: imageUrl ? null : "image is required",
};
const hasErrors = Object.values(errors).some((errorMessage) => errorMessage);
if (hasErrors) {
return json(errors);
}
invariant(typeof title === "string", "title must be a string");
invariant(typeof body === "string", "body must be a string");
invariant(typeof imageUrl === "string", "lyric must be a string");
invariant(typeof slug === "string", "slug must be a string");
if (params.slug === "new") {
await createPost({ slug, title, imageUrl, body, userId });
} else {
await updatePost({
title, imageUrl, body, slug, userId});
}
return redirect(`/posts`);
};
export default function PostAdmin() {
const data = useLoaderData<typeof loader>();
const errors = useActionData<typeof action>();
const navigation = useNavigation();
const isCreating = navigation.formData?.get("intent") === "create";
const isUpdating = navigation.formData?.get("intent") === "update";
const isNewPost = !data.post;
return (
<Form
method="post"
style={{
display: "flex",
flexDirection: "column",
gap: 8,
width: "100%",
}}
>
<div>
<label className="flex w-full flex-col gap-1">
<span>Slug: </span>
{errors?.slug ? (
<em className="text-red-600">{errors.slug}</em>
) : null}
<input
name="slug"
key={data?.post?.slug ?? "new"}
className="flex-1 rounded-md border-2 border-blue-500 px-3 text-lg leading-loose"
defaultValue={data?.post?.slug}
/>
</label>
<label className="flex w-full flex-col gap-1">
<span>imageUrl: </span>
{errors?.imageUrl ? (
<em className="text-red-600">{errors.imageUrl}</em>
) : null}
<input
name="imageUrl"
key={data?.post?.imageUrl ?? "new"}
className="flex-1 rounded-md border-2 border-blue-500 px-3 text-lg leading-loose"
defaultValue={data?.post?.imageUrl}
/>
</label>
<label className="flex w-full flex-col gap-1">
<span>Title: </span>
{errors?.title ? (
<em className="text-red-600">{errors.title}</em>
) : null}
<input
name="title"
key={data?.post?.title ?? "new"}
className="flex-1 rounded-md border-2 border-blue-500 px-3 text-lg leading-loose"
defaultValue={data?.post?.title}
/>
</label>
</div>
<div>
<label className="flex w-full flex-col gap-1">
<span>Body: </span>
{errors?.body ? (
<em className="text-red-600">{errors.body}</em>
) : null}
<textarea
name="body"
key={data?.post?.body ?? "new"}
rows={8}
className="w-full flex-1 rounded-md border-2 border-blue-500 px-3 py-2 text-lg leading-6"
defaultValue={data?.post?.body}
/>
</label>
</div>
<div className="text-right">
<button
type="submit"
value={isNewPost ? "create" : "update"}
className="rounded bg-blue-500 px-4 py-2 text-white hover:bg-blue-600 focus:bg-blue-400"
disabled={isCreating || isUpdating}>
{isNewPost ? (isCreating ? "Creating..." : "Create") : null}
{isNewPost? null : isUpdating ? "Updating..." : "Update"}
</button>
</div>
</Form>
);
}
export function ErrorBoundary() {
const error = useRouteError();
if (error instanceof Error) {
return <div>An unexpected error occurred: {error.message}</div>;
}
if (!isRouteErrorResponse(error)) {
return <h1>Unknown Error</h1>;
}
if (error.status === 404) {
return <div>Unauthorized to update this Post</div>;
}
return <div>An unexpected error occurred: {error.statusText}</div>;
} |
import { NextPage } from 'next'
import { ArrowPathIcon } from '@heroicons/react/24/outline'
import TwitterBox from './TwitterBox'
import { FeedProps, ITweet } from '../typings'
import Tweet from './Tweet'
import { fetchTweets } from '../utils/fetchTweets'
import { useState } from 'react'
import toast from 'react-hot-toast'
const Feeds: NextPage<FeedProps> = ({ tweets: tweetProps }) => {
const [tweets, setTweets] = useState<ITweet[]>(tweetProps)
const handleRefresh = async () => {
const refreshToast = toast.loading('Refreshing...')
const tweets = await fetchTweets()
setTweets(tweets)
toast.success('Tweets updated!',{
id:refreshToast
})
}
return (<main className='col-span-7 max-h-screen scrollbar-hide lg:col-span-5 border-x overflow-auto'>
<div className='flex items-center justify-between'>
<h1 className='p-5 pb-0 text-xl font-bold'>Home</h1>
{/*refresh icon button*/}
<ArrowPathIcon onClick={handleRefresh}
className='mr-5 mt-5 h-8 w-8 cursor-pointer text-twitter transition-all
duration-500 ease-out active:scale-125 active:rotate-180' />
</div>
<div>
<TwitterBox />
</div>
{/*Feeds*/}
<div>{
tweets && tweets.map(tweet => (
<Tweet key={tweet._id} tweet={tweet} />
))
}</div>
</main>)
}
export default Feeds |
package com.example.productorder.order.controller;
import com.example.productorder.order.domain.*;
import com.example.productorder.order.helper.OrderHelper;
import com.example.productorder.order.service.OrderService;
import com.example.productorder.product.domain.Price;
import com.example.productorder.product.service.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@SuppressWarnings("unused")
@RestController
@RequestMapping("/")
@Api(value="Orders", description="Operations pertaining to Orders")
public class OrderController {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
private final OrderService orderService;
private final ProductService productService;
@Autowired
public OrderController(OrderService orderService, ProductService productService) {
this.orderService = orderService;
this.productService = productService;
}
@GetMapping("/orders")
@ApiOperation(value = "View all orders between from and to dates", response = OrderInfo.class, responseContainer="List")
ResponseEntity<?> getOrders(@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") @RequestParam(required = false, value = "fromDate") LocalDateTime fromDate
, @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") @RequestParam(required = false, value = "toDate") LocalDateTime toDate
) {
//to date cannot be before from date
if (fromDate != null && toDate != null && toDate.isBefore(fromDate)) {
LOGGER.info("DateFrom is greater then dateTo");
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.build();
}
return ResponseEntity.ok(orderService.getOrders(fromDate, toDate)
.stream()
.map(order -> OrderHelper.convertToOrderInfo(order, orderService.countOrderTotal(order.getOrderDetail())))
.collect(Collectors.toList()));
}
@PostMapping("/orders")
@ApiOperation(value = "Create an order")
ResponseEntity<?> createOrder(@RequestBody @Valid NewOrderInfo newOrderInfo, BindingResult bindingResult) {
LocalDateTime orderDate = LocalDateTime.now();
Optional<Order> existingOrder = orderService.getOrderByEmailAndDate(newOrderInfo.getEmail(), orderDate);
if (bindingResult.hasErrors()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(bindingResult.getAllErrors().get(0).getDefaultMessage());
}
if (existingOrder.isPresent()) {
LOGGER.info("Order with such customer email and date already exists!!!");
return ResponseEntity.status(HttpStatus.CONFLICT)
.build();
}
if (!productService.checkIfAllProductsExists(newOrderInfo.getProductsToOrder()
.stream()
.map(NewOrderDetailInfo::getProductName)
.collect(Collectors.toSet()))) {
LOGGER.info("At least one of the ordered products does not exist!!!");
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.build();
}
Order savedOrderToSave = orderService.createNewOrder(newOrderInfo, orderDate);
OrderInfo savedOrderInfo = OrderHelper.convertToOrderInfo(orderService.save(savedOrderToSave), orderService.countOrderTotal(savedOrderToSave.getOrderDetail()));
return ResponseEntity.status(HttpStatus.CREATED).body(savedOrderInfo);
}
@GetMapping("/orders/{email}/{orderDate}/placed/{date}")
@ApiOperation(value = "Check how order with specific email and order date would look(e.g. total order sum) if it would be placed in other date", response = OrderInfo.class)
ResponseEntity<?> getOrderIfItWasPlacedOnSpecificDate(@Valid @PathVariable("email") String email
, @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") @Valid @PathVariable("orderDate") LocalDateTime orderDate
, @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") @Valid @PathVariable("date") LocalDateTime date) {
Optional<Order> existingOrder = orderService.getOrderByEmailAndDate(email, orderDate);
if (!existingOrder.isPresent()) {
LOGGER.info("Order not found");
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.build();
}
// check if all products have price that can be used to count the "what if" order with specific orderDate
if (!productService.checkIfAllProductsHavePriceOnDate(Stream.of(existingOrder.get())
.flatMap(order -> order.getOrderDetail().stream())
.map(OrderDetail::getProduct)
.collect(Collectors.toSet()), date)) {
LOGGER.info("At least one product does not have price in parameter date");
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.build();
}
return ResponseEntity.ok(OrderHelper.convertToOrderInfo(existingOrder.get(), orderService.countOrderTotalIfItWasPlacedOnSpecificDate(existingOrder.get(), date)));
}
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.codecs.simpletext;
import java.io.IOException;
import java.util.List;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.document.BinaryDocValuesField;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.tests.analysis.MockAnalyzer;
import org.apache.lucene.tests.index.BaseDocValuesFormatTestCase;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.tests.util.TestUtil;
import org.apache.lucene.util.BytesRef;
/** Tests SimpleTextDocValuesFormat */
public class TestSimpleTextDocValuesFormat extends BaseDocValuesFormatTestCase {
private final Codec codec = new SimpleTextCodec();
@Override
protected Codec getCodec() {
return codec;
}
public void testFileIsUTF8() throws IOException {
try (Directory dir = newDirectory()) {
IndexWriterConfig conf = newIndexWriterConfig(new MockAnalyzer(random()));
try (RandomIndexWriter writer = new RandomIndexWriter(random(), dir, conf)) {
for (int i = 0; i < 100; i++) {
writer.addDocument(
List.of(
new SortedDocValuesField(
"sortedVal", newBytesRef(TestUtil.randomSimpleString(random()))),
new SortedSetDocValuesField(
"sortedSetVal", newBytesRef(TestUtil.randomSimpleString(random()))),
new NumericDocValuesField("numberVal", random().nextLong()),
new BinaryDocValuesField("binaryVal", TestUtil.randomBinaryTerm(random()))));
}
}
for (String file : dir.listAll()) {
if (file.endsWith("dat")) {
try (IndexInput input = dir.openChecksumInput(file, IOContext.READONCE)) {
long length = input.length();
if (length > 20_000) {
// Avoid allocating a huge array if the length is wrong
fail("Doc values should not be this large");
}
byte[] bytes = new byte[(int) length];
input.readBytes(bytes, 0, bytes.length);
BytesRef bytesRef = new BytesRef(bytes);
assertNotEquals(bytesRef.toString(), Term.toString(bytesRef));
}
}
}
}
}
} |
package com.game.framework.message;
import com.game.framework.threads.SimpleThreadFactory;
import com.game.framework.time.ITriggerTaskExecutor;
import com.game.framework.time.TriggerFuture;
import com.game.framework.time.impl.TriggerTaskExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author liguorui
* @date 2018/1/7 18:45
*/
public class MessageHandler<H extends IMessageHandler<?>> implements Runnable, IMessageHandler<H> {
private static Logger profileLog = LoggerFactory.getLogger("profileLogger");
private static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newFixedThreadPool(100, new SimpleThreadFactory("MessageHandler-Worker"));
private static ITriggerTaskExecutor DEFAULT_TRIGGER_TASK_EXECUTOR = new TriggerTaskExecutor(5, "MessageHandler-Scheduler");
private ExecutorService executorService;
private ITriggerTaskExecutor triggerTaskExecutor;
private Queue<IMessage<H>> messages = new ConcurrentLinkedDeque<>();
private AtomicInteger size = new AtomicInteger();
private volatile Thread currentThread;
public MessageHandler(ExecutorService executorService, ITriggerTaskExecutor triggerTaskExecutor) {
super();
this.executorService = executorService;
this.triggerTaskExecutor = triggerTaskExecutor;
}
public MessageHandler() {
this(DEFAULT_EXECUTOR_SERVICE, DEFAULT_TRIGGER_TASK_EXECUTOR);
}
@SuppressWarnings("unchecked")
@Override
public void run() {
this.currentThread = Thread.currentThread();
while(true) {
IMessage<H> message = messages.poll();
if (message == null) {
break;
}
try {
long st = System.currentTimeMillis();
message.execute((H)this);
long cost = System.currentTimeMillis() - st;
if (cost > 100) {
profileLog.warn("ExecuteMessage {} cost {} ms", message.name(), cost);
}
} catch (Exception e) {
e.printStackTrace();
}
int curSize = size.decrementAndGet();
if (curSize <= 0) {
break;
}
}
}
@Override
public void addMessage(IMessage<H> message) {
messages.add(message);
int curSize = size.incrementAndGet();
if (curSize == 1) {
executorService.execute(this);
}
}
public TriggerFuture schedule(String taskName, final IMessage<H> message,
long delay, TimeUnit unit) {
TriggerFuture future = triggerTaskExecutor.schedule(taskName, new Runnable() {
@Override
public void run() {
addMessage(message);
}
}, delay, unit);
return future;
}
public TriggerFuture schedule(String taskName, final IMessage<H> message, long executeTime) {
TriggerFuture future = triggerTaskExecutor.schedule(taskName, new Runnable() {
@Override
public void run() {
addMessage(message);
}
}, executeTime);
return future;
}
public TriggerFuture scheduleAtFixedRate(String taskName, final IMessage<H> message,
long executeTime) {
TriggerFuture future = triggerTaskExecutor.schedule(taskName, new Runnable() {
@Override
public void run() {
addMessage(message);
}
}, executeTime);
return future;
}
public TriggerFuture scheduleAtFixedRate(String taskName, final IMessage<H> message,
long initialDelay, long period, TimeUnit unit ) {
TriggerFuture future = triggerTaskExecutor.scheduleAtFixedRate(taskName, new Runnable() {
@Override
public void run() {
addMessage(message);
}
}, initialDelay, period, unit);
return future;
}
public TriggerFuture scheduleWithFixedDelay(String taskName, final IMessage<H> message,
long initialDelay, long delay, TimeUnit unit) {
TriggerFuture futrue = triggerTaskExecutor.scheduleWithFixedDelay(taskName, new Runnable() {
@Override
public void run() {
addMessage(message);
}
}, initialDelay, delay, unit);
return futrue;
}
public boolean isInThread() {
return Thread.currentThread() == currentThread;
}
} |
import type { FC } from "react";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import {
TableContainer,
Table,
Thead,
Tr,
Th,
Tbody,
Td,
Radio,
Link,
Tag,
} from "@chakra-ui/react";
import { GetServerSideProps } from "next/types";
import { QueryClient, dehydrate, useQuery } from "react-query";
import { useRouter } from "next/router";
import { format } from "date-fns";
import NextLink from "next/link";
import { useTranslation, Trans } from "react-i18next";
import { ConsoleShell } from "../../../components";
import { createApiClient } from "../../../lib/createApiClient";
import { useApiClient } from "../../../hooks/useApiClient";
import { useTableControls } from "../../../hooks/useTableControls";
export const getServerSideProps: GetServerSideProps = async ({
locale,
query,
}) => {
const tenant_id = Number(query.tenant_id);
const apiClient = createApiClient();
const queryClient = new QueryClient();
await queryClient.prefetchQuery([tenant_id, "totems"], async () => {
const { data } = await apiClient.get(`/api/tenants/${tenant_id}/totems`);
return data;
});
return {
props: {
...(await serverSideTranslations(locale!, ["common"])),
dehydratedState: dehydrate(queryClient),
},
};
};
const TotemsTable: FC<{
data: {
totem_id: number;
tenant_id: number;
model_id: number;
author_id: number;
granted_at: number;
}[];
}> = ({ data }) => {
const { t } = useTranslation();
const { headerRadioProps, getRowRadioProps } = useTableControls();
return (
<TableContainer>
<Table variant="striped">
<Thead>
<Tr>
<Th>
<Radio {...headerRadioProps} />
</Th>
<Th>
<Trans t={t}>#</Trans>
</Th>
<Th>
<Trans t={t}># Author</Trans>
</Th>
<Th>
<Trans t={t}>Granted at</Trans>
</Th>
</Tr>
</Thead>
<Tbody>
{data &&
data.map(({ totem_id, tenant_id, granted_at }) => (
<Tr key={`${totem_id}/${tenant_id}`}>
<Td>
<Radio {...getRowRadioProps(totem_id, tenant_id)} />
</Td>
<Td>
<Tag variant="outline">
<pre>{totem_id}</pre>
</Tag>
</Td>
<Td>
<pre>{format(granted_at, "d.L.u k:m:s:S")}</pre>
</Td>
</Tr>
))}
</Tbody>
</Table>
</TableContainer>
);
};
export default function Totems() {
const { query } = useRouter();
const tenant_id = Number(query.tenant_id);
const apiClient = useApiClient();
const { data } = useQuery([tenant_id, "totems"], async () => {
const { data } = await apiClient.get(`/api/tenants/${tenant_id}/totems`);
return data;
});
return (
<ConsoleShell>
<TotemsTable data={data} />
</ConsoleShell>
);
} |
import React, { useContext } from 'react';
import DarkModeOutlinedIcon from '@mui/icons-material/DarkModeOutlined';
import ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';
import LightModeOutlinedIcon from '@mui/icons-material/LightModeOutlined';
import { Box, Fab, Menu, MenuItem, Typography } from '@mui/material';
import { isLightMode, Theme } from '../../contexts/ThemeProvider';
import { usePopupMenu } from '../../hooks/usePopupMenu';
import { Avatar } from '../Avatar';
export const CurrentUser = () => {
const { anchorElement, isMenuOpen, handleTriggerClick, handleMenuClose } = usePopupMenu();
const { mode, toggleThemeMode } = useContext(Theme);
const handleToggleMode = () => {
toggleThemeMode();
handleMenuClose();
};
return (
<>
<Fab variant="extended" onClick={handleTriggerClick} sx={{ boxShadow: 'none' }}>
<Avatar />
<Box
sx={{
display: 'flex',
flexDirection: 'column',
textAlign: 'left',
ml: 1,
mr: 2,
}}
>
<Typography variant="body1" sx={{ textTransform: 'none', lineHeight: 1 }}>
Jan Kowalski
</Typography>
<Typography variant="caption" sx={{ textTransform: 'none', lineHeight: 1 }}>
j.kowalski@gmail.com
</Typography>
</Box>
{isMenuOpen ? <ExpandLess /> : <ExpandMore />}
</Fab>
<Menu
anchorEl={anchorElement}
open={isMenuOpen}
onClose={handleMenuClose}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'right',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
>
<MenuItem onClick={handleToggleMode} disableRipple>
Zmień tryb na:{' '}
{isLightMode(mode) ? (
<>
ciemny <LightModeOutlinedIcon sx={{ ml: 1 }} />
</>
) : (
<>
jasny <DarkModeOutlinedIcon sx={{ ml: 1 }} />
</>
)}
</MenuItem>
</Menu>
</>
);
}; |
package com.example.flashlight
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.content.getSystemService
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val onButton= findViewById<Button>(R.id.flash_on_btn)
val ofButton=findViewById<Button>(R.id.flash_of_btn)
onButton.setOnClickListener{
onFlash()
}
ofButton.setOnClickListener{
offFlash()
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun onFlash(){
var cameraManager: CameraManager?=null
cameraManager = getSystemService(CAMERA_SERVICE)as CameraManager
try {
var cameraId : String? = null
cameraId = cameraManager.cameraIdList[0]
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
cameraManager!!.setTorchMode(cameraId, true)
Toast.makeText(this,"Flash ON",Toast.LENGTH_SHORT).show()
}
}catch (e:CameraAccessException){
/* Toast.makeText(this,"Exception:"+e.message).show()*/
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun offFlash(){
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
val cameraManager= getSystemService(CAMERA_SERVICE) as CameraManager
try {
val cameraId = cameraManager.cameraIdList[0]
cameraManager.setTorchMode(cameraId,false)
Toast.makeText(this,"Flash OFF",Toast.LENGTH_SHORT).show()
}catch (e:CameraAccessException){
}
}
}
} |
from functools import partial
from typing import Iterable, List, Optional
import attrs
import pandas as pd
import spacy
from .base import Transformer
@attrs.define
class DummySentenceTokenizer(Transformer):
"""
Initialize Dummy Sentence Tokenizer.
Attributes
----------
input_column : str
Name of column with target text to split into sentences.
output_column : str, default to "sentences"
Name of column to hold the sentences.
explode : bool
Whether to explode dataframe to have one sentence per row or not.
original_index_column : str, default to "invoice_file_id"
Name of column to store old indices after exploding dataframe.
"""
input_column: str
output_column: str = attrs.field(default="sentences")
explode: bool = attrs.field(default=True)
original_index_column: str = attrs.field(default="invoice_file_id")
split_token: str = attrs.field(default="\n")
def fit(self, X: pd.DataFrame, y: Optional[Iterable] = None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
"""Split text into sentences."""
X[self.output_column] = X[self.input_column].apply(lambda t: t.split(self.split_token))
if self.explode:
X = X.explode(self.output_column)
X.reset_index(names=self.original_index_column, inplace=True)
return X
def inverse_transform(self, X: pd.DataFrame) -> pd.DataFrame:
"""Drop column with sentences."""
X.drop(columns=self.output_column, inplace=True)
return X
@attrs.define
class SpacyTokenizer(Transformer):
r"""
Tokenize text with Spacy.
Attributes
----------
input_column : str
Name of column with input text.
output_column : str, default to "tokens"
Name of column to hold the output from Spacy's pipeline.
nlp_pipeline : `spacy.language.Language`
Spacy's pipeline.
remove_stopwords : bool
Whether to remove stopwords or not.
extra_stopwords : list of str
Extra stop words.
"""
input_column: str
output_column: str = attrs.field(default="tokens")
nlp_pipeline: spacy.language.Language = attrs.field(
factory=partial(spacy.load, "en_core_web_trf")
)
clean_tokens: bool = attrs.field(default=True)
remove_stopwords: bool = attrs.field(default=True)
extra_stopwords: List[str] = attrs.field(factory=list)
def fit(self, X: pd.DataFrame, y: Optional[Iterable] = None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
"""Apply tokenization."""
X[self.output_column] = X[self.input_column].apply(self._tokenize)
return X
def inverse_transform(self, X: pd.DataFrame) -> pd.DataFrame:
"""Drop column with tokenization result."""
X.drop(columns=self.output_column, inplace=True)
return X
def _tokenize(self, text) -> List[str]:
"""Tokenize text."""
tokens = []
for tok in self.nlp_pipeline(
text,
disable=[
"tagger",
"parser",
"attribute_ruler",
"ner",
],
):
clean_token = tok.text
if self.clean_tokens:
clean_token = tok.lemma_.lower()
if not self.remove_stopwords or (
not tok.is_stop and clean_token not in self.extra_stopwords
):
tokens.append(clean_token)
return tokens
@attrs.define
class SpacySentenceTokenizer(SpacyTokenizer):
r"""
Spacy sentence tokenizer.
Attributes
----------
input_column : str
Name of column with input text.
output_column : str, default to "tokens"
Name of column to hold the output from Spacy's pipeline.
nlp_pipeline : `spacy.language.Language`
Spacy's pipeline.
remove_stopwords : bool
Whether to remove stopwords or not.
extra_stopwords : list of str
Extra stop words.
"""
def __attrs_post_init__(self):
self.nlp_pipeline.add_pipe("sentencizer")
def _tokenize(self, text) -> List[str]:
"""Tokenize text."""
doc = self.nlp_pipeline(
text,
disable=[
"tagger",
"parser",
"attribute_ruler",
"ner",
],
)
sentences = []
for sent in doc.sents:
tokens = []
for tok in sent:
clean_token = tok.text
if self.clean_tokens:
clean_token = tok.lemma_.lower()
if not self.remove_stopwords or (
not tok.is_stop and clean_token not in self.extra_stopwords
):
tokens.append(clean_token)
sentences.append(tokens)
return sentences |
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution {
public:
bool is_palin(string &s){
// int a=0;
// for(int i=0;i<s.size();i++){
// a ^= (1<<s[i]-'a');
// }
// if(a & a-1 != 0)return false;
// return true;
return (s==string(s.rbegin(),s.rend()));
}
void find_palin(string &s, vector<string>&temp , vector<vector<string>>&tr,int i, int n){
if(i==n){
tr.push_back(temp);
return;
}
for(int k=i;k<n;k++){
string str=s.substr(i,k-i+1);
if(is_palin(str)){
temp.push_back(str);
find_palin(s,temp,tr,k+1,n);
temp.pop_back();
}
}
}
vector<vector<string>> allPalindromicPerms(string s) {
// code here
int n=s.size();
vector<vector<string>>tr;
vector<string>temp;
find_palin(s,temp,tr,0,n);
return tr;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
string S;
cin>>S;
Solution ob;
vector<vector<string>> ptr = ob.allPalindromicPerms(S);
for(int i=0; i<ptr.size(); i++)
{
for(int j=0; j<ptr[i].size(); j++)
{
cout<<ptr[i][j]<<" ";
}
cout<<endl;
}
}
return 0;
}
// } Driver Code Ends |
## DBsubject(Calculus - multivariable)
## DBchapter(Differentiation of multivariable functions)
## DBsection(Directional derivatives and the gradient)
## Institution(W.H.Freeman)
## Author(JustAsk - Vladimir Finkelshtein)
## MLT(DirDerivAtPt)
## Level(3)
## MO(1)
## TitleText1('Calculus: Early Transcendentals')
## AuthorText1('Rogawski')
## EditionText1('2')
## Section1('14.5')
## Problem1('25')
## KEYWORDS('calculus')
DOCUMENT();
loadMacros(
"PGstandard.pl",
"Parser.pl",
"freemanMacros.pl",
"PGgraphmacros.pl",
"PGchoicemacros.pl",
"PGcourse.pl"
);
TEXT(beginproblem());
Context()->texStrings;
$n=random(1,4);
if ($n==1)
{$func='asin';
$funcder='1/sqrt(1-(x*y)^2)';}
if ($n==2)
{$func='acos';
$funcder='-1/sqrt(1-(x*y)^2)';}
if ($n==3)
{$func='atan';
$funcder='1/(1+(x*y)^2)';}
if ($n==4)
{$func='acot';
$funcder='-1/(1+(x*y)^2)';}
$x=non_zero_random(0.5,0.9,1);
$y=non_zero_random(0.5,0.9,1);
$i=non_zero_random(-5,5,1);
$j=non_zero_random(-5,5,1);
$i1=$i;
if ($i1==1){$i1='';}
if ($i1==-1){$i1='-';}
$j1=$j;
if ($j1==1){$j1='';}
if ($j1==-1){$j1='-';}
$norm2=($i)**2+($j)**2;
$context = Context();
$context->variables->add(y=>'Real');
$funcder1=Formula("$funcder");
$f=Formula("$func(x*y)")->reduce();
$fx=Formula("y*$funcder")->reduce();
$fy=Formula("x*$funcder")->reduce();
$gradx=$fx->eval(x=>$x, y=>$y);
$grady=$fy->eval(x=>$x, y=>$y);
$dernum=$gradx*$i+$grady*$j;
$der=($gradx*$i+$grady*$j)/sqrt($norm2);
BEGIN_TEXT
\{ textbook_ref_exact("Rogawski ET 2e", "14.5","25") \}
$PAR
Calculate the directional derivative of \(f(x,y)=$f\) in the direction of \(\mathbf{v}=$i1 \mathbf{i}+$j1\mathbf{j}\) at the point \(P=($x,$y)\). Remember to normalize the direction vector.
$PAR
\( D_uf($x,$y)=\) \{ans_rule()\}
$BR
END_TEXT
Context()->normalStrings;
ANS($der->cmp);
Context()->texStrings;
SOLUTION(EV3(<<'END_SOLUTION'));
$PAR
$SOL
$BR
We first normalize \(\mathbf{v}\) to obtain a unit vector \(\mathbf{u}\) in the direction of \(\mathbf{v}\):
\[\mathbf{u}=\frac{\mathbf{v}}{||\mathbf{v}||}=\frac{1}{\sqrt{$norm2}}($i1\mathbf{i} +$j1 \mathbf{j})\]
We compute the gradient of \(f(x,y)=$f\) at the point \(P=($x,$y)\):
\[\nabla f=\left< \frac{\partial{f}}{\partial{x}}, \frac{\partial{f}}{\partial{y}} \right>=\left<$fx,$fy\right>=$funcder1\left<y,x\right>\]
\[\nabla f($x,$y)\approx \left<$gradx, $grady\right>\]
The directional derivative in the direction \(\mathbf{v}\) is thus
\[\begin{array}{rcl}
D_uf($x,$y)&=&\nabla f($x,$y) \cdot \mathbf{u}\\
&\approx& \left< $gradx, $grady \right> \cdot \frac{1}{\sqrt{$norm2}} \left<$i, $j\right>\\
&\approx& \frac{$dernum}{\sqrt{$norm2}}\approx $der
\end{array}\]
$BR
END_SOLUTION
ENDDOCUMENT(); |
<?php
class AdornEdgeSideAreaOpener extends AdornEdgeWidget {
public function __construct() {
parent::__construct(
'edge_side_area_opener',
esc_html__('Edge Side Area Opener', 'adorn'),
array( 'description' => esc_html__( 'Display a "hamburger" icon that opens the side area', 'adorn'))
);
$this->setParams();
}
protected function setParams() {
$this->params = array(
array(
'type' => 'textfield',
'name' => 'icon_color',
'title' => esc_html__('Side Area Opener Color', 'adorn'),
'description' => esc_html__('Define color for side area opener', 'adorn')
),
array(
'type' => 'textfield',
'name' => 'icon_hover_color',
'title' => esc_html__('Side Area Opener Hover Color', 'adorn'),
'description' => esc_html__('Define hover color for side area opener', 'adorn')
),
array(
'type' => 'textfield',
'name' => 'widget_margin',
'title' => esc_html__('Side Area Opener Margin', 'adorn'),
'description' => esc_html__('Insert margin in format: top right bottom left (e.g. 10px 5px 10px 5px)', 'adorn')
),
array(
'type' => 'textfield',
'name' => 'widget_title',
'title' => esc_html__('Side Area Opener Title', 'adorn')
)
);
}
public function widget($args, $instance) {
$holder_styles = array();
if (!empty($instance['icon_color'])) {
$holder_styles[] = 'color: ' . $instance['icon_color'].';';
}
if (!empty($instance['widget_margin'])) {
$holder_styles[] = 'margin: ' . $instance['widget_margin'];
}
?>
<a class="edge-side-menu-button-opener edge-icon-has-hover" <?php echo adorn_edge_get_inline_attr($instance['icon_hover_color'], 'data-hover-color'); ?> href="javascript:void(0)" <?php adorn_edge_inline_style($holder_styles); ?>>
<?php if (!empty($instance['widget_title'])) { ?>
<h5 class="edge-side-menu-title"><?php echo esc_html($instance['widget_title']); ?></h5>
<?php } ?>
<span class="edge-side-menu-lines">
<span class="edge-side-menu-line edge-line-1"></span>
<span class="edge-side-menu-line edge-line-2"></span>
<span class="edge-side-menu-line edge-line-3"></span>
</span>
</a>
<?php }
} |
# Send Get Requests
```javascript
import React, {useState} from 'react';
import MoviesList from './components/MoviesList';
import './App.css';
function App() {
const [movies, setMovies] = useState([]);
function fetchMoviesHandler () {
fetch('https://swapi.dev/api/films')
.then(response => {
return response.json();
})
.then((data)=>{
const trasnformedMovies = data.results.map(movieData=>{
return {
id:movieData.episode_id,
title: movieData.title,
openingText: movieData.opening_crawl,
releaseDate: movieData.release_date
}
})
setMovies(trasnformedMovies)
});
}
return (
<React.Fragment>
<section>
<button onClick={fetchMoviesHandler}>Fetch Movies</button>
</section>
<section>
<MoviesList movies={movies} />
</section>
</React.Fragment>
);
}
export default App;
```
Using async/await
```javascript
import React, {useState} from 'react';
import MoviesList from './components/MoviesList';
import './App.css';
function App() {
const [movies, setMovies] = useState([]);
async function fetchMoviesHandler () {
const response = await fetch('https://swapi.dev/api/films')
const data = await response.json();
const trasnformedMovies = data.results.map(movieData=>{
return {
id:movieData.episode_id,
title: movieData.title,
openingText: movieData.opening_crawl,
releaseDate: movieData.release_date
}
})
setMovies(trasnformedMovies)
}
return (
<React.Fragment>
<section>
<button onClick={fetchMoviesHandler}>Fetch Movies</button>
</section>
<section>
<MoviesList movies={movies} />
</section>
</React.Fragment>
);
}
export default App;
```
# Firebase
Firebase: create a back end + database : a full backend app and complete rest API
- Create project
- Real time database
- Create database
- Take the link provided and add something : https://react-http-26861-default-rtdb.firebaseio.com/ + movies.json
Then you can send GET and POST request to the firebase backend
```javascript
import React, { useState, useEffect, useCallback } from 'react';
import MoviesList from './components/MoviesList';
import AddMovie from './components/AddMovie';
import './App.css';
function App() {
const [movies, setMovies] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const fetchMoviesHandler = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const response = await fetch('https://react-http-26861-default-rtdb.firebaseio.com/movies.json');
if (!response.ok) {
throw new Error('Something went wrong!');
}
const data = await response.json();
const loadedMovies = [];
for (const key in data) {
loadedMovies.push({
id: key,
title: data[key].title,
openingText: data[key].openingText,
releaseDate: data[key].releaseDate,
});
}
setMovies(loadedMovies);
} catch (error) {
setError(error.message);
}
setIsLoading(false);
}, []);
useEffect(() => {
fetchMoviesHandler();
}, [fetchMoviesHandler]);
async function addMovieHandler(movie) {
const response = await fetch('https://react-http-26861-default-rtdb.firebaseio.com/movies.json', {
method: 'POST',
body: JSON.stringify(movie),
headers: {
'Content-Type': 'application/json'
}
});
const data = await response.json()
console.log(data)
}
let content = <p>Found no movies.</p>;
if (movies.length > 0) {
content = <MoviesList movies={movies} />;
}
if (error) {
content = <p>{error}</p>;
}
if (isLoading) {
content = <p>Loading...</p>;
}
return (
<React.Fragment>
<section>
<AddMovie onAddMovie={addMovieHandler} />
</section>
<section>
<button onClick={fetchMoviesHandler}>Fetch Movies</button>
</section>
<section>{content}</section>
</React.Fragment>
);
}
export default App;
``` |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strmapi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: eboumaza <eboumaza.trav@gmail.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/08/14 14:21:35 by eboumaza #+# #+# */
/* Updated: 2023/08/14 14:21:35 by eboumaza ### ########.fr */
/* */
/* ************************************************************************** */
#include "../libft.h"
char *ft_strmapi(char const *s, char (*f)(unsigned int, char))
{
char *str;
size_t i;
i = 0;
if (s == NULL || f == NULL)
return (NULL);
str = malloc(sizeof(char) * ft_strlen(s) + 1);
if (str == NULL)
return (NULL);
while (s[i])
{
str[i] = f((unsigned int)i, s[i]);
i++;
}
str[i] = '\0';
return (str);
} |
import fs from 'fs';
// https://adventofcode.com/2021/day/17
interface Range { min: number, max: number }
interface Area { x: Range, y: Range }
export function load(filename: string) {
return fs.readFileSync(filename, { encoding: 'utf-8' })
.replace('target area:', '').trim().split(', ')
.reduce((out, line) => {
const [axis, range] = line.split('=');
const [min, max] = range.split('..');
out[axis as 'x'|'y'].min = parseInt(min);
out[axis as 'x'|'y'].max = parseInt(max);
return out;
}, {x: {min: 0, max: 0}, y: { min: 0, max: 0}});
}
const targetArea = load('input.txt')
interface Vector {
x: number,
y: number,
dx: number,
dy: number
}
function step(velocity: Vector) {
return {
x: velocity.x + velocity.dx,
y: velocity.y + velocity.dy,
dx: velocity.dx === 0 ? 0 : velocity.dx - (velocity.dx / Math.abs(velocity.dx)),
dy: velocity.dy - 1
}
}
function test(targetArea: Area, dx: number, dy: number) {
let velocity = { x: 0, y: 0, dx, dy };
let maxY = -Infinity;
while (velocity.x <= targetArea.x.max && velocity.y >= targetArea.y.min) {
maxY = Math.max(velocity.y, maxY);
if (velocity.x >= targetArea.x.min && velocity.y <= targetArea.y.max) {
return maxY;
}
velocity = step(velocity);
}
return undefined;
}
function generateRanges(targetArea: Area) {
let maxY = -Infinity;
for (let x = 0; x <= Math.ceil(targetArea.x.max / 4); x++) {
for (let y = 1000; y > -1000; y--) {
const result = test(targetArea, x, y);
if (result !== undefined) {
maxY = Math.max(maxY, result);
}
}
}
console.log('part 1:', maxY);
}
generateRanges(targetArea); |
<!--
// Copyright © 2020 Anticrm Platform Contributors.
//
// Licensed under the Eclipse Public License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. You may
// obtain a copy of the License at https://www.eclipse.org/legal/epl-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.
-->
<script lang="ts">
import type { IntlString } from '@hcengineering/platform'
import { translate } from '@hcengineering/platform'
import plugin from '../plugin'
import Label from './Label.svelte'
import { themeStore } from '@hcengineering/theme'
export let label: IntlString | undefined = undefined
export let width: string | undefined = undefined
export let height: string | undefined = undefined
export let margin: string | undefined = undefined
export let value: string | undefined = undefined
export let placeholder: IntlString = plugin.string.EditBoxPlaceholder
export let placeholderParam: any | undefined = undefined
export let noFocusBorder: boolean = false
export let disabled: boolean = false
let input: HTMLTextAreaElement
let phTraslate: string = ''
$: translate(placeholder, placeholderParam ?? {}, $themeStore.language).then((res) => {
phTraslate = res
})
export function focus () {
input.focus()
}
</script>
<div class="textarea" class:no-focus-border={noFocusBorder} style:width style:height style:margin>
{#if label}<div class="label"><Label {label} /></div>{/if}
<textarea
bind:value
bind:this={input}
{disabled}
placeholder={phTraslate}
on:keydown
on:change
on:keydown
on:keypress
on:blur
/>
</div>
<style lang="scss">
.textarea {
display: flex;
flex-direction: column;
min-width: 3.125rem;
min-height: 2.25rem;
.label {
margin-bottom: 0.25rem;
font-size: 0.75rem;
font-weight: 500;
color: var(--accent-color);
pointer-events: none;
user-select: none;
}
textarea {
width: auto;
min-height: 4.5rem;
margin: -4px;
padding: 2px;
font-family: inherit;
font-size: inherit;
line-height: 150%;
color: var(--caption-color);
background-color: transparent;
border: 2px solid transparent;
border-radius: 0.125rem;
outline: none;
overflow-y: scroll;
resize: none;
&:focus {
border-color: var(--primary-button-default);
}
&::placeholder {
color: var(--dark-color);
}
}
}
.no-focus-border {
textarea {
font-weight: 500;
font-size: 1rem;
&:focus {
border-color: transparent;
}
}
}
</style> |
int a = 1; //input, skal skrives manuelt da processing ikke har en inputfunktion
int x = 2;
int b = 3;
int y = 5;
int testX1; int testY1; //initierer to (x,y) koordinater til linjen der,
int testX2; int testY2; //skal gå fra venstre side af skærmen til højre
void setup() {
size(1000, 1000);
background(255, 110, 148);
int testX1 = 0-(width/2); //da koordinatsystemets origo senere rykket til (500,500) skal linjens x starte i origo minus 500
int testY1 = (a * testX1 + b)*-1;
int testX2 = width; //der er principielt ikke brug for at linjen går så langt, man man kan ikke se det så det er ligemeget
int testY2 = (a * testX2 + b)*-1;
line(width/2, 0, width/2, height);
line(0, height/2, width, height/2); //tegner rigtigt koordinatsystem
pushMatrix();
translate(width/2, height/2); //rykker linjen og punktet's origo til midten af skærmen
scale(4); //skalerer linjen så vi rent faktisk kan se hvad der sker med punktet og linjen med de små numre
stroke(254);
line(testX1, testY1, testX2, testY2); //linjen tegnes ud fra de to (x,y)-koordinater
circle(x, y*-1, 1); //punktet tegnes
popMatrix();
determineOutput(); //skriver om punktet ligger over, under, eller på linjen. Se nedenfor for funktion, bare et if/elseif-statement
}
void determineOutput() {
textSize(100);
if (y > a*x+b) {text("OVER", 550, 250);}
else if (y < a*x+b) {text("UNDER", 550, 250);}
else {text("YOU HIT!", 550, 250);}
} |
/**
* refracta - 마이크로프로세서및실습 (CSE124-02)
* 과제 3 IR Sensor 소스 코드
*/
#include <IRremote.h>
#include <LiquidCrystal.h>
#define BUZZER_PIN 10
#define RECEIVE_PIN 7
#define LC_D0_PIN 5
#define LC_D1_PIN 4
#define LC_D2_PIN 3
#define LC_D3_PIN 2
#define LC_ENABLE_PIN 11
#define LC_RS_PIN 12
#define IR_CH_MINUS 0xFFA25D
#define IR_CH 0xFF629D
#define IR_CH_PLUS 0xFFE21D
#define IR_PREV 0xFF22DD
#define IR_NEXT 0xFF02FD
#define IR_PAUSE 0xFFC23D
#define IR_MINUS 0xFFE01F
#define IR_PLUS 0xFFA857
#define IR_EQ 0xFF906F
#define IR_0 0XFF6897
#define IR_100 0xFF9867
#define IR_200 0xFFB04F
#define IR_1 0xFF30CF
#define IR_2 0xFF18E7
#define IR_3 0xFF7A85
#define IR_4 0xFF10EF
#define IR_5 0xFF38C7
#define IR_6 0xFF5AA5
#define IR_7 0xFF42BD
#define IR_8 0xFF4AB5
#define IR_9 0xFF52AD
#define IR_NUM_OF_BUTTONS 21
int BUTTON_VALUES[] = {IR_CH_MINUS, IR_CH, IR_CH_PLUS, IR_PREV, IR_NEXT, IR_PAUSE, IR_MINUS, IR_PLUS, IR_EQ, IR_0,
IR_100, IR_200, IR_1, IR_2, IR_3, IR_4, IR_5, IR_6, IR_7, IR_8, IR_9};
char CALCULATOR_SYMBOLS[] = {'E', '(', ')', 'B', 'C', '/', '-', '+', '*', '0', '<', '>', '1', '2', '3', '4', '5', '6',
'7', '8', '9'};
char toChar(int signal) {
for (int i = 0; i < IR_NUM_OF_BUTTONS; i++) {
if (BUTTON_VALUES[i] == signal) {
return CALCULATOR_SYMBOLS[i];
}
}
return '\0';
}
LiquidCrystal lcd(LC_RS_PIN, LC_ENABLE_PIN, LC_D0_PIN, LC_D1_PIN, LC_D2_PIN, LC_D3_PIN);
IRrecv irr(RECEIVE_PIN);
decode_results results;
#define SUCCESS_TUNE() playTone('g', 5, 200);
#define FAIL_TUNE() playTone('F', 6, 100); playTone('F', 6, 100);
/*
* data from https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody
* 아두이노 튜토리얼 문서의 헤더 파일을 배열 형태로 정리한 것, 각 음계의 진동수의 상수 정의이다.
*/
const int frequencies[] =
{
31, // octave 0
33, 35, 37, 39, 41, 44, 46, 49, 52, 55, 58, 62, // octave 1
65, 69, 73, 78, 82, 87, 93, 98, 104, 110, 117, 123, // octave 2
131, 139, 147, 156, 165, 175, 185, 196, 208, 220, 233, 247, // octave 3
262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494, // octave 4
523, 554, 587, 622, 659, 698, 740, 784, 831, 880, 932, 988, // octave 5
1047, 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661, 1760, 1865, 1976, // octave 6
2093, 2217, 2349, 2489, 2637, 2794, 2960, 3136, 3322, 3520, 3729, 3951, // octave 7
4186, 4435, 4699, 4978 // octave 8
};
// "도 도# 레 레# 미 파 파# 솔 솔# 라 라# 시" 순의 출력 처리용 character 배열
const char notes[] = {'c', 'C', 'd', 'D', 'e', 'f', 'F', 'g', 'G', 'a', 'A', 'b'}; // length = 12
// note에 해당하는 notes의 index를 반환한다.
int getNoteIndex(char note) {
for (int i = 0; i < 12; i++) {
if (notes[i] == note) {
return i;
}
}
return -1;
}
// note, octave의 출력으로 duration 동안 부저에 소리를 출력하는 함수
void playTone(char note, int octave, int duration) {
int frequency = frequencies[getNoteIndex(note) - 11 + octave * 12];
tone(BUZZER_PIN, frequency, duration);
delay(duration);
noTone(BUZZER_PIN);
}
int getReceiveSignal() {
int value = 0;
if (irr.decode(&results)) {
if (results.decode_type == NEC) {
value = results.value;
}
irr.resume();
}
return value;
}
char screen[32] = {0,};
int cursor = 0;
void clear(bool withZero) {
for (int i = 0; i < 32; i++) {
screen[i] = 0;
}
lcd.clear();
if (withZero) {
lcd.print('0');
}
lcd.home();
cursor = 0;
}
#define IS_ADD_TYPE(c) ((c) == '+' || (c) == '-')
#define IS_MULTI_TYPE(c) ((c) == '*' || (c) == '/')
#define IS_OPERATOR(c) (IS_ADD_TYPE(c) || IS_MULTI_TYPE(c))
#define IS_PARENTHESES(c) ((c) == ')' || (c) == ')')
#define IS_DIGIT(c) ('0' <= (c) && (c) <= '9')
#define STACK_SIZE 64
// 주어진 표현식의 소괄호 쌍이 닫혀있는지 검사한다.
bool isValidParentheses(char *target) {
int length = strlen(target);
if (length == 0) { return true; }
// if (length % 2 == 1) { return false; }
char stack[32] = {0,};
int stackCursor = 0;
for (int i = 0; i < length; i++) {
char c = target[i];
if (c == '(') {
stack[stackCursor++] = c;
} else if (c == ')') {
if (stackCursor == 0) {
return false;
} else {
stack[--stackCursor] = '\0';
}
}
}
return stackCursor == 0;
}
// 주어진 표현식을 검증한다. (소괄호 쌍 검사, 연산자와 피연산자가 올바른 형태로 나타났는지 검사)
bool isValidExpression(char *target) {
if (!isValidParentheses(target)) {
return false;
}
int operatorCount = 0;
int operandCount = 0;
char prev = '(';
int length = strlen(target);
for (int i = 0; i < length; i++) {
char c = target[i];
if (IS_OPERATOR(c)) {
if (operandCount == 0) {
return false;
}
operandCount = 0;
++operatorCount;
if (operatorCount > 1) {
return false;
}
} else if (!IS_DIGIT(prev) && IS_DIGIT(c)) {
operatorCount = 0;
++operandCount;
if (operandCount > 1) {
return false;
}
}
prev = c;
}
return operatorCount == 0;
}
// 함수 포인터로 이용되는 표현식 계산 소기능 함수들
bool isOperatorPredicate(char c) {
return IS_OPERATOR(c);
}
bool isLPPredicate(char c) {
return c == '(';
}
bool isMultiTypePredicate(char c) {
return IS_MULTI_TYPE(c);
}
bool isLPAndAddTypePredicate(char c) {
return c == '(' || IS_ADD_TYPE(c);
}
bool alwaysFalsePredicate(char c) {
return false;
}
String postfix;
// stack에서 postfix String에 덧붙일 요소들을 이동시킨다.
int moveOperatorsToPostfix(char *stack, int stackCursor, bool (*pushPredicate)(char), bool (*stopPredicate)(char)) {
int originalStackCursor = stackCursor;
while (stackCursor != 0) {
char top = stack[stackCursor - 1];
if (pushPredicate(top)) {
postfix += top;
postfix += ' ';
stackCursor--;
} else if (stopPredicate(top)) {
break;
}
}
return stackCursor - originalStackCursor;
}
// infix 표현식을 postfix 형태로 변환시킨다.
String toPostfix(char *infix) {
postfix = "";
char stack[STACK_SIZE];
int stackCursor = 0;
int length = strlen(infix);
int n = 0;
bool processingDigit = false;
for (int i = 0; i < length; i++) {
char c = infix[i];
if (IS_DIGIT(c)) {
processingDigit = true;
n = (c - '0') + n * 10;
} else if (c == '(') {
stack[stackCursor++] = c;
} else if (c == ')' || IS_OPERATOR(c)) {
if (processingDigit) {
postfix += String(n) + " ";
n = 0;
processingDigit = false;
}
if (IS_OPERATOR(c)) {
if (stackCursor == 0) {
stack[stackCursor++] = c;
} else {
if (IS_ADD_TYPE(c)) {
stackCursor += moveOperatorsToPostfix(stack, stackCursor, isOperatorPredicate, isLPPredicate);
} else {
stackCursor += moveOperatorsToPostfix(stack, stackCursor, isMultiTypePredicate,
isLPAndAddTypePredicate);
}
stack[stackCursor++] = c;
}
} else {
stackCursor += moveOperatorsToPostfix(stack, stackCursor, isOperatorPredicate, isLPPredicate);
int top = stack[stackCursor - 1];
if (top == '(') { stackCursor--; }
}
}
}
if (processingDigit) {
postfix += String(n) + " ";
}
stackCursor += moveOperatorsToPostfix(stack, stackCursor, isOperatorPredicate, alwaysFalsePredicate);
postfix = postfix.substring(0, postfix.length() - 1);
return postfix;
}
// postfix 형태를 가지는 표현식의 실제 연산 결과를 얻는다.
int evaluatePostfix(String postfix) {
int stack[STACK_SIZE];
int stackCursor = 0;
int n = 0;
bool processingDigit = false;
int length = postfix.length();
for (int i = 0; i < length; i++) {
char c = postfix[i];
if (IS_DIGIT(c)) {
processingDigit = true;
n = (c - '0') + n * 10;
} else if (c == ' ') {
if (processingDigit) {
stack[stackCursor++] = n;
n = 0;
processingDigit = false;
}
} else if (IS_OPERATOR(c)) {
int n2 = stack[--stackCursor];
int n1 = stack[--stackCursor];
switch (c) {
case '+':
stack[stackCursor++] = n1 + n2;
break;
case '-':
stack[stackCursor++] = n1 - n2;
break;
case '*':
stack[stackCursor++] = n1 * n2;
break;
default:
stack[stackCursor++] = n1 / n2;
break;
}
}
}
return stack[--stackCursor];
}
bool evalStatus = true;
// 계산기 표현식을 매개변수로 받아 해당 표현식의 평가값을 반환한다. 구문, 문법 오류가 나지 않으면 evalStatus의 값을 false로, 오류가 나면 true로 변경한다.
int evaluate(char *target) {
if (!isValidExpression(target)) {
evalStatus = false;
return 0;
} else {
evalStatus = true;
return evaluatePostfix(toPostfix(target));
}
}
// 현재 계산기 화면을 직렬 통신 출력으로 내보낸다.
void printToSerial() {
Serial.println("<CalculatorScreen>");
Serial.print('[');
for (int i = 0; i < 16; i++) {
if (screen[i]) {
Serial.print(screen[i]);
} else {
Serial.print(' ');
}
}
Serial.println(']');
Serial.print('[');
for (int i = 16; i < 32; i++) {
if (screen[i]) {
Serial.print(screen[i]);
} else {
Serial.print(' ');
}
}
Serial.println(']');
}
// LCD, IR 수신부 초기화
void setup() {
lcd.begin(16, 2);
lcd.blink();
clear(true);
irr.enableIRIn();
Serial.begin(9600);
}
int eval = 0;
bool waitClear = false;
// 사용자의 계산기 입력이 처리되는 루프
void loop() {
lcd.cursor();
char input = toChar(getReceiveSignal());
if (input) {
if (waitClear) {
waitClear = false;
clear(true);
}
switch (input) {
case 'C':
// Clear
SUCCESS_TUNE();
clear(true);
break;
case 'B':
// Backspace
if (cursor > 0) {
SUCCESS_TUNE();
if (screen[cursor] && cursor < 32) {
int c = cursor;
for (; c < 32; c++) {
if (screen[c]) {
screen[c - 1] = screen[c];
lcd.setCursor((c - 1) % 16, (c - 1) / 16);
lcd.print(screen[c - 1]);
} else {
break;
}
}
screen[c - 1] = '\0';
if (c - 2 == 15) {
lcd.setCursor(0, 1);
}
lcd.print(' ');
cursor--;
lcd.setCursor(cursor % 16, cursor / 16);
} else {
cursor--;
screen[cursor] = '\0';
lcd.setCursor(cursor % 16, cursor / 16);
lcd.print(' ');
lcd.setCursor(cursor % 16, cursor / 16);
}
} else {
FAIL_TUNE();
}
break;
case 'E':
// Enter
if (cursor == 0 && !screen[cursor]) {
FAIL_TUNE();
return;
}
eval = evaluate(screen);
clear(false);
lcd.noBlink();
if (evalStatus) {
SUCCESS_TUNE();
lcd.print("=");
lcd.print(eval);
Serial.print("EVAL: ");
Serial.println(eval);
} else {
FAIL_TUNE();
lcd.print("SYNTAX ERROR!");
Serial.println("EVAL: SYNTAX ERROR!");
}
waitClear = true;
break;
case '<':
// 커서 왼쪽으로 옮기기
if (0 < cursor) {
SUCCESS_TUNE();
cursor--;
lcd.setCursor(cursor % 16, cursor / 16);
} else {
FAIL_TUNE();
}
break;
case '>':
// 커서 오른쪽으로 옮기기
if (cursor < 32 - 1 && screen[cursor]) {
SUCCESS_TUNE();
cursor++;
lcd.setCursor(cursor % 16, cursor / 16);
} else {
FAIL_TUNE();
}
break;
default:
// 비기능 키 입력 구현
if (cursor < 32) {
SUCCESS_TUNE();
lcd.print(input);
if (cursor == 15) {
lcd.setCursor(0, 1);
}
screen[cursor] = input;
cursor++;
} else {
FAIL_TUNE();
}
break;
}
printToSerial();
}
} |
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Tir\Crud\Support\Scaffold\BaseScaffold;
use Tir\Crud\Support\Scaffold\Fields\Button;
use Tir\Crud\Support\Scaffold\Fields\FileUploader;
use Tir\Crud\Support\Scaffold\Fields\Editor;
use Tir\Crud\Support\Scaffold\Fields\TextArea;
use Tir\Crud\Support\Scaffold\Fields\Text;
use Tir\Crud\Support\Scaffold\Fields\Select;
use Tir\Crud\Support\Scaffold\Fields\Group;
use Tir\Crud\Support\Scaffold\Fields\Blank;
use Tir\Crud\Support\Scaffold\Fields\DatePicker;
use Tir\Crud\Support\Scaffold\Fields\Number;
use Tir\Crud\Support\Scaffold\Fields\ColorPicker;
use Tir\Crud\Support\Scaffold\Fields\Custom;
use Tir\Crud\Support\Scaffold\Fields\Slug;
use Tir\Crud\Support\Scaffold\Fields\SwitchBox;
class Message extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
use BaseScaffold;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'job',
'email',
'phone',
'subject',
'message',
'status',
'interested',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [];
protected function setModuleName(): string
{
return 'message';
}
protected function setAcl(): string
{
return false;
}
protected function setActions(): array
{
return [
'create' => false,
'edit' => false,
'destroy' => false,
'fullDestroy' => false,
];
}
protected function setFields(): array
{
return [
Group::make('left-col')->display('')->children(
Text::make('name')->rules('required'),
Text::make('job')->rules('required')->hideFromIndex(),
Text::make('email')->rules('required'),
Text::make('interested')->rules('required')->hideFromIndex(),
)->col(17)->hideFromIndex(),
Group::make('right-col')->display('')->children(
Select::make('status')->data(
['value' => 'Read', 'label' => 'Read'],
['value' => 'UnRead', 'label' => 'UnRead'],
)->default('Published')->rules('required')->filter()->onlyOnIndex(),
)->col(7)->hideFromIndex(),
DatePicker::make('created_at')->disable()->format('yy M d')->onlyOnIndex()->filter(),
Custom::make('reading')->type('CustomReading')->hideFromIndex(),
];
}
// protected function setButtons(): array
// {
// return [
// Button::make('cancel')->action('Cancel')->path('/admin/post'),
// Button::make('submit')->action('Submit'),
// ];
// }
} |
#ifndef BINARYTREE_H_INCLUDED
#define BINARYTREE_H_INCLUDED
#include <algorithm>
#include <cmath>
template <typename T>
struct Node {
T data;
Node<T>* left;
Node<T>* right;
Node(T data) {
this->data = data;
this->left = nullptr;
this->right = nullptr;
}
};
template <typename T>
class BinaryTree {
private:
Node<T>* root;
public:
BinaryTree() : root(nullptr) {}
// Return the root of the tree
Node<T>* getRoot() {
return this->root;
}
// Insert a node into the tree
void insert(Node<T>* node, T data) {
if (node == nullptr) {
this->root = new Node<T>(data);
return;
}
if (data < node->data) {
if (node->left == nullptr) {
node->left = new Node<T>(data);
} else {
insert(node->left, data);
}
} else {
if (node->right == nullptr) {
node->right = new Node<T>(data);
} else {
insert(node->right, data);
}
}
}
void remove(Node<T>* node, T data) {
if (node == nullptr) {
return;
}
if (data < node->data) {
remove(node->left, data);
} else if (data > node->data) {
remove(node->right, data);
} else {
if (node->left == nullptr && node->right == nullptr) {
delete node;
node = nullptr;
} else if (node->left == nullptr) {
Node<T>* temp = node;
node = node->right;
delete temp;
} else if (node->right == nullptr) {
Node<T>* temp = node;
node = node->left;
delete temp;
} else {
Node<T>* temp = findMin(node->right);
node->data = temp->data;
remove(node->right, temp->data);
}
}
}
void find(Node<T>* node, T data) {
if (node == nullptr) {
return;
}
if (data < node->data) {
find(node->left, data);
} else if (data > node->data) {
find(node->right, data);
} else {
return;
}
}
void find_min(Node<T>* node) {
if (node == nullptr) {
return;
}
if (node->left == nullptr) {
return node;
}
return find_min(node->left);
}
void find_max(Node<T>* node) {
if (node == nullptr) {
return;
}
if (node->right == nullptr) {
return node;
}
return find_max(node->right);
}
int height(Node<T>* node) {
if (node == nullptr) {
return -1;
}
return 1 + std::max(height(node->left), height(node->right));
}
int size(Node<T>* node) {
if (node == nullptr) {
return 0;
}
return 1 + size(node->left) + size(node->right);
}
};
#endif |
<template>
<div class="data-table">
<div class="card-deck d-block d-sm-none">
<div
v-for="notification in data.data"
:key="notification.id"
class="card"
>
<div class="card-body shadow">
<div class="d-flex align-items-center mb-3">
<notification-user :notification="notification" />
</div>
<h5 class="card-title">
<notification-message
:notification="notification"
:show-time="showTime"
/>
</h5>
<h6 class="card-subtitle mb-2 text-muted">
{{ notification.read_at || 'N/A' }}
</h6>
<a
v-if="notification.data.url"
href="#"
@click="redirectToURL(notification.data.url)"
>More</a>
</div>
</div>
</div>
<div class="card card-body table-card d-none d-sm-block">
<vuetable
:data-manager="dataManager"
:sort-order="sortOrder"
:css="css"
:api-mode="false"
:fields="fields"
:data="data"
data-path="data"
pagination-path="meta"
:no-data-template="$t('No Data Available')"
@vuetable:pagination-data="onPaginationData"
>
<!-- Change Status Slot -->
<template
slot="changeStatus"
slot-scope="props"
>
<span
v-if="props.rowData.read_at === null"
style="cursor:pointer"
class="far fa-envelope fa-lg blue-envelope"
@click="read(props.rowData.id)"
/>
<span
v-if="props.rowData.read_at !== null"
style="cursor:pointer"
@click="unread(props.rowData)"
>
<i class="far fa-envelope-open fa-lg gray-envelope" />
</span>
</template>
<!-- From Slot -->
<template
slot="from"
slot-scope="props"
>
<notification-user :notification="props.rowData" />
</template>
<!-- Subject Slot -->
<template
slot="subject"
slot-scope="props"
>
<a
style="cursor: pointer;"
@click="redirectToURL(props.rowData.data?.url)"
>
<span v-if="props.rowData.type === 'FILE_READY'" />
<span v-else>
<notification-message
:notification="props.rowData"
:style="{ fontSize: '14px' }"
/>
</span>
</a>
</template>
</vuetable>
<pagination
ref="pagination"
:single="$t('Task')"
:plural="$t('Tasks')"
:per-page-select-enabled="true"
@changePerPage="changePerPage"
@vuetable-pagination:change-page="onPageChange"
/>
</div>
</div>
</template>
<script>
import moment from "moment";
import datatableMixin from "../../components/common/mixins/datatable";
import AvatarImage from "../../components/AvatarImage";
import NotificationMessage from "./notification-message";
import NotificationUser from "./notification-user";
Vue.component("AvatarImage", AvatarImage);
export default {
components: {
NotificationMessage,
NotificationUser,
AvatarImage,
},
mixins: [datatableMixin],
props: ["filter", "filterComments", "type", "showTime"],
data() {
return {
response: null,
orderBy: "",
showTime: true,
sortOrder: [],
fields: [
{
title: () => this.$t("Status"),
name: "__slot:changeStatus",
sortField: "read_at",
width: "80px",
},
{
title: () => this.$t("From"),
name: "__slot:from",
sortField: "from",
},
{
title: () => this.$t("Message"),
name: "__slot:subject",
sortField: "subject",
},
{
title: () => this.$t("Time"),
name: "created_at",
sortField: "created_at",
},
],
};
},
computed: {
url() {
return this.notification.data?.url;
},
isComment() {
return this.data.type === "COMMENT";
},
timeFormat() {
const parts = window.ProcessMaker.user.datetime_format.split(" ");
parts.shift();
return parts.join(" ");
},
},
watch: {
filterComments() {
// this.transformResponse();
this.fetch();
},
response() {
this.transformResponse();
},
},
mounted() {
const params = new URL(document.location).searchParams;
const successRouting = params.get("successfulRouting") === "true";
if (successRouting) {
ProcessMaker.alert(this.$t("The request was completed."), "success");
}
},
methods: {
redirectToURL(url) {
if (url && url !== "/") {
window.location.href = url;
}
},
toggleReadStatus(id, isRead) {
const action = isRead ? ProcessMaker.unreadNotifications : ProcessMaker.removeNotifications;
action([id]).then(() => {
this.fetch();
});
},
read(id) {
ProcessMaker.removeNotifications([id]).then(() => {
this.fetch();
ProcessMaker.removeNotifications([id]);
});
},
unread(notification) {
ProcessMaker.unreadNotifications([notification.id]).then(() => {
this.fetch();
ProcessMaker.pushNotification(notification);
});
},
getSortParam() {
if (this.sortOrder.length > 0) {
const { sortField, direction } = this.sortOrder[0];
return `&order_by=${sortField}&order_direction=${direction}`;
}
return "";
},
transform(data) {
return {
data: data.data.map((record) => ({
...record,
created_at: this.formatDate(record.created_at),
read_at: record.read_at ? this.formatDate(record.read_at) : null,
})),
meta: data.meta,
};
},
transformResponse() {
// if (this.filterComments === true) {
// const filteredData = this.response.data.data.filter((item) => item.data && item.data.type === "COMMENT");
// this.data = this.transform({ data: filteredData });
// } else if (this.filterComments === false) {
// const filteredData = this.response.data.data.filter((item) => item.data && item.data.type !== "COMMENT");
// this.data = this.transform({ data: filteredData });
// } else {
this.data = this.transform(this.response.data);
// }
},
formatDate(dateTime) {
const months = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December",
];
const dateObj = new Date(dateTime);
const currentDate = new Date();
if (
dateObj.getDate() === currentDate.getDate()
&& dateObj.getMonth() === currentDate.getMonth()
&& dateObj.getFullYear() === currentDate.getFullYear()
) {
return moment(dateObj).format(this.timeFormat);
}
const month = dateObj.getMonth();
const day = dateObj.getDate();
const formattedMonth = months[month];
return `${formattedMonth} ${day}`;
},
addLeadingZero(value) {
return value < 10 ? `0${value}` : value;
},
fetch() {
this.loading = true;
if (this.cancelToken) {
this.cancelToken();
this.cancelToken = null;
}
const { CancelToken } = ProcessMaker.apiClient;
const params = {
page: this.page,
per_page: this.perPage,
filter: this.filter,
comments: this.filterComments,
};
// Load from your API client (adjust the API endpoint and parameters as needed)
ProcessMaker.apiClient
.get("notifications", {
params: {
...params,
...this.getSortParam(),
include: "user",
},
cancelToken: new CancelToken((c) => {
this.cancelToken = c;
}),
})
.then((response) => {
this.response = response;
this.loading = false;
});
},
},
};
</script>
<style lang="scss" scoped>
.icon {
width: 1em;
}
.gray-envelope {
color: gray;
}
.blue-envelope {
color: rgb(55, 55, 87);
}
:deep(.vuetable-th-slot-subject) {
min-width: 450px;
white-space: nowrap;
}
:deep(tr td:nth-child(1) span) {
padding: 6px 0px 0px 12px;
}
</style> |
import React, {Component} from 'react';
import { Line } from 'react-chartjs'
import * as Kastra from '../../constants'
import { translate } from 'react-i18next';
import Pagination from '../common/pagination';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
data: {},
stats: {},
visits: [],
recentUsers: [],
applicationVersion: '',
coreVersion: ''
};
}
componentDidMount() {
this.fetchGraphData();
this.fetchGlobalStats();
this.fetchVisits();
this.fetchRecentUsers();
this.fetchVersions();
}
fetchGraphData(index) {
fetch(`${Kastra.API_URL}/api/Statistics/GetVisitorsByDay?index=${index}`,
{
method: 'GET',
credentials: 'include'
})
.then(res => res.json())
.then(
(result) => {
this.setState({ data: result });
}
).catch(function(error) {
console.log('Error: \n', error);
});
}
fetchGlobalStats() {
fetch(`${Kastra.API_URL}/api/Statistics/GetGlobalStats`,
{
method: 'GET',
credentials: 'include'
})
.then(res => {
if(res.ok) {
return res.json();
} else {
if(res.status === 401) {
this.props.history.push('/login');
}
}
})
.then(
(result) => {
this.setState({ stats: result });
}
).catch(function(error) {
console.log('Error: \n', error);
});
}
fetchVisits(index) {
fetch(`${Kastra.API_URL}/api/Statistics/GetVisits?index=${index}`,
{
method: 'GET',
credentials: 'include'
})
.then(res => res.json())
.then(
(result) => {
this.setState({ visits: result });
}
).catch(function(error) {
console.log('Error: \n', error);
});
}
fetchRecentUsers(index) {
fetch(`${Kastra.API_URL}/api/Statistics/GetRecentUsers?index=${index}`,
{
method: 'GET',
credentials: 'include'
})
.then(res => res.json())
.then(
(result) => {
this.setState({ recentUsers: result });
}
).catch(function(error) {
console.log('Error: \n', error);
});
}
fetchVersions() {
fetch(`${Kastra.API_URL}/api/SiteConfiguration/GetApplicationVersions`,
{
method: 'GET',
credentials: 'include'
})
.then(res => res.json())
.then(
(result) => {
this.setState({
applicationVersion: result.applicationVersion,
coreVersion: result.coreVersion
});
}
).catch(function(error) {
console.log('Error: \n', error);
});
}
renderVisitsTable() {
const { t } = this.props;
if(this.state.visits.length > 0) {
return (
<table className="table table-hover table-dark bg-dark mt-5 rounded">
<thead>
<tr>
<th>{t('home.date')}</th>
<th>{t('home.user')}</th>
<th>{t('home.ipAddress')}</th>
</tr>
</thead>
<tbody>
{
this.state.visits.map((visit, index) => {
return (
<tr key={index}>
<td>{visit.date}</td>
<td>{visit.username}</td>
<td>{visit.ipAddress}</td>
</tr>
);
})
}
</tbody>
</table>
);
} else {
return (
<table>
<thead>
<tr>
<th>{t('home.date')}</th>
<th>{t('home.user')}</th>
<th>{t('home.ipAddress')}</th>
<th>{t('home.userAgent')}</th>
</tr>
</thead>
<tbody>
<tr><td>{t('home.visitNotFound')}</td></tr>
</tbody>
</table>
);
}
}
renderRecentUsers() {
const { t } = this.props;
if(this.state.recentUsers.length > 0) {
return (
<table className="table table-hover table-dark bg-dark mt-5 rounded">
<tbody>
{
this.state.recentUsers.map((user, index) => {
return (
<tr key={index}>
<td>
<div className="list-group small">
<div className="w-100">
<h5 className="mb-1">{user.username}</h5>
</div>
<p className="mb-0">{user.email}</p>
</div>
</td>
</tr>
);
})
}
</tbody>
</table>
);
} else {
return (
<p>{t('home.userNotFound')}</p>
);
}
}
render() {
if(Object.keys(this.state.data).length === 0) {
return null;
}
const { t } = this.props;
const { stats } = this.state;
return (
<div className="text-white mt-5 clearfix">
<div className="container">
<div className="row">
<div className="col">
<div className="bg-dark mb-4 p-4">
<blockquote className="blockquote">
<p>{t('home.welcomeTitle')}</p>
<footer className="blockquote-footer text-right">
<small>Kastra website (v{this.state.applicationVersion}) based on Kastra Core (v{this.state.coreVersion})</small>
</footer>
</blockquote>
</div>
</div>
</div>
<div className="row mb-4">
<div className="col-4">
<div className="bg-dark p-4">
<h3>
<i className={`icon ion-person-stalker`}></i>
<small> {t('home.userNumber')}</small>
</h3>
<h2 className="display-4">{this.state.stats.numberOfUsers}</h2>
</div>
</div>
<div className="col-4">
<div className="bg-dark p-4">
<h3>
<i className={`icon ion-clock`}></i>
<small> {t('home.visitOfDay')}</small>
</h3>
<h2 className="display-4">{this.state.stats.visitsPerDay}</h2>
</div>
</div>
<div className="col-4">
<div className="bg-dark p-4">
<h3><i className="icon ion-clipboard"></i><small> {t('home.totalVisits')}</small></h3>
<h2 className="display-4">{this.state.stats.totalVisits}</h2>
</div>
</div>
</div>
<div className="row mb-4">
<div className="col-12">
<div className="bg-dark p-4">
<h3>{t('home.visitByDay')}</h3>
<Line id="visits-chart" data={this.state.data} options={{ maintainAspectRatio: false, pointDot: false, responsive: true }} />
<Pagination limit="5" enableNegativeIndex load={(index) => this.fetchGraphData(index)} />
</div>
</div>
</div>
<div className="row">
<div className="col-6">
<div className="bg-dark mr-sm-1 p-4">
<h3>{t('home.recentUsers')}</h3>
{this.renderRecentUsers()}
<Pagination limit="5" load={(index) => this.fetchRecentUsers(index)} total={stats.numberOfUsers} />
</div>
</div>
<div className="col-6">
<div className="bg-dark p-4">
<h3>{t('home.visits')}</h3>
{this.renderVisitsTable()}
<Pagination limit="5" load={(index) => this.fetchVisits(index)} total={stats.totalVisits} />
</div>
</div>
</div>
</div>
</div>
);
}
}
export default translate()(Home); |
const router = require('express').Router();
const { celebrate, Joi } = require('celebrate');
const { errors } = require('celebrate');
const {
getCards,
createCard,
deleteCardById,
likeCard,
dislikeCard,
} = require('../controllers/cards');
// возвращает все карточки
router.get('/cards', getCards);
// создаёт карточку места
router.post(
'/cards',
celebrate({
body: Joi.object().keys({
name: Joi.string().required().min(2).max(30),
link: Joi.string().required().min(2).max(30)
.pattern(/(https?:\/\/)(w{3}\.)?(((\d{1,3}\.){3}\d{1,3})|((\w-?)+\.(ru|com)))(:\d{2,5})?((\/.+)+)?\/?#?/),
}),
}),
createCard,
);
// удаляет карточку по идентификатору
router.delete(
'/cards/:cardId',
celebrate({
params: Joi.object().keys({
cardId: Joi.string().length(24).hex().required(),
}),
}),
deleteCardById,
);
// поставить лайк карточке
router.put(
'/cards/:cardId/likes',
celebrate({
params: Joi.object().keys({
cardId: Joi.string().length(24).hex().required(),
}),
}),
likeCard,
);
// убрать лайк с карточки
router.delete(
'/cards/:cardId/likes',
celebrate({
params: Joi.object().keys({
cardId: Joi.string().length(24).hex().required(),
}),
}),
dislikeCard,
);
router.use(errors());
module.exports = router; |
+++
title = "Quick Xamarin RE Guide"
date = "2023-08-30"
author = "Joan Calabrés"
description = "Get started with Xamarin reverse engineering with this quick guide."
+++
## What is Xamarin?
Xamarin is an open source platform used to compile modern applications with a great performance for iOS, Android and Windows with .NET. Xamarin is an abstraction layer that administrates shared code with the code of the underlying platform. Xamarin is executed in an administered environment that performs memory assignation and garbage collection.
## How it works?
In this diagram we show the general architecture of a Xamarin multi platform application. Xamarin lets the developers to write a native GUI for every platform and write the logic in C# that will be shared with all the platforms. In most of the cases, with Xamarin, we can share the 80% of the code of the application. Xamarin is added to .NET that automatically controls memory assignation and does the interoperability between the platforms.
{{< image src="/posts/img/xamarin/platform.png" alt="Xamarin Platform" position="center" style="border-radius: 8px;height: 250px;">}}
## Android Xamarin Compilation
C# is compiled to IL and packaged with MonoVM + JIT’ing. Unused classes in the framework are stripped out during linking. The application runs side by side with Java/ART (Android runtime) and interacts with the native types via JNI.
## Where to find Shared Code?
Shared Code is compiled into static .DLL libraries, these libraries are found into the `assemblies` folder of your root apk directory. You will find in this directory multiple .DLL files including the `Mono.Android.dll` that is in charge of the Mono runtime, also you will find other libraries related with third party libraries or the main code of the application.
## How to decompile .DLL code?
The payload of the .DLL libraries is compressed using the **lz4** algorithm, this payloads have the instructions of the **IL** (Intermediate Language) that can be decompiled using different programs such as ILSpy. The following image represents the format:
{{< image src="/posts/img/xamarin/binary_format.png" alt="Binary Format" position="left" style="border-radius: 8px;height: 250px;">}}
In order to decompress the payloads inside the .DLL files we can use the following bash script:
```python
#!/usr/bin/python
import sys, struct, lz4.block, os.path
if len(sys.argv) != 2:
sys.exit("[i] Usage: " + sys.argv[0] + " in_file.dll")
in_file = sys.argv[1]
with open(in_file, "rb") as compressed_file:
compressed_data = compressed_file.read()
header = compressed_data[:4]
if header != b"XALZ":
sys.exit("[!] Wrong header, aborting...!")
packed_payload_len = compressed_data[8:12]
unpacked_payload_len = struct.unpack('<I', packed_payload_len)[0]
compressed_payload = compressed_data[12:]
decompressed_payload = lz4.block.decompress(compressed_payload, uncompressed_size=unpacked_payload_len)
out_file = in_file.rsplit(".",1)[0] + "_out.dll"
if os.path.isfile(out_file):
sys.exit("[!] Output file [" + out_file + "] already exists, aborting...!")
with open(out_file, "wb") as decompressed_file:
decompressed_file.write(decompressed_payload)
print("[i] Success!")
print("[i] File [" + out_file + "] was created as result!")
```
You can use it using the following format: `python3 [de-lz4.py](http://de-lz4.py) {PATH_TO_DLL}`. A file with the suffix `_out.dll` will be added to the same path.
## Decompiling .NET code
You can download `ILSpy` a decompiler to inspect **IL** bytecode. Later on, open the .DLL that you want to inspect with it. It is recommended to put part of the assemblies that you want to reverse in order to obtain cross-references between different .DLL files.
## Hooking .NET Code
A GitHub repository has been created with the API for the Mono runtime https://github.com/freehuntx/frida-mono-api. The https://github.com/NorthwaveSecurity/fridax tool integrates this API with Frida in order to allow you to easily modify the .NET binary inside a Xamarin application on runtime.
### Installation
For the correct functionality of this tool, you will need to use an old version of frida-server. In that case **14.0.8** is working well with this tool. New versions might fail as fridax dependencies are outdated and assembled to work with old versions.
Follow the steps inside the GitHub repository. Be sure to have Node **14.0.0**, if not, the installation will fail as Fridax was created with older versions of Node. An easy way to have multiple Node installations is to install https://github.com/nvm-sh/nvm. Later on, install node 14 and change the default node to use:
`nvm install 14`
`nvm use 14`
### Usage
For usb devices you can use:
`./fridax.js inject --device "usb”`
There are multiple templates inside the **fridax** folder, examples. This folder contains different templates for hooking aot/jit binaries.
## Bypassing Cert Pinning
### How it’s implemented?
There are two entry points to override certificate validation, depending on whether .NET Framework or .NET Core is being used. Mono has recently moved to .NET Code APIs
Prior to .NET Code validation occurs through `System.Net.ServicePointManager.ServerCertificateValidationCallback` which is a static property containing the function to call when validating a certificate. All `HttpClient` instances will call the same function, *so only one function needs to be hooked*.
Starting with .NET Core, however, the HTTP stack has been refactored such that each `HttpClient` has its own `HttpClientHandler` exposing a `ServerCertificateCustomValidationCallback` property. This handler is injected into the `HttpClient` at construction time and is frozen after the first HTTP call to prevent modification. This scenario is much more difficult as it requires knowledge of every `HttpClient` instance and their location in memory at runtime.
### Fridax hook
```jsx
import { MonoApiHelper, MonoApi } from '../vendors/frida-mono-api'
import ClassHelper from '../libraries/class_helper'
// The root AppDomain is the initial domain created by the runtime when it is initialized.
const domain = MonoApi.mono_get_root_domain()
// Get System.Net.Http from memory
let status = Memory.alloc(0x1000);
let http = MonoApi.mono_assembly_load_with_partial_name(Memory.allocUtf8String('System.Net.Http'), status);
let img = MonoApi.mono_assembly_get_image(http);
// Get HttpClientHandler class and constructor
var kHandler = MonoApi.mono_class_from_name(img, Memory.allocUtf8String('System.Net.Http'), Memory.allocUtf8String('HttpClientHandler'));
var ctor = MonoApiHelper.ClassGetMethodFromName(kHandler, 'CreateDefaultHandler');
// Get HttpRequestMessage class and ToString method
let request = MonoApi.mono_class_from_name(img, Memory.allocUtf8String('System.Net.Http'), Memory.allocUtf8String('HttpRequestMessage'));
let toString = MonoApiHelper.ClassGetMethodFromName(request, 'ToString');
var INJECTED = {};
if (kHandler) {
// Hook HttpMessageInvoker.SendAsync
var kInvoker = MonoApi.mono_class_from_name(img, Memory.allocUtf8String('System.Net.Http'), Memory.allocUtf8String('HttpMessageInvoker'));
// Attach interceptor and fish out the first method argument
MonoApiHelper.Intercept(kInvoker, 'SendAsync', {
onEnter: function(args) {
// Print HTTP Request
console.log(MonoApiHelper.StringToUtf8(MonoApiHelper.RuntimeInvoke(toString, args[1])));
// Get the HTTP handler
var self = args[0];
var handler = MonoApiHelper.ClassGetFieldFromName(kInvoker, '_handler');
var cur = MonoApiHelper.FieldGetValueObject(handler, self);
if (INJECTED[cur]) return; // Already bypassed.
// Create a new handler per HttpClient to avoid dispose() causing a crash.
var pClientHandler = MonoApiHelper.RuntimeInvoke(ctor, NULL); // instance is NULL for static methods.
console.log("[+] New HttpClientHandler VA=".concat(pClientHandler));
MonoApi.mono_field_set_value(self, handler, pClientHandler);
console.log("[+] Injected default handler for Client=".concat(self));
INJECTED[pClientHandler] = true; // TODO: cleanup on HttpClient dispose.
}
})
}
console.log(`Xamarin pinning bypass attached and ready.`)
```
## Resources
* [Reverse Engineering a Xamarin Application. " Security Grind](https://securitygrind.com/reverse-engineering-a-xamarin-application/)
* [Bypassing Xamarin Certificate Pinning on Android - GoSecure](https://www.gosecure.net/blog/2020/04/06/bypassing-xamarin-certificate-pinning-on-android/)
* [https://github.com/NorthwaveSecurity/fridax](https://github.com/NorthwaveSecurity/fridax) |
<div class="flex flex-col justify-center items-center">
<div class="mt-2 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert" *ngIf="error">
<strong class="font-bold">Ops!</strong>
<span class="block sm:inline ml-1">Something seriously bad happened.</span>
<span class="block sm:inline ml-1">{{error}}</span>
</div>
<form *ngIf="!loading" #authForm="ngForm" (ngSubmit)="onSubmit(authForm)">
<div class="flex flex-col gap-1 my-4">
<label for="email" class="">Email</label>
<input ngModel required type="email" name="email" id="email" email
class="outline outline-1 rounded outline-gray-300">
</div>
<div class="flex flex-col gap-1 mb-4">
<label for="password" class="">Password</label>
<input ngModel minlength="6" required type="password" name="password" id="password"
class="outline outline-1 rounded outline-gray-300">
</div>
<button type="submit" [disabled]="!authForm.valid"
class="disabled:bg-slate-500 disabled:text-white disabled:border-none border text-blue-400 rounded px-2 border-blue-400 active:bg-blue-200 transition-colors font-medium mr-2 w-32">{{isLoginMode
? 'Login' : 'Sign Up'}}</button>
<span class="text-slate-500 font-bold">|</span>
<button type="button"
class="w-40 ml-2 border text-blue-400 rounded px-2 border-blue-400 active:bg-blue-200 transition-colors font-medium"
(click)="onSwitchMode()">Switch to {{isLoginMode ? 'Sign Up': 'Login'}}</button>
</form>
<app-loading-spinner *ngIf="loading" />
</div> |
import { CARTA } from "carta-protobuf";
import { Client, AckStream, Usage, AppendTxt, EmptyTxt, Wait, Monitor } from "./CLIENT";
import * as Socket from "./SocketOperation";
import config from "./config.json";
let testServerUrl: string = config.localHost + ":" + config.port;
let testSubdirectory: string = config.path.performance;
let testImage: string = config.image.cube;
let execTimeout: number = config.timeout.execute;
let connectTimeout: number = config.timeout.connection;
let readfileTimeout: number = config.timeout.readFile;
let cursorTimeout: number = config.timeout.region;
let cursorRepeat: number = config.repeat.region;
let monitorPeriod: number = config.wait.monitor;
interface AssertItem {
register: CARTA.IRegisterViewer;
filelist: CARTA.IFileListRequest;
fileOpen: CARTA.IOpenFile;
setRegion: CARTA.ISetRegion;
setSpectralRequirements: CARTA.ISetSpectralRequirements;
}
let assertItem: AssertItem = {
register: {
sessionId: 0,
apiKey: "",
clientFeatureFlags: 5,
},
filelist: { directory: testSubdirectory },
fileOpen: {
directory: testSubdirectory,
file: testImage,
hdu: "0",
fileId: 0,
renderMode: CARTA.RenderMode.RASTER,
},
setRegion: {
fileId: 0,
regionId: 1,
regionInfo: {
regionType: CARTA.RegionType.RECTANGLE,
controlPoints: [{ x: 50, y: 50 }, { x: 0, y: 0 }],
rotation: 0.0,
},
},
setSpectralRequirements: {
fileId: 0,
regionId: 1,
spectralProfiles: [{ coordinate: "z", statsTypes: [CARTA.StatsType.Sum] }],
},
}
describe("Z profile cursor action: ", () => {
let Connection: Client;
let cartaBackend: any;
let logFile = assertItem.fileOpen.file.substr(assertItem.fileOpen.file.search('/') + 1).replace('.', '_') + "_ZProfileRegion.txt";
let usageFile = assertItem.fileOpen.file.substr(assertItem.fileOpen.file.search('/') + 1).replace('.', '_') + "_ZProfileRegion_usage.txt";
test(`Empty the record files`, async () => {
await EmptyTxt(logFile);
await EmptyTxt(usageFile);
});
test(`CARTA is ready`, async () => {
cartaBackend = await Socket.CartaBackend(
logFile,
config.port,
);
await Wait(config.wait.exec);
}, execTimeout + config.wait.exec);
describe(`Go to "${assertItem.filelist.directory}" folder`, () => {
beforeAll(async () => {
Connection = new Client(testServerUrl);
await Connection.open();
await Connection.send(CARTA.RegisterViewer, assertItem.register);
await Connection.receive(CARTA.RegisterViewerAck);
}, connectTimeout);
describe(`start the action`, () => {
let ack: AckStream;
test(`should open the file "${assertItem.fileOpen.file}"`, async () => {
await Connection.send(CARTA.OpenFile, assertItem.fileOpen);
ack = await Connection.stream(2) as AckStream; // OpenFileAck | RegionHistogramData
}, readfileTimeout);
test(`should get z-profile`, async () => {
await Connection.send(CARTA.SetRegion, {
regionId: -1,
...assertItem.setRegion,
});
await Connection.receiveAny();
await Connection.send(CARTA.SetSpectralRequirements, assertItem.setSpectralRequirements);
await Connection.receiveAny();
for (let idx = 0; idx < cursorRepeat; idx++) {
let Dx = Math.floor((ack.Responce[0] as CARTA.OpenFileAck).fileInfoExtended.width * (.4 + .2 * Math.random()));
let Dy = Math.floor((ack.Responce[0] as CARTA.OpenFileAck).fileInfoExtended.height * (.4 + .2 * Math.random()));
await Connection.send(CARTA.SetRegion, {
...assertItem.setRegion,
regionInfo: {
...assertItem.setRegion.regionInfo,
controlPoints: [
{
x: Dx - assertItem.setRegion.regionInfo.controlPoints[0].x * .5,
y: Dy - assertItem.setRegion.regionInfo.controlPoints[0].y * .5,
},
{
x: Dx + assertItem.setRegion.regionInfo.controlPoints[0].x * .5,
y: Dy + assertItem.setRegion.regionInfo.controlPoints[0].y * .5,
},
],
},
});
await Connection.receiveAny();
let monitor = Monitor(cartaBackend.pid, monitorPeriod);
await Connection.send(CARTA.SetSpectralRequirements, assertItem.setSpectralRequirements);
while ((await Connection.receive(CARTA.SpectralProfileData) as CARTA.SpectralProfileData).progress < 1) { }
// let R = await Connection.receive(CARTA.SpectralProfileData) as CARTA.SpectralProfileData;
// while ( R.progress< 1) {
// R = await Connection.receive(CARTA.SpectralProfileData) as CARTA.SpectralProfileData;
// console.log(R);
// }
clearInterval(monitor.id);
if (monitor.data.cpu.length === 0) {
await AppendTxt(usageFile, await Usage(cartaBackend.pid));
} else {
await AppendTxt(usageFile, monitor.data);
}
await Wait(config.wait.cursor);
}
await Connection.send(CARTA.CloseFile, { fileId: -1 });
}, (cursorTimeout + config.wait.cursor) * cursorRepeat);
});
});
afterAll(async done => {
await Connection.close();
cartaBackend.kill();
cartaBackend.on("close", () => done());
}, execTimeout);
}); |
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#define STR_LEN 256
#define BUFF_READ_LEN 20
#ifndef MULTILIB_ASCII
#define MULTILIB_ASCII
static const int VOWELS[] = {97, 101, 105, 111, 117};
static const int UPPER_VOWELS[] = {65, 69, 73, 79, 85};
static const int CONSONANTS[] = {98, 99, 100, 102, 103, 104, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 118, 119, 120, 121, 122};
static const int UPPER_CONSONANTS[] = {66, 67, 68, 70, 71, 72, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90};
static const int VOWELS_LEN = 5;
static const int CONSONANTS_LEN = 21;
#endif
/**
* Usually used between server-client communication when the server wants to terminate the sending of files, because,
* for example it has already sent all the files.
*/
static const char FILE_TRANSMISSION_END[] = "__#done";
/**
* Used as temporary file were to write temporary data instead of storing it in the ram.
*/
static const char TEMP_OUT_FILE[] = "__tmp_out";
struct FileScanOutput
{
int nChars;
int nWords;
int nLines;
int errorCode;
};
typedef struct FileScanOutput FileScanOutput;
/**
* Checks whether the port is valid or not.
*
* @return 0 if the port is not valid, 1 otherwise
*/
int is_port_valid(int port)
{
return port < 1024 || port > 65535 ? 0 : 1;
}
/**
* Controlla se la sequenza di caratteri passati è un numero valid
*/
int is_numeric_string(char *str)
{
int nread = 0;
while (str[nread] != '\0')
{
if ((str[nread] < '0') || (str[nread] > '9'))
{
return 0;
}
nread++;
}
return 1;
}
/**
* Checks whether the str param starts with the prefix param.
*
* @retval 0 if not
* @retval 1 if yes
*/
int starts_with(const char *str, const char *prefix)
{
if (!str || !prefix)
{
return 0;
}
size_t lenstr = strlen(str);
size_t lenprefix = strlen(prefix);
if (lenprefix > lenstr)
{
return 0;
}
return strncmp(prefix, str, strlen(prefix)) == 0;
}
/**
* Checks whether the str param ends with the suffix param.
*
* @retval 0 if not
* @retval 1 if yes
*/
int ends_with(const char *str, const char *suffix)
{
if (!str || !suffix)
{
return 0;
}
size_t lenstr = strlen(str);
size_t lensuffix = strlen(suffix);
if (lensuffix > lenstr)
{
return 0;
}
return strncmp(str + lenstr - lensuffix, suffix, lensuffix) == 0;
}
/**
* Checks whether the given char parameter is a vowel or not.
*
* @param c the char to check
*
* @retval 0 if the char is not a vowel
* @retval 1 if the char is a vowel
*/
int is_vowel(char c)
{
int is = 0;
for (int i = 0; i < VOWELS_LEN; i++)
{
if (c == VOWELS[i])
{
is = 1;
}
}
if (is == 0)
{
for (int i = 0; i < VOWELS_LEN; i++)
{
if (c == UPPER_VOWELS[i])
{
is = 1;
}
}
}
return is;
}
/**
* Checks whether the given char parameter is a consonant or not.
*
* @param c the char to check
*
* @retval 0 if the char is not a consonant
* @retval 1 if the char is a consonant
*/
int is_consonant(char c)
{
int is = 0;
for (int i = 0; i < CONSONANTS_LEN; i++)
{
if (c == CONSONANTS[i])
{
is = 1;
}
}
if (is == 0)
{
for (int i = 0; i < CONSONANTS_LEN; i++)
{
if (c == UPPER_CONSONANTS[i])
{
is = 1;
}
}
}
return is;
}
/**
* Checks whether the str parameter contains a vocal AND a consonant
*
* @retval 0 if the str does not contain at least a vocal AND a consonant
* @retval 1 if the str contains at least a vocal AND a consonant
*/
int has_vocal_and_consonant(char *str)
{
int i;
int hasVocal = 0;
int hasConsonant = 0;
for (i = 0; i < strlen(str) && (hasVocal == 0 || hasConsonant == 0); i++)
{
if (hasVocal == 0)
{
hasVocal = is_vowel(str[i]);
}
if (hasConsonant == 0)
{
hasConsonant = is_consonant(str[i]);
}
}
return hasVocal == 1 && hasConsonant == 1;
}
/**
* Returns the given line at the given line number.
*
* @param *filepath the path of the file to read
* @param *line the line to return
*/
char *get_line_str_of_file(char *filepath, int line)
{
char ris[STR_LEN];
char c;
int fd, curline = 0;
if ((fd = open(filepath, O_RDONLY)) < 0)
{
perror("open");
return NULL;
}
while ((read(fd, &c, sizeof(char))) > 0)
{
if ((curline - 1) == line)
{
strcat(ris, &c);
}
if (c == '\n' || c == '\r')
{
curline++;
}
}
close(fd);
return ris;
}
/**
* Counts in how many lines the given str parameter is found in the file.
*
* @param *filepath the path of the file to scan
* @param *str the string to search for
*
* @retval -1 if some error occurs
* @retval >= 0 the number of lines found containing the str parameter
*/
int find_str_occurrences_in_file_line(char *filepath, char *str)
{
char c;
int fd, ris = 0;
char line[STR_LEN];
if ((fd = open(filepath, O_RDONLY)) < 0)
{
perror("open");
return -1;
}
while ((read(fd, &c, sizeof(char))) > 0)
{
strcat(line, &c);
if (c == '\n' || c == '\r')
{
if (strstr(line, str) != NULL)
{
ris++;
}
memset(line, 0, STR_LEN);
}
}
close(fd);
return ris;
}
/**
* Finds the longest word in a file and returns its length.
* The longest word gets copied to the `longestWordResult` parameter.
*/
int find_longest_word_in_file(char *file, char *longestWordResult)
{
int rdFile, nread = 0, currentDim = 0, ris = 0;
char c;
char word[STR_LEN], tmpword[STR_LEN];
if ((rdFile = open(file, O_RDONLY)) < 0)
{
perror("open file sorgente");
return -1;
}
while ((nread = read(rdFile, &c, sizeof(c))) > 0)
{
if (c != ' ' && c != '\n' && c != '\r')
{
tmpword[currentDim] = c;
currentDim++;
}
else
{
if (currentDim > ris)
{
ris = currentDim;
tmpword[currentDim] = '\0';
strcpy(word, tmpword);
}
// reset tmpword
memset(tmpword, 0, sizeof(tmpword));
currentDim = 0;
}
}
strcpy(longestWordResult, word);
close(rdFile);
return ris;
}
/**
* Deletes the matching `word` from a file
*/
int delete_words_from_file(char *file, char *wordToRemove)
{
char c;
char tmpword[STR_LEN];
int rdFile, wrFile;
int nread = 0, removed = 0, currentDim = 0;
if ((rdFile = open(file, O_RDONLY)) < 0)
{
perror("open file sorgente");
return -1;
}
if ((wrFile = open(TEMP_OUT_FILE, O_CREAT | O_WRONLY, 0644)) < 0)
{
perror("open file destinazione");
return -1;
}
while ((nread = read(rdFile, &c, sizeof(c))) > 0)
{
// we consider words the block of chars delimited by spaces, new lines or carriage returns
if (c != ' ' && c != '\n' && c != '\r')
{
tmpword[currentDim] = c;
currentDim++;
}
else
{
tmpword[currentDim] = '\0';
// if the wordToRemove matches with the read word, we simply do not write it to the file otherwise
// we write what we read to the file including the word delimiter char
if (strcmp(wordToRemove, tmpword) == 0)
{
removed++;
}
else
{
write(wrFile, tmpword, strlen(tmpword));
// write the end of line chars or space
write(wrFile, &c, 1);
}
currentDim = 0;
// reset tmpword
memset(tmpword, 0, sizeof(tmpword));
}
}
// remove the current file & replace it with the tmp one that will get renominated to the original file
if (remove(file) != 0)
{
perror("remove file");
return -1;
}
if (rename(TEMP_OUT_FILE, file) != 0)
{
perror("rename file");
return -1;
}
close(rdFile);
close(wrFile);
return removed;
}
/**
* Lists file in a directory with the subdirs as well.
*/
void listdir(const char *name, int indent)
{
DIR *dir;
struct dirent *entry;
if (!(dir = opendir(name)))
return;
while ((entry = readdir(dir)) != NULL)
{
if (entry->d_type == DT_DIR)
{
char path[STR_LEN * 2];
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
printf("%*s[%s]\n", indent, "", entry->d_name);
listdir(path, indent + 2);
}
else
{
printf("%*s- %s\n", indent, "", entry->d_name);
}
}
closedir(dir);
}
/**
* Conta i file in un direttorio
*/
int count_files_in_dir(char *dirname)
{
DIR *dir;
struct dirent *dd;
int count = 0;
dir = opendir(dirname);
if (dir == NULL)
{
return -1;
}
while ((dd = readdir(dir)) != NULL)
{
printf("Trovato il file %s\n", dd->d_name);
count++;
}
// Conta anche direttorio stesso e padre
printf("Numero totale di file %d\n", count);
closedir(dir);
return count;
}
/**
* Counts the chars, words and lines of a target file.
*/
FileScanOutput filescan(char *filepath)
{
static FileScanOutput result;
result.nChars = 0;
result.nLines = 0;
result.nWords = 0;
result.errorCode = 0;
int fd, nread = 0;
char c, prevChar = ' ';
char word[STR_LEN];
if ((fd = open(filepath, O_RDONLY)) < 0)
{
perror("open file sorgente");
result.errorCode = 1;
return result;
}
while ((nread = read(fd, &c, sizeof(c))) > 0)
{
result.nChars++;
if (c == ' ' && prevChar == ' ')
{
continue;
}
if (c == '\n' || c == '\r')
{
result.nLines++;
}
if (c == ' ')
{
result.nWords++;
}
prevChar = c;
}
printf("nChars: %d\n", result.nChars);
printf("nLines: %d\n", result.nLines);
printf("nWords: %d\n", result.nWords);
return result;
}
/**
* Removes the VOWELS from a file content.
*
* @param file the file to remove the VOWELS from
*
* @retval -1 if an error occurred
* @retval the number of VOWELS removed from the file (>= 0)
*/
int delete_vowels_from_file(char *file)
{
char c;
char tmpword[STR_LEN];
int rdFile, wrFile;
int nread = 0, vowelsRemoved = 0, currentDim = 0;
if ((rdFile = open(file, O_RDONLY)) < 0)
{
perror("open file sorgente");
return -1;
}
if ((wrFile = open(TEMP_OUT_FILE, O_CREAT | O_WRONLY, 0644)) < 0)
{
perror("open file destinazione");
return -1;
}
while ((nread = read(rdFile, &c, sizeof(c))) > 0)
{
if (is_vowel(c) == 0)
{
write(wrFile, &c, 1);
}
else
{
vowelsRemoved++;
}
}
// remove the current file & replace it with the tmp one that will get renominated to the original file
if (remove(file) != 0)
{
perror("remove file");
return -1;
}
if (rename(TEMP_OUT_FILE, file) != 0)
{
perror("rename file");
return -1;
}
close(rdFile);
close(wrFile);
return vowelsRemoved;
}
/**
* Scans the files in a given directory by ignoring the ones which size < threshold
*/
int dirscan_threshold(char *targetDir, int threshold)
{
static int result = 0;
DIR *dir;
struct dirent *dd;
int i, fd_file;
off_t fileSize;
result = -1;
printf("Richiesto direttorio %s\n", targetDir);
if ((dir = opendir(targetDir)) == NULL)
{
return result;
}
result = 0;
while ((dd = readdir(dir)) != NULL)
{
fd_file = open(dd->d_name, O_RDONLY);
if (fd_file < 0)
{
printf("File inesistente\n");
return result;
}
fileSize = lseek(fd_file, 0L, SEEK_END);
if (fileSize >= threshold)
{
printf("DEBUG: candidate file size %lld\n", fileSize);
result++;
}
}
printf("Numero totale di file nel direttorio richiesto %d\n", result);
return result;
}
/**
* Sends the file corresponding to the given /path/filename through the given socket.
* NOTE: the path will be completed with the filename if it is not already present.
*
* @param socket_d the socket to send the file through
* @param filename the filename of the file to send
* @param path the path of the file to send, may be either the full path or not,
* if not it will be completed with the filename
*
* @retval the number of bytes sent
* @retval -1 in case of error.
*/
int send_file_via_socket(int socket_d, char *filename, char *path)
{
int file_fd, nread, size = 0;
char fbuff[BUFF_READ_LEN];
char fullpath[STR_LEN];
printf("transferring %s to client\n", filename);
// need to pass the raw STR_LEN size, sizeof(filename) would be wrong for some reason
/*
* ATTENZIONE, usare strlen e NON
* sizeof(*msg) che restituisce
* NON la dimensione della stringa puntata da *msg,
* MA la dimensione di un puntatore, cio� 4 byte.
*/
// !CHECK!
write(socket_d, filename, STR_LEN);
strcpy(fullpath, path);
// check whether the path has already the filename specified or not -> /path/filename
// if not, add it to the path
if (strcmp(filename, strrchr(path, '/') + 1) != 0)
{
// no '/' specified at the end of the path -> add it
if (fullpath[strlen(fullpath) - 1] != '/')
strcat(fullpath, "/");
// add the filename at the end
strcat(fullpath, filename);
}
if ((file_fd = open(fullpath, O_RDONLY)) < 0)
{
perror("file open");
return -1;
}
// get the file size bytes and send it to the recipient
size = lseek(file_fd, 0L, SEEK_END);
lseek(file_fd, 0L, SEEK_SET);
write(socket_d, &size, sizeof(size));
printf("sending file size of %s: %d\n", filename, size);
// buffered read of the file in chunks of BUFF_READ_LEN bytes
while ((nread = read(file_fd, &fbuff, sizeof(fbuff))) > 0)
{
// write number of read bytes from the file
if (write(socket_d, fbuff, nread) < 0)
{
perror("writing to socket_d");
return -1;
}
}
close(file_fd);
printf("file transfer completed, sent %d bytes\n", size);
return size;
}
/**
* Saves a file received from a socket to the current directory.
*
* @param socket_d the socket descriptor
*
* @retval > 0 the number of bytes received
* @retval 0 in case the server signals the end of the file transmission with the FILE_TRANSMISSION_END marker
* @retval -1 in case of error.
*/
int save_file_from_socket(int socket_d)
{
int nread, file_fd, size = 0;
char filename[STR_LEN];
char c;
// read the filename from the socket
if (read(socket_d, &filename, sizeof(filename)) < 0)
{
perror("reading from socket_d");
exit(1);
}
if (strcmp(filename, FILE_TRANSMISSION_END) == 0)
{
return 0;
}
// open the file for writing
if ((file_fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0777)) < 0)
{
perror("file open");
return -1;
}
printf("Downloading %s\n", filename);
// receive the file size
if (read(socket_d, &size, sizeof(size)) < 0)
{
perror("reading from socket_d");
return -1;
}
printf("received file size: %d\n", size);
printf("waiting for file..\n");
// receive byte-a-byte and write them to the file
for (int i = 0; i < size; i++)
{
if (read(socket_d, &c, sizeof(c)) <= 0)
break;
if (write(file_fd, &c, sizeof(c)) < 0)
break;
}
close(file_fd);
printf("wrote %d bytes to disk\n", size);
return size;
} |
<?php
use App\Http\Controllers\AccessTokenController;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::prefix('v1')->group(function () {
Route::get('/user/{id}', function ($id) {
return new UserResource(User::findOrFail($id));
});
Route::controller(AccessTokenController::class)->name('token.')->group(function () {
Route::post('authorize/token/new', 'create')->name('create');
Route::post('authorize/token', 'store')->name('store');
Route::delete('authorize/token/revoke', 'destroy')->name('delete');
});
}); |
import Image from "next/image";
import { useCallback, useState } from "react";
import { useDropzone } from "react-dropzone";
import toast from "react-hot-toast";
interface ImageUploadProps {
onChange: (base64: string) => void;
label: string;
value?: string;
disabled?: boolean;
}
const ImageUpload: React.FC<ImageUploadProps> = ({
onChange,
label,
value,
disabled,
}) => {
const [base64, setBase64] = useState(value);
const handleChange = useCallback(
(base64: string) => {
onChange(base64);
},
[onChange]
);
const handleDrop = useCallback(
(files: any) => {
const file = files[0];
if (file.size > 350000) {
toast.error("File max size is 350kb");
return;
} else {
const reader = new FileReader();
reader.onload = (event: any) => {
setBase64(event.target.result);
handleChange(event.target.result);
};
reader.readAsDataURL(file);
}
},
[handleChange]
);
const { getRootProps, getInputProps } = useDropzone({
maxFiles: 1,
onDrop: handleDrop,
disabled,
accept: {
"image/jpg": [],
"image/png": [],
},
});
return (
<div
{...getRootProps({
className:
"w-full p-4 text-white text-center border-2 border-dotted rounded-md border-neutral-700",
})}
>
<input {...getInputProps()} />
{base64 ? (
<div className="flex items-center justify-center">
<Image
src={base64}
width={100}
height={100}
style={{ objectFit: "cover", overflowY: "hidden" }}
alt="Uploaded image"
/>
</div>
) : (
<p className="text-white">{label}</p>
)}
</div>
);
};
export default ImageUpload; |
import React from 'react';
import { getMergeSortAnimations, getQuickSortAnimations, getHeapSortAnimations, getBubbleSortAnimations } from '../sortingAlgorithms/sortingAlgorithms.js';
import './SortingVisualizer.css';
// Change this value for the speed of the animations.
const ANIMATION_SPEED_MS = 0.7;
// Change this value for the number of bars (value) in the array.
const NUMBER_OF_ARRAY_BARS = 350;
// This is the main color of the array bars.
const PRIMARY_COLOR = 'rgba(135,86,227,255)';
// This is the color of array bars that are being compared throughout the animations.
const SECONDARY_COLOR = '#ff0004';
export default class SortingVisualizer extends React.Component {
constructor(props) {
super(props);
this.state = {
array: [],
};
}
componentDidMount() {
this.resetArray();
}
resetArray() {
const array = [];
for (let i = 0; i < NUMBER_OF_ARRAY_BARS; i++) {
array.push(randomIntFromInterval(5, 730));
}
this.setState({ array });
}
mergeSort() {
const animations = getMergeSortAnimations(this.state.array);
for (let i = 0; i < animations.length; i++) {
const arrayBars = document.getElementsByClassName('array-bar');
const isColorChange = i % 3 !== 2;
if (isColorChange) {
const [barOneIdx, barTwoIdx] = animations[i];
const barOneStyle = arrayBars[barOneIdx].style;
const barTwoStyle = arrayBars[barTwoIdx].style;
const color = i % 3 === 0 ? SECONDARY_COLOR : PRIMARY_COLOR;
setTimeout(() => {
barOneStyle.backgroundColor = color;
barTwoStyle.backgroundColor = color;
}, i * ANIMATION_SPEED_MS);
} else {
setTimeout(() => {
const [barOneIdx, newHeight] = animations[i];
const barOneStyle = arrayBars[barOneIdx].style;
barOneStyle.height = `${newHeight}px`;
}, i * ANIMATION_SPEED_MS);
}
}
}
quickSort() {
const animations = getQuickSortAnimations(this.state.array);
for (let i = 0; i < animations.length; i++) {
const arrayBars = document.getElementsByClassName('array-bar');
const isColorChange = !(animations[i].length === 3 && animations[i][2] === true);
if (isColorChange) {
const [barOneIdx, barTwoIdx] = animations[i];
const barOneStyle = arrayBars[barOneIdx].style;
const barTwoStyle = arrayBars[barTwoIdx].style;
const color = i % 2 === 0 ? SECONDARY_COLOR : PRIMARY_COLOR;
setTimeout(() => {
barOneStyle.backgroundColor = color;
barTwoStyle.backgroundColor = color;
}, i * ANIMATION_SPEED_MS);
} else {
setTimeout(() => {
const [barOneIdx, newHeight] = animations[i];
const barOneStyle = arrayBars[barOneIdx].style;
barOneStyle.height = `${newHeight}px`;
}, i * ANIMATION_SPEED_MS);
}
}
}
heapSort() {
const animations = getHeapSortAnimations(this.state.array);
for (let i = 0; i < animations.length; i++) {
const arrayBars = document.getElementsByClassName('array-bar');
const isColorChange = !(animations[i].length === 3 && animations[i][2] === true);
if (isColorChange) {
const [barOneIdx, barTwoIdx] = animations[i];
const barOneStyle = arrayBars[barOneIdx].style;
const barTwoStyle = arrayBars[barTwoIdx].style;
const color = i % 2 === 0 ? SECONDARY_COLOR : PRIMARY_COLOR;
setTimeout(() => {
barOneStyle.backgroundColor = color;
barTwoStyle.backgroundColor = color;
}, i * ANIMATION_SPEED_MS);
} else {
setTimeout(() => {
const [barOneIdx, newHeight] = animations[i];
const barOneStyle = arrayBars[barOneIdx].style;
barOneStyle.height = `${newHeight}px`;
}, i * ANIMATION_SPEED_MS);
}
}
}
bubbleSort() {
const animations = getBubbleSortAnimations(this.state.array);
for (let i = 0; i < animations.length; i++) {
const arrayBars = document.getElementsByClassName('array-bar');
const isColorChange = !(animations[i].length === 3 && animations[i][2] === true);
if (isColorChange) {
const [barOneIdx, barTwoIdx] = animations[i];
const barOneStyle = arrayBars[barOneIdx].style;
const barTwoStyle = arrayBars[barTwoIdx].style;
const color = i % 2 === 0 ? SECONDARY_COLOR : PRIMARY_COLOR;
setTimeout(() => {
barOneStyle.backgroundColor = color;
barTwoStyle.backgroundColor = color;
}, i * ANIMATION_SPEED_MS);
} else {
setTimeout(() => {
const [barOneIdx, newHeight] = animations[i];
const barOneStyle = arrayBars[barOneIdx].style;
barOneStyle.height = `${newHeight}px`;
}, i * ANIMATION_SPEED_MS);
}
}
}
render() {
const { array } = this.state;
return (
<div className="SortingVisualizer">
<div className="button-container">
<button onClick={() => this.resetArray()}>Generate New Array</button>
<button onClick={() => this.mergeSort()}>Merge Sort</button>
<button onClick={() => this.quickSort()}>Quick Sort</button>
<button onClick={() => this.heapSort()}>Heap Sort</button>
<button onClick={() => this.bubbleSort()}>Bubble Sort</button>
</div>
<div className="array-container">
{array.map((value, idx) => (
<div
className="array-bar"
key={idx}
style={{
backgroundColor: PRIMARY_COLOR,
height: `${value}px`,
}}>
</div>
))}
</div>
</div>
);
}
}
// From https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript
function randomIntFromInterval(min, max) {
// min and max included
return Math.floor(Math.random() * (580 - min + 1) + min);
} |
import numpy as np
import pandas as pd
import os
from tqdm import tqdm
import matplotlib.pyplot as plt
# Base class
class Layer:
def __init__(self):
self.input = None
self.output = None
def forward_propagation(self, input):
raise NotImplementedError
def backward_propagation(self, output_error, learning_rate):
raise NotImplementedError
class Linear(Layer):
# input_size = number of input neurons
# output_size = number of output neurons
def __init__(self, input_size, output_size):
self.weights = np.random.rand(input_size, output_size) - 0.5
self.bias = np.random.rand(1, output_size) - 0.5
# returns output for a given input
def forward_propagation(self, input_data):
self.input = input_data
self.output = np.dot(self.input, self.weights) + self.bias
return self.output
# computes dE/dW, dE/dB for a given output_error=dE/dY. Returns input_error=dE/dX.
def backward_propagation(self, output_error, learning_rate):
input_error = np.dot(output_error, self.weights.T)
weights_error = np.dot(self.input.T, output_error)
# dBias = output_error
# update parameters
self.weights -= learning_rate * weights_error
self.bias -= learning_rate * output_error
return input_error
class ActivationLayer(Layer):
def __init__(self, activation, activation_prime):
self.activation = activation
self.activation_prime = activation_prime
# returns the activated input
def forward_propagation(self, input_data):
self.input = input_data
self.output = self.activation(self.input)
return self.output
# Returns input_error=dE/dX for a given output_error=dE/dY.
# learning_rate is not used because there is no "learnable" parameters.
def backward_propagation(self, output_error, learning_rate):
return self.activation_prime(self.input) * output_error
class Network:
def __init__(self,layers):
self.layers = layers
self.loss = None
self.loss_prime = None
# add layer to network
def add(self, layer):
self.layers.append(layer)
# set loss to use
def use(self, loss, loss_prime):
self.loss = loss
self.loss_prime = loss_prime
# predict output for given input
def predict(self, input_data):
# sample dimension first
samples = len(input_data)
result = []
# run network over all samples
for i in range(samples):
# forward propagation
output = input_data[i]
for layer in self.layers:
output = layer.forward_propagation(output)
result.append(output)
return np.array(result)
# train the network
def fit(self, x_train, y_train, epochs, learning_rate):
# sample dimension first
samples = len(x_train)
# training loop
for i in (range(epochs)):
# apply SGD
err = 0
perm = np.random.permutation(samples)
for idx in perm:
x = x_train[idx].reshape(1,-1)
y = y_train[idx].reshape(1,-1)
# breakpoint()
# forward propagation
for layer in self.layers:
x = layer.forward_propagation(x)
y_pred = x
err += self.loss(y, y_pred)
error = self.loss_prime(y, y_pred)
for layer in reversed(self.layers):
error = layer.backward_propagation(error, learning_rate)
err /= samples
print('epoch %d/%d error=%f' % (i+1, epochs, err))
errs.append(err)
def logistic(y_true, y_pred):
return np.mean(-y_true * np.log(y_pred) - (1 - y_true) * np.log(1 - y_pred))
def logistic_prime(y_true, y_pred):
return -y_true/(y_pred) + (1-y_true)/(1-y_pred)
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigmoid_prime(x):
return sigmoid(x)*(1-sigmoid(x))
def standardize(X):
mean = np.mean(X,axis=0)
std = np.std(X,axis=0)
return (X-mean)/std
def plot_loss_curve():
plt.cla()
window_size = 100
weights = np.repeat(1.0, window_size) / window_size
moving_avg_errs = np.convolve(errs, weights, 'valid')
plt.plot(moving_avg_errs, '-bx',label='train')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.title('Loss vs. No. of epochs')
plt.legend()
plt.savefig('loss_curve.png')
if __name__ == '__main__':
errs = []
# read datapoints from csv file
hw_scores = pd.read_csv(os.path.join('hw1_dataset','Problem 2','Averaged homework scores.csv'))
final_scores = pd.read_csv(os.path.join('hw1_dataset','Problem 2','Final exam scores.csv'))
results = pd.read_csv(os.path.join('hw1_dataset','Problem 2','Results.csv'))
X = standardize(np.array(hw_scores))
Y = standardize(np.array(final_scores))
Z = np.array(results)
data = np.concatenate((X,Y,Z),axis=1)
train_data = data[:400,:]
test_data = data[400:,:]
X_train = train_data[:,:2].reshape(-1, 2)
Y_train = train_data[:,2].reshape(-1, 1)
X_test = test_data[:,:2].reshape(-1, 2)
Y_test = test_data[:,2].reshape(-1, 1)
# breakpoint()
# create network
net = Network([Linear(2, 1),ActivationLayer(sigmoid, sigmoid_prime)])
# train
net.use(logistic, logistic_prime)
net.fit(X_train, Y_train, epochs=1000, learning_rate=0.01)
# plot the prediction
plt.scatter(X_test[:,0],X_test[:,1],c=Y_test)
# calculate the loss on test_set
out = net.predict(X_test)
loss = logistic(Y_test,out)
print('loss on test set: ', loss)
# plot the decision boundary
x1 = np.linspace(-2,2,100)
x2 = np.linspace(-2,2,100)
x1,x2 = np.meshgrid(x1,x2)
x1 = x1.reshape(-1,1)
x2 = x2.reshape(-1,1)
X = np.concatenate((x1,x2),axis=1)
y = net.predict(X).reshape(100,100)
plt.contour(np.linspace(-2,2,100),np.linspace(-2,2,100),y,levels=[0.5])
plt.xlabel('Homework score')
plt.ylabel('Final score')
# plt.legend()
plt.savefig('problem2.png')
plot_loss_curve() |
import axios from 'axios';
import { logger } from '../logger';
import { generateFUBHeader } from './generate-fub-header';
export const getPersonIdByPhoneNumber = async (apiKey: string, phone: string, logPrefix: string): Promise<number> => {
const url = process.env.FUB_API_ENDPOINT + '/people?phone=' + phone;
try {
logger.debug({ eventType: `${logPrefix}fetch-people-by-phone-input`, data: { url } });
const res = await axios.get(url, {
headers: generateFUBHeader(apiKey),
});
const { data } = res;
logger.debug({ eventType: `${logPrefix}fetch-people-by-phone-output`, data });
const people = data?.people ?? [];
if (!people.length) {
throw new Error(`No people found for phone number ${phone}`);
}
return people[0].id;
} catch (err) {
logger.error({ eventType: `${logPrefix}fetch-people-by-phone-error`, data: { url, err } });
throw err;
}
}; |
import json, math
from collections import defaultdict, Counter, OrderedDict
import re
from itertools import chain
import multiprocessing
import json
from decimal import Decimal
import argparse
import os
import sys
class PMICalculator:
"""Code to read the SNLI corpus and calculate PMI association metrics on it.
"""
def __init__(self, infile = 'snli_1.0/snli_1.0_dev.jsonl', label_filter=None):
self.infile = infile
self.label_filter = label_filter # restricts the set of examples to read
# mappings of words to indices of documents in which they appear
self.premise_vocab_to_docs = defaultdict(set)
self.hypothesis_vocab_to_docs = defaultdict(set)
self.n_docs = 0
self.COUNT_THRESHOLD = 10
def preprocess(self):
"""
Read in the SNLI corpus and accumulate word-document counts to later calculate PMI.
Your first task will be to look at the corpus and figure out how to read in its format.
One hint - each line in the '.jsonl' files is a json object that can be read into a python
dictionary with: json.loads(line)
The corpus provides pre-tokenized and parsed versions of the sentences; you should use this
existing tokenization, but it will require getting one of the parse representations and
manipulating it to get just the tokens out. I recommend using the _binary_parse one.
Remember to lowercase the tokens.
As described in the assignment, instead of raw counts we will use binary counts per-document
(e.g., ignore multiple occurrences of the same word in the document). This works well
in short documents like the SNLI sentences.
To make the necessary PMI calculations in a computationally efficient manner, the code is set up
so that you do this slightly backwards - instead of accumulating counts of words, for each word
we accumulate a set of indices (or other unique identifiers) for the documents in which it appears.
This way we can quickly see, for instance, how many times two words co-occur in documents by
intersecting their sets. Document identifiers can be whatever you want; I recommend simply
keeping an index of the line number in the file with `enumerate` and using this.
You can choose to modify this setup and do the counts for PMI some other way, but I do recommend
going with the way it is.
When loading the data, use the self.label_filter variable to restrict the data you look at:
only process those examples for which the 'gold_label' key matches self.label_filter.
If self.label_filter is None, include all examples.
Finally, once you've loaded everything in, remove all words that don't appear in at least
self.COUNT_THRESHOLD times in the hypothesis documents.
Parameters
----------
None
Returns
-------
None (modifies self.premise_vocab_to_docs, self.hypothesis_vocab_to_docs, and self.n_docs)
"""
'''
{
"annotator_labels": ["neutral", "entailment", "neutral", "neutral", "neutral"],
"captionID": "4705552913.jpg#2",
"gold_label": "neutral",
"pairID": "4705552913.jpg#2r1n",
"sentence1": "Two women are embracing while holding to go packages.",
"sentence1_binary_parse": "( ( Two women ) ( ( are ( embracing ( while ( holding ( to ( go packages ) ) ) ) ) ) . ) )",
"sentence1_parse": "(ROOT (S (NP (CD Two) (NNS women)) (VP (VBP are) (VP (VBG embracing) (SBAR (IN while) (S (NP (VBG holding)) (VP (TO to) (VP (VB go) (NP (NNS packages)))))))) (. .)))",
"sentence2": "The sisters are hugging goodbye while holding to go packages after just eating lunch.",
"sentence2_binary_parse": "( ( The sisters ) ( ( are ( ( hugging goodbye ) ( while ( holding ( to ( ( go packages ) ( after ( just ( eating lunch ) ) ) ) ) ) ) ) ) . ) )",
"sentence2_parse": "(ROOT (S (NP (DT The) (NNS sisters)) (VP (VBP are) (VP (VBG hugging) (NP (UH goodbye)) (PP (IN while) (S (VP (VBG holding) (S (VP (TO to) (VP (VB go) (NP (NNS packages)) (PP (IN after) (S (ADVP (RB just)) (VP (VBG eating) (NP (NN lunch))))))))))))) (. .)))"
}
{
"annotator_labels": ["entailment", "entailment", "entailment", "entailment", "entailment"],
"captionID": "4705552913.jpg#2",
"gold_label": "entailment",
"pairID": "4705552913.jpg#2r1e",
"sentence1": "Two women are embracing while holding to go packages.",
"sentence1_binary_parse": "( ( Two women ) ( ( are ( embracing ( while ( holding ( to ( go packages ) ) ) ) ) ) . ) )",
"sentence1_parse": "(ROOT (S (NP (CD Two) (NNS women)) (VP (VBP are) (VP (VBG embracing) (SBAR (IN while) (S (NP (VBG holding)) (VP (TO to) (VP (VB go) (NP (NNS packages)))))))) (. .)))", "sentence2": "Two woman are holding packages.",
"sentence2_binary_parse": "( ( Two woman ) ( ( are ( holding packages ) ) . ) )", "sentence2_parse": "(ROOT (S (NP (CD Two) (NN woman)) (VP (VBP are) (VP (VBG holding) (NP (NNS packages)))) (. .)))"
}
{
"annotator_labels": ["contradiction", "contradiction", "contradiction", "contradiction", "contradiction"],
"captionID": "4705552913.jpg#2",
"gold_label": "contradiction",
"pairID": "4705552913.jpg#2r1c",
"sentence1": "Two women are embracing while holding to go packages.",
"sentence1_binary_parse": "( ( Two women ) ( ( are ( embracing ( while ( holding ( to ( go packages ) ) ) ) ) ) . ) )",
"sentence1_parse": "(ROOT (S (NP (CD Two) (NNS women)) (VP (VBP are) (VP (VBG embracing) (SBAR (IN while) (S (NP (VBG holding)) (VP (TO to) (VP (VB go) (NP (NNS packages)))))))) (. .)))",
"sentence2": "The men are fighting outside a deli.",
"sentence2_binary_parse": "( ( The men ) ( ( are ( fighting ( outside ( a deli ) ) ) ) . ) )",
"sentence2_parse": "(ROOT (S (NP (DT The) (NNS men)) (VP (VBP are) (VP (VBG fighting) (PP (IN outside) (NP (DT a) (NNS deli))))) (. .)))"
}
'''
# read in the json data
data = []
for line in open(self.infile, 'r'):
data.append(json.loads(line))
# print(len(data),data[0])
#words only
sentences2 = []
sentences1 = []
#label_filter = contracdition
for i,t in enumerate(data):
if self.label_filter == None or (self.label_filter != None and self.label_filter == t['gold_label']):
#for unigram
tmp2 = t['sentence2'].lower()
words_pattern = '([a-zA-Z]+)'
extracted2 = re.findall(words_pattern, tmp2)
sentences2.append(extracted2)
tmp1 = t['sentence1'].lower()
extracted1 = re.findall(words_pattern, tmp1)
sentences1.append(extracted1)
# print((self.label_filter != None and "contradiction" in t['annotator_labels']), t['annotator_labels'])
# break
#for bi-gram
# tmp = t['sentence1_binary_parse'].lower()
# words_pattern = '([a-zA-Z]+(\s*)[a-zA-Z]*)'
# extracted = re.findall(words_pattern, tmp)
# extracted = [a_tuple[0].strip() for a_tuple in extracted]
# # extracted = list(filter(lambda x: (" " in x), extracted))
# sentences.append(extracted)
# print("!!!!!",len(sentences1), len(sentences2))
self.n_docs = len(sentences1)
flatten_list1 = list(chain.from_iterable(sentences1))
flatten_list2 = list(chain.from_iterable(sentences2))
tmp_count1 = Counter({k: c for k, c in Counter(flatten_list1).items() if c >= self.COUNT_THRESHOLD})
tmp_count2 = Counter({k: c for k, c in Counter(flatten_list2).items() if c >= self.COUNT_THRESHOLD})
# print(len(tmp.keys()),tmp)
print(">> Total Words with freq > thresh in Premise: ", len(tmp_count1.keys()))
print(">> Total Words with freq > thresh in Hypothesis: ", len(tmp_count2.keys()))
for i, w in enumerate(tmp_count1.keys()):
for j, s in enumerate(sentences1):
if w in s:
self.premise_vocab_to_docs[w].add(j)
for i, w in enumerate(tmp_count2.keys()):
for j, s in enumerate(sentences2):
if w in s:
self.hypothesis_vocab_to_docs[w].add(j)
#sort the hypothesis index list
for i,k in enumerate(self.hypothesis_vocab_to_docs.keys()):
self.hypothesis_vocab_to_docs[k] = set(sorted(list(self.hypothesis_vocab_to_docs[k])))
print("✅ finished preprocessing ✅")
# print(tmp_count1['the'])
# print(len(self.premise_vocab_to_docs['the']),self.premise_vocab_to_docs['the'])
# print(len(self.hypothesis_vocab_to_docs['the']),self.hypothesis_vocab_to_docs['the'])
def pmi(self, word1, word2, cross_analysis=True):
"""
Calculate the PMI between word1 and word1. the cross_analysis argument determines
whether we look for word1 in the premise (True) or in the hypothesis (False).
In either case we look for word2 in the hypothesis.
Since we are using binary counts per document, the PMI calculation is simplified.
The numerator will be the number of total number of documents times the number
of times word1 and word2 appear together. The denominator will be the number
of times word1 appears total times the number of times word2 appears total.
Do this using set operations on the document ids (values in the self.*_vocab_to_docs
dictionaries). If either the numerator or denominator is 0 (e.g., any of the counts
are zero), return 0.
Parameters
----------
word1 : str
The first word in the PMI calculation. In the 'cross' analysis type,
this refers to the word from the premise.
word2 : str
The second word in the PMI calculation. In both analysis types, this
is a word from the hypothesis documents.
cross_analysis : bool
Determines where to look up the document counts for word1;
if True we look in the premise, if False we look in the hypothesis.
Returns
-------
float
The pointwise mutual information between word1 and word2.
"""
# The numerator will be [the number of total number of documents] times the number
# of times word1 and word2 appear together. The denominator will be the number
# of times word1 appears total times the number of times word2 appears total.
if not cross_analysis:
set1 = self.hypothesis_vocab_to_docs[word1]
set2 = self.hypothesis_vocab_to_docs[word2]
else:
set1 = self.premise_vocab_to_docs[word1]
set2 = self.hypothesis_vocab_to_docs[word2]
# print(set1, set2)
# print("!!!!",len(set1), len(set2))
intersection = set1.intersection(set2)
numerator = self.n_docs * len(intersection)
denominator = len(set1) * len(set2)
# print("Intersection: ",len(intersection),self.n_docs * len(intersection))
# print("✅ finished pmi calculation ✅ ",numerator,denominator )
# print(self.n_docs, "*", len(intersection), "/", len(set1), "*", len(set2))
# print(numerator,"/",denominator, "=",numerator/denominator)
if denominator == 0 or numerator == 0:
return 0.0
return math.log2(numerator/denominator)
def print_top_associations(self, target, n=10, cross_analysis=True):
"""
Function to print the top associations by PMI across the corpus with
a given target word. This is for qualitative use and
Since `word2` in the PMI calculation will always use counts in the
hypothesis, you'll want to loop over all words in the hypothesis vocab.
Calculate PMI for each relative to the target, and print out the top n
words with the highest values.
"""
results = defaultdict()
for _,w in enumerate(self.hypothesis_vocab_to_docs.keys()):
# totalLen = len(self.hypothesis_vocab_to_docs[target])
# if(i%100 == 0):
# print("progress: ", i, "/", totalLen)
calculated = self.pmi(target, w, cross_analysis)
# print(w, target, cross_analysis, calculated)
results[w] = calculated
# print(results)
filtered_results = dict(sorted(results.items(), key=lambda x: x[1], reverse=True)[:n])
writing = {target: filtered_results}
return writing
# print(printing)
# print("✅ finished pmi calculation ✅ ",numerator,denominator )
def flatten_list(inputlist):
return list(chain.from_iterable(inputlist))
def getTupleList(inputlist):
return [a_tuple[0] for a_tuple in inputlist]
def setArgparse():
parser = argparse.ArgumentParser(description='run PMI with the following specifications')
parser.add_argument('--dir', default='snli_1.0/snli_1.0_dev.jsonl', help='input directory and name of training data')
parser.add_argument('--filter', default=None,
help='[None, "neutral", "entailment", "contradiction"]')
parser.add_argument('-ca','--ca', action='store_true', help='doing cross analysis?')
# parser.add_argument('--thresh', default='10',
# help='a number that defines the COUNT_THRESHOLD to be filtered on')
parser.add_argument('--topAssoc', default='10',
help='a number that defines top-n assiciations will be returned')
parser.add_argument('--keyword', default='dog',
help='a keyword to run top associations')
parser.add_argument('--keywords',
help='the txt contains keywords to run print_top_associations')
parser.add_argument('--out', default='PMI_results.txt',
help='output file directory and name')
args = parser.parse_args()
if args.filter not in ["neutral", "entailment", "contradiction"]:
print("ERROR: --filter set to None because the input is not in [\"neutral\", \"entailment\", \"contradiction\"]")
args.filter = None
try:
args.topAssoc = int(args.topAssoc)
except:
print("ERROR: please enter a valid positive integer")
args.topAssoc = 10
return args
def readtxt(fname):
lines = []
with open(fname) as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
return lines
def write2Json(writing, outName):
out_file = open(outName, "w")
printing = json.dump(writing, out_file, indent=4)
out_file.close()
if __name__ == '__main__':
print("Start testing...")
args = setArgparse()
print(args, args.dir, args.filter, args.ca, args.topAssoc)
calculator = PMICalculator(args.dir, args.filter)
calculator.preprocess()
outList = []
if args.keywords != None:
print("📁 working with all the text in ", args.keywords)
#read in the txt files
keywords = readtxt(args.keywords)
print(keywords)
for k in keywords:
outList.append(calculator.print_top_associations(k, args.topAssoc, args.ca))
else:
outList.append(calculator.print_top_associations(args.keyword, args.topAssoc, args.ca))
if args.out == None or args.out == "":
args.out = "results.json"
write2Json(outList, args.out)
# testing PMI
# print(">> Testing PMI: ", all_labels.pmi('man','beast'))
# # #3.6915
# print(">> Testing PMI: ", all_labels.pmi('dog', 'frisbee', cross_analysis=False))
#test contradiction
# all_labels = PMICalculator(label_filter='contradiction')
# all_labels.preprocess()
# print(">> Testing PMI: ", all_labels.pmi('boat','fish', cross_analysis=True)) |
const CACHE_NAME = "version-1";
const urlsToCache = ["index.html", "public.html"];
const self = this;
// Install SW
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log("Opened cache");
return cache.addAll(urlsToCache);
})
);
});
// Listen for requests
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then(() => {
return fetch(event.request).catch(() => caches.match("offline.html"));
})
);
});
// Activate the SW
self.addEventListener("activate", (event) => {
const cacheWhitelist = [];
cacheWhitelist.push(CACHE_NAME);
event.waitUntil(
caches.keys().then((cacheNames) =>
Promise.all(
cacheNames.map((cacheName) => {
if (!cacheWhitelist.includes(cacheName)) {
return caches.delete(cacheName);
}
})
)
)
);
});
self.addEventListener("push", async (event) => {
const message = await event.data.json();
let { title, image, description } = message;
console.log({ message });
await event.waitUntil(
self.registration.showNotification(title, {
body: description,
icon: image,
actions: [
{
action: "alert-action",
title: "Alert Raised!",
},
],
})
);
}); |
// -- Interface --
interface Product {
readonly code: number
name: string
colour?: string
price: number
}
const product1: Product = {
code: 9001,
name: 'Summer Candy Skirt',
price: 1200
}
// -- Interface Method
interface Person {
name: string
age: number
info: () => void
}
const person1: Person = {
name: 'Peter',
age: 1,
info() {
console.log(`Last update: ${new Date().toLocaleTimeString()}`)
}
}
// person1.name = 'Wendy'
// console.log(person1.info())
// console.log(person1)
// -- Extended Interface --
interface Pet {
petName: string
petType: string
petBirth: string
}
interface CloseFriend {
cfName: string
cfCountry: string
}
interface User extends Pet, CloseFriend {
name: string
country: string
}
let account1: User = {
name: 'Lala',
country: 'China',
petName: 'Leo',
petType: 'Cat',
petBirth: '12/12/2002',
cfName: 'Kim',
cfCountry: 'US'
} |
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <array>
#include <algorithm>
#include <numeric>
#include "shader.h"
Shader::Shader(const std::string& vertexShaderPath, const std::string fragmentShaderPath, const std::string& geometryShaderPath) {
createProgram(vertexShaderPath, fragmentShaderPath, geometryShaderPath);
glUseProgram(program);
int count;
glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &count);
uniforms.resize(count);
std::array<GLchar, BUFFER_SIZE> data;
int length;
for (unsigned int i = 0; i < count; i++) {
auto& uniform = uniforms[i];
glGetActiveUniform(program, i, BUFFER_SIZE, &length, &uniform.size, &uniform.type, data.data());
uniform.name = std::string(data.data());
uniformLocations.insert({ uniform.name, glGetUniformLocation(program, uniform.name.c_str()) });
}
glGetProgramiv(program, GL_ACTIVE_ATTRIBUTES, &count);
attributes.resize(count);
// TODO create helper function
for (unsigned int i = 0; i < count; i++) {
auto& attribute = attributes[i];
glGetActiveAttrib(program, i, BUFFER_SIZE, &length, &attribute.size, &attribute.type, data.data());
attribute.name = std::string(data.data());
}
glGetProgramiv(program, GL_ACTIVE_UNIFORM_BLOCKS, &count);
for (unsigned int i = 0; i < count; i++) {
int size;
glGetActiveUniformBlockiv(program, i, GL_UNIFORM_BLOCK_NAME_LENGTH, &length);
glGetActiveUniformBlockName(program, i, length, nullptr, data.data());
std::string blockName = std::string(data.data());
auto& uniformBlock = uniformBlocks[blockName];
glGetActiveUniformBlockiv(program, i, GL_UNIFORM_BLOCK_DATA_SIZE, &uniformBlock.size);
uniformBlock.index = glGetUniformBlockIndex(program, blockName.c_str());
}
}
Shader::~Shader() {
glDeleteProgram(program);
}
std::string Shader::parseShader(const std::string& path) {
std::fstream source(path);
std::stringstream file;
std::string line;
std::string currentStruct;
while (getline(source, line)) {
file << line << '\n';
}
return file.str();
}
unsigned int Shader::compileShader(const std::string& path, int shaderType) {
unsigned int id = glCreateShader(shaderType);
const std::string vertexSource = parseShader(path);
const char* sourcePointer = &vertexSource[0];
glShaderSource(id, 1, &sourcePointer, nullptr);
glCompileShader(id);
int shaderCompiled;
glGetShaderiv(id, GL_COMPILE_STATUS, &shaderCompiled);
if (shaderCompiled == GL_FALSE) {
std::cout << "Shader compilation error in file " << path << std::endl;
int logLength;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &logLength);
char* message = new char[logLength];
glGetShaderInfoLog(id, logLength, nullptr, message);
std::cout << message << std::endl;
delete[] message;
}
return id;
}
bool Shader::linkValidateError() {
int programLinked;
int programValidated;
glGetProgramiv(program, GL_LINK_STATUS, &programLinked);
glGetProgramiv(program, GL_VALIDATE_STATUS, &programValidated);
if (programLinked == GL_FALSE || programValidated == GL_FALSE) {
int logLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength);
char* message = new char[logLength];
glGetProgramInfoLog(program, logLength, nullptr, message);
std::cout << message << std::endl;
delete[] message;
return true;
}
return false;
}
void Shader::createProgram(const std::string& vertexPath, const std::string& fragmentPath, const std::string& geometryPath) {
unsigned int vertexShader = compileShader(vertexPath, GL_VERTEX_SHADER);
unsigned int geometryShader = (geometryPath != "") ? compileShader(geometryPath, GL_GEOMETRY_SHADER) : 0;
unsigned int fragmentShader = compileShader(fragmentPath, GL_FRAGMENT_SHADER);
program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
if (geometryPath != "")
glAttachShader(program, geometryShader);
glLinkProgram(program);
glValidateProgram(program);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
if (geometryPath != "")
glDeleteShader(geometryShader);
linkValidateError();
}
template<>
void Shader::modifyUniform<glm::mat4>(const std::string& name, const glm::mat4& matrix) {
glUniformMatrix4fv(uniformLocations[name], 1, GL_FALSE, glm::value_ptr(matrix));
}
template<>
void Shader::modifyUniform<glm::mat3>(const std::string& name, const glm::mat3& matrix) {
glUniformMatrix3fv(uniformLocations[name], 1, GL_FALSE, glm::value_ptr(matrix));
}
template<>
void Shader::modifyUniform<glm::vec3>(const std::string& name, const glm::vec3& vector) {
glUniform3f(uniformLocations[name], vector.x, vector.y, vector.z);
}
template<>
void Shader::modifyUniform<int>(const std::string& name, const int& number) {
glUniform1i(uniformLocations[name], number);
}
template<>
void Shader::modifyUniform<float>(const std::string& name, const float& number) {
glUniform1f(uniformLocations[name], number);
}
template<>
void Shader::modifyUniform<bool>(const std::string& name, const bool& term) {
glUniform1i(uniformLocations[name], term);
}
unsigned int Shader::getProgram() const {
return program;
}
const Shader::UniformBlock& Shader::getUniformBlock(const std::string& name) {
return uniformBlocks[name];
}
void Shader::use() const {
glUseProgram(program);
}
void Shader::unUse() const {
glUseProgram(0);
} |
#ifndef SOFA_SpringInteractor_H
#define SOFA_SpringInteractor_H
#include <SofaSimpleGUI/config.h>
#include "Interactor.h"
#include <sofa/component/statecontainer/MechanicalObject.h>
#include <sofa/component/solidmechanics/spring/StiffSpringForceField.h>
#include <sofa/defaulttype/VecTypes.h>
namespace sofa{
namespace simplegui{
using sofa::defaulttype::Vec3Types ;
using MechanicalObject3 = sofa::component::statecontainer::MechanicalObject<Vec3Types> ;
using StiffSpringForceField3 = sofa::component::solidmechanics::spring::StiffSpringForceField<Vec3Types> ;
/**
* @brief Interaction using a spring.
* An interactor, typically attached to the mouse pointer, pulls a control point using a spring.
* @author Francois Faure, 2014
*/
class SOFA_SOFASIMPLEGUI_API SpringInteractor: public Interactor
{
typedef Interactor Inherited;
protected:
MechanicalObject3::SPtr _interactorDof;
StiffSpringForceField3::SPtr _spring;
public:
/**
* @brief SpringInteractor
* @param picked The picked point.
* @param stiffness The stiffness of the spring attached to the picked point.
*/
SpringInteractor(const PickedPoint& picked, SReal stiffness=(SReal) 100.);
/// Insert this in the scene as a child of the given node
void attach( SofaScene* scene ) override;
/// Remove this from the scene, without destroying it.
void detach() override;
/// current interaction point
Vec3 getPoint() override;
/// Displace the interaction to the given point
void setPoint( const Vec3& p ) override;
};
}
}
#endif // SOFA_SpringInteractor_H |
package com.example.dinder;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.intent.Intents.intended;
import static androidx.test.espresso.intent.Intents.intending;
import static androidx.test.espresso.intent.matcher.IntentMatchers.anyIntent;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static com.example.dinder.utils.TestUtils.awaitTransition;
import static org.hamcrest.CoreMatchers.not;
import android.app.Activity;
import android.app.Instrumentation;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.espresso.IdlingRegistry;
import androidx.test.espresso.intent.Intents;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.android.volley.RequestQueue;
import com.example.dinder.activities.LoginActivity;
import com.example.dinder.activities.UserHomeActivity;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class LoginActivityTest {
private VolleyIdlingResource idlingResource;
@Before
public void setUp() {
// Initialize Espresso Intents before each test
Intents.init();
// Register Idling Resource
RequestQueue queue = VolleySingleton.getInstance(ApplicationProvider.getApplicationContext()).getRequestQueue();
idlingResource = new VolleyIdlingResource(queue);
IdlingRegistry.getInstance().register(idlingResource);
}
@After
public void tearDown() {
// Release Espresso Intents after each test
Intents.release();
// Unregister idling resource
if (idlingResource != null) {
IdlingRegistry.getInstance().unregister(idlingResource);
}
loginScenario.getScenario().onActivity(Activity::finish);
}
@Rule
public ActivityScenarioRule<LoginActivity> loginScenario = new ActivityScenarioRule<>(LoginActivity.class);
@Test
public void testLoginSuccess() {
// Enter valid username and password
onView(withId(R.id.editTextUsername)).perform(typeText("MrEthan"), closeSoftKeyboard());
onView(withId(R.id.editTextPassword)).perform(typeText("johndeere"), closeSoftKeyboard());
// Click on the login button
onView(withId(R.id.loginBtn)).perform(click());
awaitTransition(1000);
// Check if the UserHomeActivity is started
intended(hasComponent(UserHomeActivity.class.getName()));
}
@Test
public void testLoginFailure() {
// Enter invalid username and password
onView(withId(R.id.editTextUsername)).perform(typeText("MrEthan"), closeSoftKeyboard());
onView(withId(R.id.editTextPassword)).perform(typeText("notjohndeere"), closeSoftKeyboard());
// Click on the login button
onView(withId(R.id.loginBtn)).perform(click());
awaitTransition(1000);
// Assert that the UserHomeActivity intent doesn't exist
intending(not(anyIntent())).respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
}
} |
import { fetchDoctors } from "@/services/fetchDoctors"
import { useEffect, useState } from "react"
import { useDebounce } from "./useDebouncer"
export const useDoctors = () => {
const [doctors, setDoctors] = useState([])
const [inputValue, setInputValue] = useState('')
const [selectedSpecialty, setSelectedSpecialty] = useState('')
const [selectedLocation, setSelectedLocation] = useState('')
useEffect(() => {
const fetch = async () => {
const data = await fetchDoctors()
setDoctors(data)
}
fetch()
}, [])
const debouncedInput = useDebounce(inputValue, 300)
const filteredDoctors = doctors.filter(({ speciality, name, location }) => {
const hasSelectedLocation = selectedLocation !== '';
const hasSelectedSpecialty = selectedSpecialty !== '';
if (!hasSelectedLocation && !hasSelectedSpecialty && inputValue === '') {
return true;
} else if (hasSelectedLocation && hasSelectedSpecialty) {
return location === selectedLocation && speciality === selectedSpecialty && name.toLowerCase().includes(debouncedInput.toLowerCase());
} else if (hasSelectedLocation) {
return location === selectedLocation && name.toLowerCase().includes(debouncedInput.toLowerCase());
} else if (hasSelectedSpecialty) {
return speciality === selectedSpecialty && name.toLowerCase().includes(debouncedInput.toLowerCase());
} else {
return name.toLowerCase().includes(debouncedInput.toLowerCase());
}
});
return {doctors, filteredDoctors, setInputValue, setSelectedLocation, setSelectedSpecialty}
} |
<?php
/**
* Copyright (C) 2024 Daniel Fernández Giménez <hola@danielfg.es>
*/
namespace FacturaScripts\Plugins\PortalCliente\Controller;
use FacturaScripts\Core\Base\DataBase\DataBaseWhere;
use FacturaScripts\Core\Cache;
use FacturaScripts\Core\Session;
use FacturaScripts\Core\Tools;
use FacturaScripts\Dinamic\Lib\PortalPanelController;
use FacturaScripts\Dinamic\Model\Contacto;
use Symfony\Component\HttpFoundation\Cookie;
/**
* @author Daniel Fernández Giménez <hola@danielfg.es>
*/
class PortalLogin extends PortalPanelController
{
const LOGIN_TEMPLATE = 'PortalLogin';
const MAX_ATTEMPTS = 6;
const MAX_TIME = 600;
/** @var string */
public $pc_nick;
/** @var string */
public $return;
/** @var array */
private static $blocked_nicks;
/** @var array */
private static $blocked_ips;
public static function blockNick(string $nick, ?int $time = null): void
{
self::loadBlockedNickList();
if (isset(self::$blocked_nicks[$nick])) {
self::$blocked_nicks[$nick]['attempts']++;
self::$blocked_nicks[$nick]['last'] = ($time ?? time());
} else {
self::$blocked_nicks[$nick] = [
'attempts' => 1,
'last' => ($time ?? time()),
];
}
Cache::set('portal-cliente-blocked-email-list', self::$blocked_nicks);
}
public static function blockIp(string $ip, ?int $time = null): void
{
self::loadBlockedIpList();
if (isset(self::$blocked_ips[$ip])) {
self::$blocked_ips[$ip]['attempts']++;
self::$blocked_ips[$ip]['last'] = ($time ?? time());
} else {
self::$blocked_ips[$ip] = [
'attempts' => 1,
'last' => ($time ?? time()),
];
}
Cache::set('portal-cliente-blocked-ip-list', self::$blocked_ips);
}
public static function isIpBlocked(string $ip): bool
{
self::loadBlockedIpList();
foreach (self::$blocked_ips as $key => $value) {
if ($key === $ip && $value['attempts'] >= self::MAX_ATTEMPTS) {
return true;
}
}
return false;
}
public static function isNickBlocked(string $nick): bool
{
self::loadBlockedNickList();
foreach (self::$blocked_nicks as $key => $value) {
if ($key === $nick && $value['attempts'] >= self::MAX_ATTEMPTS) {
return true;
}
}
return false;
}
protected function createViews()
{
if (empty($this->contact)) {
$this->return = $this->request->get('return', 'PortalCliente');
$this->pc_nick = $this->request->get('pc_nick', '');
$this->setTemplate(self::LOGIN_TEMPLATE);
$this->title = Tools::lang()->trans('login');
return;
}
$this->redirect('PortalCliente');
}
/**
* @param string $action
*
* @return bool
*/
protected function execPreviousAction($action)
{
if ($action === 'login') {
return $this->loginAction();
}
return parent::execPreviousAction($action);
}
protected static function loadBlockedIpList(): void
{
if (is_null(self::$blocked_ips)) {
self::$blocked_ips = Cache::remember('portal-cliente-blocked-ip-list', function () {
return [];
});
}
// quitamos los registros antiguos
$time = time();
foreach (self::$blocked_ips as $key => $value) {
if ($value['last'] < ($time - self::MAX_TIME)) {
unset(self::$blocked_ips[$key]);
}
}
}
protected static function loadBlockedNickList(): void
{
if (is_null(self::$blocked_nicks)) {
self::$blocked_nicks = Cache::remember('portal-cliente-blocked-nick-list', function () {
return [];
});
}
// quitamos los registros antiguos
$time = time();
foreach (self::$blocked_nicks as $key => $value) {
if ($value['last'] < ($time - self::MAX_TIME)) {
unset(self::$blocked_nicks[$key]);
}
}
}
protected function loadData($viewName, $view)
{
$this->hasData = true;
}
protected function loginAction(): bool
{
// obtenemos la contraseña
$password = $this->request->request->get('pc_password', '');
if (false === $this->validateFormToken()) {
return false;
} elseif ($this->isIpBlocked(Session::getClientIp())) {
// evitamos ataques de fuerza bruta
Tools::log()->warning('ip-banned');
return false;
} elseif (self::isNickBlocked($this->pc_nick)) {
Tools::log()->warning('nick-blocked', ['%nick%' => $this->pc_nick]);
return false;
}
// evitamos ataques con contraseñas muy largas
if (strlen($password) > 100) {
Tools::log()->warning('password-too-long');
$this->blockNick($this->pc_nick);
$this->blockIp(Session::getClientIp());
return false;
}
// buscamos el contacto
$contact = new Contacto();
$where = [new DataBaseWhere('pc_nick', $this->pc_nick)];
if (false === $contact->loadFromCode('', $where)) {
Tools::log()->warning('nick-not-found', ['%nick%' => $this->pc_nick]);
$this->blockNick($this->pc_nick);
$this->blockIp(Session::getClientIp());
return false;
}
// comprobamos si está activo
if (false === $contact->pc_active) {
Tools::log()->warning('inactive-contact', ['%nick%' => $this->pc_nick]);
self::blockNick($contact->pc_nick);
self::blockIp(Session::getClientIp());
return false;
}
// comprobamos la contraseña
if (false === $contact->verifyPCPassword($password)) {
Tools::log()->warning('wrong-password');
self::blockNick($contact->pc_nick);
self::blockIp(Session::getClientIp());
return false;
}
// actualizamos la semilla de tokens
$this->multiRequestProtection->addSeed($contact->idcontacto);
// actualizamos la actividad
$contact->newPCLogkey();
$contact->updatePCActivity($this->response->headers->get('User-Agent'));
$contact->save();
// guardamos las cookies
$expire = time() + FS_COOKIES_EXPIRE;
$this->response->headers->setCookie(
Cookie::create('pc_idcontacto', $contact->idcontacto, $expire, Tools::config('route', '/'))
);
$this->response->headers->setCookie(
Cookie::create('pc_log_key', $contact->pc_log_key, $expire, Tools::config('route', '/'))
);
$this->contact = $contact;
// redireccionamos
if (empty($this->return)) {
$this->redirect('PortalCliente');
return true;
}
$this->redirect($this->return);
return true;
}
} |
import { getCustomRepository, getRepository } from 'typeorm';
import AppError from '../errors/AppError';
import TransactionsRepository from '../repositories/TransactionsRepository';
import Transaction from '../models/Transaction';
import Category from '../models/Category';
interface Request {
title: string;
value: number;
type: string;
category: string;
}
class CreateTransactionService {
public async execute({
title,
value,
type,
category,
}: Request): Promise<Transaction> {
if (type !== 'income' && type !== 'outcome') {
throw new AppError('This type of transaction is not valid', 401);
}
const transactionsRepository = getCustomRepository(TransactionsRepository);
if (type === 'outcome') {
const balance = await transactionsRepository.getBalance();
if (value > balance.total) {
throw new AppError(
"Haven't no balance to create this transaction.",
400,
);
}
}
const categoryRepository = getRepository(Category);
let currentCategory = await categoryRepository.findOne({
where: { title: category },
});
if (!currentCategory) {
currentCategory = categoryRepository.create({
title: category,
});
await categoryRepository.save(currentCategory);
}
const transaction = transactionsRepository.create({
title,
value,
type,
category_id: currentCategory.id,
});
await transactionsRepository.save(transaction);
return transaction;
}
}
export default CreateTransactionService; |
#include <stdio.h>
#include "includes/debug.h"
#include "includes/chunk.h"
#include "includes/value.h"
void disassemble_chunk(Chunk* chunk, const char* name) {
printf("== %s ==\n", name);
// chunk_info(chunk, name);
for (int offset = 0; offset < chunk->count;) {
offset = disassemble_instruction(chunk, offset);
}
}
int disassemble_instruction(Chunk* chunk, int offset) {
printf("%04d ", offset);
uint8_t instruction = chunk->code[offset];
// printf("instruction: %d", instruction);
switch (instruction) {
case OP_RETURN:
// printf("inside the OP_RETURN case");
return simple_instruction("OP_RETURN", offset);
case OP_CONSTANT: // actually takes an operand, the index to the constant stored in the constant pool
return constant_instruction("OP_CONSTANT", chunk, offset);
case OP_NIL:
return simple_instruction("OP_NIL", offset);
case OP_TRUE:
return simple_instruction("OP_TRUE", offset);
case OP_FALSE:
return simple_instruction("OP_FALSE", offset);
case OP_NEGATE:
return simple_instruction("OP_NEGATE", offset);
case OP_NOT:
return simple_instruction("OP_NOT", offset);
case OP_ADD: // even though the arithmetic operators take operands, the bytecode instructions DO NOT
return simple_instruction("OP_ADD", offset);
case OP_SUBTRACT:
return simple_instruction("OP_SUBTRACT", offset);
case OP_MULTIPLY:
return simple_instruction("OP_MULTIPLY", offset);
case OP_DIVIDE:
return simple_instruction("OP_DIVIDE", offset);
default:
printf("Unknown opcode %d\n", instruction);
return offset + 1;
}
}
int simple_instruction(const char* name, int offset) {
printf("%s\n", name);
return offset + 1;
}
int constant_instruction(const char* name, Chunk* chunk, int offset) {
uint8_t const_idx = chunk->code[offset + 1];
printf("%-16s %4d ", name, const_idx);
Value constant = chunk->constants.values[const_idx];
print_value(constant);
printf("\n");
return offset + 2;
}
void chunk_info(Chunk* chunk, const char* name) {
printf("== %s ==\n", name);
printf("chunk->count: %d\t\tchunk->capacity: %d\n", chunk->count, chunk->capacity);
printf("ValueArr->count: %d\tValueArr->capacity: %d\n", chunk->constants.count, chunk->constants.capacity);
} |
namespace BinaryTrees {
// binary_trees, from the Computer Language Benchmarks Game.
// http://benchmarksgame.alioth.debian.org/u64q/binarytrees-description.html#binarytrees
// This implementation is loosely based on:
// http://benchmarksgame.alioth.debian.org/u64q/program.php?test=binarytrees&lang=fsharpcore&id=8
enum Tree {
case Singleton,
case Node(Tree, Tree)
}
def minHeight(): Int = 4
def maxHeight(): Int = 16
def makeTree(height: Int): Tree =
if (height > 0)
Node(makeTree(height - 1), makeTree(height - 1))
else
Singleton
def computeChecksum(tree: Tree): Int = match tree with {
case Node(ls, rs) => computeChecksum(ls) + computeChecksum(rs) + 1
case Singleton => 1
}
def stretchTreeChecksum(): Int = computeChecksum(makeTree(maxHeight() + 1))
def calculateHeights(h: Int): List[Int] = if (h > maxHeight()) Nil else h :: calculateHeights(h + 2)
def treeFrequency(height: Int): Int = 1 <<< (maxHeight() - height + minHeight())
def calculateChecksumOfTrees(height: Int, number: Int, acc: Int): Int =
if (number > 0)
calculateChecksumOfTrees(height, number - 1, computeChecksum(makeTree(height)) + acc)
else
acc
@benchmark
def binaryTrees(): List[Int] =
let temp_Tree_Checksum = stretchTreeChecksum();
let long_Lived_Tree = makeTree(maxHeight());
let height_list = calculateHeights(minHeight());
List.map(height -> calculateChecksumOfTrees(height, treeFrequency(height), 0), height_list)
} |
//throttle 节流
function throttle(fn, interval, options = { leading: true, trailing: false }) {
//1.记录上一次的开始时间
const { leading, trailing } = options; //控制首次,尾次是否触发函数
let lastTime = 0;
//2.事件触发时,真正执行的函数
const _throttle = function () {
//2.1获取事件触发的当前时间
const nowTime = new Date().getTime();
if (!lastTime && !leading) lastTime = nowTime; //当首次进入,且leading设置为false 执行,使remainTime =0
//2.2 当前触发时间 和 上一次触发的时间 相减,与我设置的时间对比,是否到达了
const remainTime = interval - (nowTime - lastTime);
if (remainTime <= 0) {
//2.3时间到达,真正触发函数
fn.apply(this, args);
//2.4 保留上次触发的时间
lastTime = nowTime;
}
};
return _throttle;
} |
//Copyright © 2023 Charles Kerr. All rights reserved.
import Foundation
/*
HueEntry
WORD ColorTable[32];
WORD TableStart;
WORD TableEnd;
CHAR Name[20];
HueGroup
DWORD Header;
HueEntry Entries[8];
*/
// HueEntry
struct HueEntry {
static public let RECORDSIZE = 88
public var colors = [UInt16](repeating: 0, count: 32)
public var nameData = [UInt8](repeating: 0, count: 20)
}
extension HueEntry {
init(data:Data) {
self.init()
guard data.count >= HueEntry.RECORDSIZE else {
return
}
colors = data.subdata(in: data.startIndex..<data.startIndex+64).uInt16Array
for (index,pixel) in colors.enumerated() {
colors[index] = pixel.withAlpha
}
nameData = data.subdata(in: data.startIndex+68..<data.startIndex+88).uInt8Array
}
public var data:Data {
var rvalue = colors.data
rvalue.append(colors[0].data)
rvalue.append(colors[31].data)
rvalue.append(nameData.data)
return rvalue
}
public var name:String {
nameData.data.nonNullAsciiString
}
}
struct Hue {
static public let MULFILENAME = "hues.mul"
static public let GROUPENTRY = 8
static public let GROUPSIZE = GROUPENTRY * HueEntry.RECORDSIZE + 4
public var entries = [HueEntry]()
}
extension Hue {
init(hueURL url:URL) {
self.init()
guard let exists = try? url.checkResourceIsReachable() else { return }
guard exists else { return }
guard let data = try? Data(contentsOf: url) else { return }
let count = data.count / Hue.GROUPSIZE
entries.reserveCapacity(count * Hue.GROUPENTRY)
for index in 0..<count {
let groupData = data[index*Hue.GROUPSIZE..<(index+1) * Hue.GROUPSIZE]
for groupEntry in 0..<Hue.GROUPENTRY {
entries.append(HueEntry(data: groupData[groupData.startIndex+4 + (groupEntry*HueEntry.RECORDSIZE)..<groupData.startIndex+4 + ((groupEntry+1)*HueEntry.RECORDSIZE)]))
}
}
}
public var data:Data {
var rvalue = Data()
let groupCount = entries.count / Hue.GROUPENTRY // Yes, this means the count must be multiple of "groups"
for groupIndex in 0..<groupCount {
rvalue.append(UInt32(0).data)
for entryIndex in 0..<Hue.GROUPENTRY {
rvalue.append(entries[(groupIndex * Hue.GROUPENTRY) + entryIndex].data)
}
}
return rvalue
}
public var count:Int {
return entries.count
}
} |
// Задача: Создать и добавить стиль для элемента:
// Напишите функцию, которая создает новый элемент, добавляет его в DOM и устанавливает для него стиль с помощью CSS.
//создаем функцию, которая принимает в себя, тег элемента, содержимое объекта и объект стили
function createAndAddElement(tag, content, style) {
//создаем элемент при помощи createElement
const element = document.createElement(tag);
//добавляем ему содержимое
element.textContent = content;
//через цикл проходимся по ключам объекта стилей и добавляем их ему
for (const key in style) {
element.style[key] = style[key];
}
//добавляем созданный элемент в тело документа
document.body.appendChild(element);
}
const element = createAndAddElement('button', 'Элемент', {
'background-color': 'violet',
'color': 'black',
'padding': '20px',
'margin': '10px'
}); |
package com.sll.lib_framework.base.activity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.viewbinding.ViewBinding
import com.sll.lib_framework.base.interfaces.IViewModel
import com.sll.lib_framework.ext.lazyNone
/**
*
*
*
* @author Gleamrise
* <br/>Created: 2023/08/03
*/
abstract class BaseMvvmActivity<VB : ViewBinding, VM : ViewModel> : BaseBindingActivity<VB>(), IViewModel<VM> {
protected val viewModel: VM by lazyNone {
initViewModel()
}
override fun initViewModel(): VM {
return ViewModelProvider(this, getViewModelFactory())[getViewModelClass().java]
}
/**
* 默认使用 [androidx.lifecycle.SavedStateViewModelFactory] 作为默认 Factory
*
* 如果 ViewModel 的构造函数有自定义参数,则需要自己写一个 Factory,然后在这里返回即可
*
*/
override fun getViewModelFactory(): ViewModelProvider.Factory = defaultViewModelProviderFactory
/**
* 传入 ViewModel 的一些额外信息,例如 Intent
* */
override fun getCreationExtras(): CreationExtras = defaultViewModelCreationExtras
} |
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_IEDGECONNECTIVITYBUILDER_H
#define CRYINCLUDE_CRYCOMMON_IEDGECONNECTIVITYBUILDER_H
#pragma once
class IStencilShadowConnectivity;
class CStencilShadowConnectivity;
//
//
class IStencilShadowConnectivity
{
public:
typedef unsigned short vindex; // vertex index (0..0xffff)
// <interfuscator:shuffle>
//! don't forget to call Release for freeing the memory resources
virtual void Release(void) = 0;
//! to keep the interface small and the access fast
//! /return pointer to the internal memory representation (only used within module 3DEngine)
const virtual CStencilShadowConnectivity* GetInternalRepresentation(void) const = 0;
//! for debugging and profiling
//! /param outVertexCount
//! /param outTriangleCount
virtual void GetStats(DWORD& outVertexCount, DWORD& outTriangleCount) = 0;
//! Memorize the vertex buffer in this connectivity object. This is needed if a static object doesn't need this info
virtual void SetVertices(const Vec3* pVertices, unsigned numVertices) = 0;
//! Serializes this object to the given memory block; if it's NULL, only returns
//! the number of bytes required. If it's not NULL, returns the number of bytes written
//! (0 means error, insufficient space)
virtual unsigned Serialize (bool bSave, void* pStream, unsigned nSize, IMiniLog* pWarningLog = NULL) = 0;
//! Calculates the size of this object
virtual void GetMemoryUsage(ICrySizer* pSizer) = 0;
//! If this returns true, then the meshing functions don't need external input of mesh information
//! This is for static objects only
virtual bool IsStandalone() const {return false; };
//! number of orphaned (open) edges
//! /return orphaned (open) count
virtual unsigned numOrphanEdges() const = 0;
// </interfuscator:shuffle>
#ifdef WIN32
//! /param szFilename filename with path (or relative) and extension
//! /return true=success, false otherwise
virtual bool DebugConnectivityInfo(const char* szFilename) = 0;
#endif
};
// (don't copy the interface pointer and don't forget to call Release)
class IEdgeConnectivityBuilder
{
public:
typedef IStencilShadowConnectivity::vindex vindex;
// <interfuscator:shuffle>
virtual ~IEdgeConnectivityBuilder() {}
//! return to the state right after construction
virtual void Reinit(void) = 0;
virtual void SetWeldTolerance (float fTolerance) {}
//! reserves space for the given number of triangles that are to be added
//! /param innNumTriangles
//! /param innNumVertices
virtual void ReserveForTriangles(unsigned innNumTriangles, unsigned innNumVertices) = 0;
//! adds a single triangle to the mesh
//! the triangle is defined by three vertices, in counter-clockwise order
//! these vertex indices will be used later when accessing the array of
//! deformed character/model vertices to determine the shadow volume boundary
//! /param nV0 vertex index one 0..0xffff
//! /param nV1 vertex index two 0..0xffff
//! /param nV2 vertex index three 0..0xffff
virtual void AddTriangle(vindex nV0, vindex nV1, vindex nV2) = 0;
//! slower than AddTriangle but with the auto weld feature (if there are vertices with the same position your result is smaller and therefore faster)
//! /param nV0 vertex index one 0..0xffff
//! /param nV1 vertex index two 0..0xffff
//! /param nV2 vertex index three 0..0xffff
//! /param vV0 original vertex one position
//! /param vV1 original vertex two position
//! /param vV2 original vertex three position
virtual void AddTriangleWelded(vindex nV0, vindex nV1, vindex nV2, const Vec3& vV0, const Vec3& vV1, const Vec3& vV2) = 0;
//! constructs/compiles the optimum representation of the connectivity
//! to be used in run-time
//! WARNING: use Release method to dispose the connectivity object
//! /return
virtual IStencilShadowConnectivity* ConstructConnectivity(void) = 0;
//! returns the number of single (with no pair faces found) or orphaned edges
//! /return
virtual unsigned numOrphanedEdges(void) const = 0;
//! Returns the list of faces for orphaned edges into the given buffer;
//! For each orphaned edge, one face will be returned; some faces may be duplicated
virtual void getOrphanedEdgeFaces (unsigned* pBuffer) = 0;
//! return memory usage
virtual void GetMemoryUsage(class ICrySizer* pSizer) {} // todo: implement
// </interfuscator:shuffle>
};
// *****************************************************************
// used for runtime edge calculations
class IEdgeDetector
{
public:
typedef unsigned short vindex;
// <interfuscator:shuffle>
virtual ~IEdgeDetector(){}
// vertex index
//! for deformable objects
//! /param pConnectivity must not be 0 - don't use if there is nothing to do
//! /param invLightPos
//! /param pDeformedVertices must not be 0 - don't use if there is nothing to do
virtual void BuildSilhuetteFromPos(const IStencilShadowConnectivity* pConnectivity, const Vec3& invLightPos, const Vec3* pDeformedVertices) = 0;
//! for undeformed objects)
//! /param outiNumTriangles, must not be 0 - don't use if there is nothing to do
//! /return pointer to the cleared (set to zero) bitfield where each bit represents the orientation of one triangle
virtual unsigned* getOrientationBitfield(int iniNumTriangles) = 0;
//! /param pConnectivity must not be 0 - don't use if there is nothing to do
//! /param inpVertices must not be 0 - don't use if there is nothing to do
virtual void BuildSilhuetteFromBitfield(const IStencilShadowConnectivity* pConnectivity, const Vec3* inpVertices) = 0;
// pointer to the triplets defining shadow faces
virtual const vindex* getShadowFaceIndices(unsigned& outCount) const = 0;
//! O(1), returs the pointer to an array of unsigned short pairs of vertex numbers
virtual const vindex* getShadowEdgeArray(unsigned& outiNumEdges) const = 0;
//!
//! /return
virtual unsigned numShadowVolumeVertices(void) const = 0;
//! number of indices required to define the shadow volume,
//! use this to determine the size of index buffer passed to meshShadowVolume
//! this is always a dividend of 3
//! /return
virtual unsigned numShadowVolumeIndices(void) const = 0;
//! make up the shadow volume
//! constructs the shadow volume mesh, and puts the mesh definition into the
//! vertex buffer (vertices that define the mesh) and index buffer (triple
//! integers defining the triangular faces, counterclockwise order)
//! /param vLight
//! /param fFactor
//! /param outpVertexBuf The size of the vertex buffer must be at least numVertices()
//! /param outpIndexBuf The size of the index buffer must be at least numIndices()
virtual void meshShadowVolume (Vec3 vLight, float fFactor, Vec3* outpVertexBuf, unsigned short* outpIndexBuf) = 0;
//! get memory usage
virtual void GetMemoryUsage(class ICrySizer* pSizer) {}
// </interfuscator:shuffle>
};
#endif // CRYINCLUDE_CRYCOMMON_IEDGECONNECTIVITYBUILDER_H |
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\PendudukModel;
use App\Models\UmkmKategoriModel;
use App\Models\UmkmModel;
use App\Models\KategoriModel;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class UmkmController extends Controller
{
public function index()
{
$page = 'listUmkm';
$selected = 'Umkm';
$user = PendudukModel::paginate(10);
$umkmKategoris = UmkmKategoriModel::all();
$categories = KategoriModel::all();
$umkms = UmkmModel::select('tb_umkm.*', 'tb_penduduk.nama as pemilik')
->join('tb_penduduk', 'tb_umkm.id_pemilik', '=', 'tb_penduduk.id_penduduk')
->where('status', 'diterima')
->orderBy('updated_at', 'desc')
->paginate(10);
// return $umkms;
return view('Admin.Umkm.index', compact('user', 'page', 'selected', 'umkmKategoris', 'categories', 'umkms'));
}
public function ajuanUmkm()
{
$page = 'ajuanUmkm';
$selected = 'Umkm';
// $user = PendudukModel::paginate(10);
$umkmKategoris = UmkmKategoriModel::all();
$categories = KategoriModel::all();
$umkms = UmkmModel::select('tb_umkm.*', 'tb_penduduk.nama as pemilik')
->join('tb_penduduk', 'tb_umkm.id_pemilik', '=', 'tb_penduduk.id_penduduk')
->where('status', 'diproses')
->paginate(10);
return view('Admin.Umkm.ajuan-umkm', compact('umkms', 'page', 'selected', 'umkmKategoris', 'categories'));
}
public function umkmReject(Request $request)
{
$request->validate([
'alasan' => 'required|string|max:255',
'umkm_id' => 'required|integer',
]);
// return $request->input('alasan');
try {
$umkm_id = $request->umkm_id;
$umkm = UmkmModel::findOrFail($umkm_id);
$umkm->update([
'status' => 'ditolak',
'alasan_rw' => $request->alasan,
'tanggal_ditolak' => now(),
]);
return redirect()->route('ajuan-umkm-admin')->with('success', 'UMKM telah ditolak.');
} catch (\Exception $e) {
return redirect()->route('ajuan-umkm-admin')->with('error', 'Terjadi kesalahan saat menolak UMKM: ' . $e->getMessage());
}
}
public function umkmAccept(Request $request)
{
$request->validate([
'umkm_id' => 'required|integer',
]);
try {
$umkm_id = $request->input('umkm_id');
$umkm = UmkmModel::findOrFail($umkm_id);
$umkm->update([
'status' => 'diterima',
'tanggal_disetujui' => now(),
]);
return redirect()->route('ajuan-umkm-admin')->with('success', 'UMKM telah diterima.');
} catch (\Exception $e) {
return redirect()->route('ajuan-umkm-admin')->with('error', 'Terjadi kesalahan saat menerima UMKM: ' . $e->getMessage());
}
}
public function storeUmkmAdmin(Request $request)
{
// $file = $request->file('foto');
// if ($file) {
// $filename = $file->getClientOriginalName();
// $mimeType = $file->getClientMimeType();
// $fileSize = $file->getSize();
// echo "Nama File: " . $filename . "<br>";
// echo "Tipe File: " . $mimeType . "<br>";
// echo "Ukuran File: " . $fileSize . " bytes<br>";
// } else {
// echo "Tidak ada file yang diunggah.";
// return $request->all();
// }
$validator = Validator::make($request->all(), [
'nama' => 'required|string|max:50',
'pemilik' => 'required|string',
'no_wa' => 'required|string|max:50',
'lokasi' => 'required|string|max:100',
'buka_waktu' => 'required|date_format:H:i',
'tutup_waktu' => 'required|date_format:H:i',
'deskripsi' => 'nullable|string',
'lokasi_map' => 'nullable|string',
'foto' => 'required|image|mimes:jpeg,png,jpg|max:2048',
'kategori' => 'required',
]);
if ($validator->fails()) {
// return $request->all();
return back()->with('errors', $validator->messages()->all()[0])->withInput();
}
// return $request->all();
$pemilik = $request->input('pemilik');
$penduduk = PendudukModel::where('nama', $pemilik)->first();
$id_penduduk = $penduduk->id_penduduk;
$kategori = $request->kategori;
$kategori_id = explode(',', $kategori);
$hashedPhoto = $request->file('foto')->store('UMKM', 'umkm_images');
$umkm = new UmkmModel([
'nama' => $request->nama,
'no_wa' => $request->no_wa,
'id_pemilik' => $id_penduduk,
'lokasi' => $request->lokasi,
'buka_waktu' => $request->buka_waktu,
'tutup_waktu' => $request->tutup_waktu,
'deskripsi' => $request->deskripsi,
'lokasi_map' => $request->lokasi_map,
'foto' => isset($hashedPhoto) ? $hashedPhoto : null,
'status' => 'diterima',
]);
$umkm->save();
$umkm_id = $umkm->getKey();
foreach ($kategori_id as $id) {
$umkmKategori = new UmkmKategoriModel([
'umkm_id' => $umkm_id,
'kategori_id' => $id,
]);
$umkmKategori->save();
}
return redirect()->route('umkm-admin')->with([
'success' => 'Data UMKM berhasil ditambahkan!'
]);
}
public function editUmkm(Request $request, $umkm_id)
{
$validator = Validator::make($request->all(), [
// 'umkm_id' => 'required',
'nama' => 'required|string|max:50',
// 'id_penduduk' => 'required',
'no_wa' => 'nullable|string|max:50',
'lokasi' => 'nullable|string|max:100',
'buka_waktu' => 'nullable|date_format:H:i:s',
'tutup_waktu' => 'nullable|date_format:H:i:s',
'deskripsi' => 'nullable|string',
'lokasi_map' => 'nullable|string',
'foto' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
'kategori' => 'nullable',
// 'alasan' => 'required|string|max:150',
]);
if ($validator->fails()) {
// return $request->all();
return back()->with('errors', $validator->messages()->all()[0])->withInput();
}
$kategori = $request->kategori;
$kategori_id = explode(',', $kategori);
// $umkm_id = $request->umkm_id;
$umkmData = [
'nama' => $request->nama,
// 'id_penduduk' => $request->id_penduduk,
'no_wa' => $request->no_wa,
'lokasi' => $request->lokasi,
'buka_waktu' => $request->buka_waktu,
'tutup_waktu' => $request->tutup_waktu,
'deskripsi' => $request->deskripsi,
'lokasi_map' => $request->lokasi_map,
'status' => 'diterima',
// 'alasan_warga' => $request->alasan,
];
if ($request->hasFile('foto')) {
$fotoPath = $request->file('foto')->store('UMKM', 'umkm_images');
$umkmData['foto'] = $fotoPath;
}
// Hapus field yang memiliki nilai null dari array $umkmData
$umkmData = array_filter($umkmData, function ($value) {
return !is_null($value);
});
UmkmModel::find($umkm_id)->update($umkmData);
if (!is_null($kategori)) {
UmkmKategoriModel::where('umkm_id', $umkm_id)->delete();
foreach ($kategori_id as $id) {
$umkmKategori = new UmkmKategoriModel([
'umkm_id' => $umkm_id,
'kategori_id' => $id,
]);
$umkmKategori->save();
}
}
return redirect(route('umkm-admin'))->with('success', 'UMKM berhasil diperbarui.');
}
public function destroyUmkm($id_umkm)
{
try {
$deleted_fk = UmkmKategoriModel::where('umkm_id', $id_umkm)->delete();
if ($deleted_fk) {
$deleted_umkm = UmkmModel::destroy($id_umkm);
if ($deleted_umkm) {
return redirect(route('umkm-admin'))->with('success', 'Data berhasil dihapus!');
} else {
return redirect(route('umkm-admin'))->with('Gagal menghapus data utama');
}
} else {
return redirect(route('umkm-admin'))->with('Gagal menghapus data anak');
}
} catch (\Exception $e) {
return response()->json(['message' => 'Terjadi kesalahan: ' . $e->getMessage()], 500);
}
}
public function getDataByCategoryDaftar(Request $request)
{
$categories = KategoriModel::all();
$umkms_id = UmkmKategoriModel::where('kategori_id', $request->kategori_id)->pluck('umkm_id');
$umkms = UmkmModel::whereIn('umkm_id', $umkms_id)
->where('status', 'diterima')
->paginate(10);
$page = 'listUmkm';
$selected = 'Umkm';
$users = PendudukModel::all();
// $umkms = UmkmModel::where('status', 'diterima')->paginate(10);
$umkmKategoris = UmkmKategoriModel::all();
// $categories = KategoriModel::all();
// return $users;
return view('Admin.Umkm.index', compact('users', 'umkms', 'page', 'selected', 'umkmKategoris', 'categories'));
}
public function searchList(Request $request)
{
$page = 'listUmkm';
$selected = 'Umkm';
$users = PendudukModel::all();
$umkmKategoris = UmkmKategoriModel::all();
$categories = KategoriModel::all();
$search = $request->input('search');
// $umkmQuery = UmkmModel::where('status', 'diterima');
$umkmQuery = UmkmModel::select('tb_umkm.*', 'tb_penduduk.nama as pemilik')
->join('tb_penduduk', 'tb_umkm.id_pemilik', '=', 'tb_penduduk.id_penduduk')
->where('status', 'diterima');
if ($search) {
$umkmQuery->where('tb_umkm.nama', 'like', '%' . $search . '%');
}
$umkms = $umkmQuery->orderBy('updated_at', 'desc')->paginate(10);
return view('Admin.Umkm.index', compact('users', 'umkms', 'page', 'selected', 'umkmKategoris', 'categories'));
}
public function searchAjuan(Request $request)
{
$page = 'ajuanUmkm';
$selected = 'Umkm';
$users = PendudukModel::all();
$umkmKategoris = UmkmKategoriModel::all();
$categories = KategoriModel::all();
$search = $request->input('search');
$umkmQuery = UmkmModel::where('status', 'diproses');
if ($search) {
$umkmQuery->where('nama', 'like', '%' . $search . '%');
}
$umkms = $umkmQuery->paginate(10);
return view('Admin.Umkm.ajuan-umkm', compact('users', 'umkms', 'page', 'selected', 'umkmKategoris', 'categories'));
}
} |
<?php
namespace App\Entity;
use App\Repository\OrganisationRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: OrganisationRepository::class)]
class Organisation implements \Stringable
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
/** Mapped from OrganisationListener */
protected Collection $clients;
public function __toString(): string
{
return $this->name;
}
public function __construct()
{
$this->clients = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): static
{
$this->name = $name;
return $this;
}
/**
* @return Collection<int, Client>
*/
public function getClients(): Collection
{
return $this->clients;
}
public function addClient(Client $client): static
{
if ($this->clients->contains($client) === false) {
$this->clients->add($client);
}
return $this;
}
} |
import { Message } from "discord.js";
import { stripIndents, oneLine } from "common-tags";
/// Detect direct links to trainer and show adjusted links.
export default async (message: Message) => {
const trainerLinks = message.content.match(PATTERN);
if (!trainerLinks) return false;
const links = trainerLinks.map((s) => "- <" + s.replace(/\/train\/[a-z]+$/, "") + ">").join("\n");
const Q = "❓";
const newMessage = await message.reply(stripIndents`
Please don't link directly to the trainer. Please change your link(s) to:
${links}
React with ${Q} within ${REACTION_SECS}s to get a DM with explanation.
`);
// React to the new message so users can just click it.
const reaction = await newMessage.react(Q);
newMessage
.createReactionCollector({
filter: (reaction, _user) => reaction.emoji.name === Q,
time: REACTION_SECS * 1000,
})
.on("collect", async (_reaction, user) => {
if (user.bot) return;
try {
const dm = await user.createDM();
await dm.send(INFO);
} catch (err: any) {
// Can error if the user have DM disabled.
console.warn(`failed to DM ${user.tag}: ${err.message || "unknown error"}`);
}
})
.once("end", async () => {
// Requires `MANAGE_MESSAGE` permission.
try {
await newMessage.edit(newMessage.content.replace(/React with .+$/, "").trimRight());
await reaction.remove();
} catch (e: any) {
console.log(`failed to remove reaction: ${e.message || "unknown error"}`);
}
});
return true;
};
const PATTERN = /https?:\/\/(?:www\.)?codewars.com\/kata\/[0-9a-f]{24}\/train\/[a-z]+/g;
const INFO = oneLine`
When you post a link to a kata, make sure the link doesn't end with \`/train/{language-id}\`.
Those are links to trainers and will start a training session when followed. This can be annoying
for other users because they can end up with an unwanted kata in their "unfinished" list.
`;
const REACTION_SECS = 15; |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
#pragma once
#include <InputDevice.h>
#include <InputMapper.h>
#include <InputReader.h>
#include <MapperHelpers.h>
namespace android {
class FuzzContainer {
std::shared_ptr<FuzzEventHub> mFuzzEventHub;
sp<FuzzInputReaderPolicy> mFuzzPolicy;
FuzzInputListener mFuzzListener;
std::unique_ptr<FuzzInputReaderContext> mFuzzContext;
std::unique_ptr<InputDevice> mFuzzDevice;
InputReaderConfiguration mPolicyConfig;
std::shared_ptr<ThreadSafeFuzzedDataProvider> mFdp;
public:
FuzzContainer(std::shared_ptr<ThreadSafeFuzzedDataProvider> fdp) : mFdp(fdp) {
// Setup parameters.
std::string deviceName = mFdp->ConsumeRandomLengthString(16);
std::string deviceLocation = mFdp->ConsumeRandomLengthString(12);
int32_t deviceID = mFdp->ConsumeIntegralInRange<int32_t>(0, 5);
int32_t deviceGeneration = mFdp->ConsumeIntegralInRange<int32_t>(/*from*/ 0, /*to*/ 5);
// Create mocked objects.
mFuzzEventHub = std::make_shared<FuzzEventHub>(mFdp);
mFuzzPolicy = sp<FuzzInputReaderPolicy>::make(mFdp);
mFuzzContext = std::make_unique<FuzzInputReaderContext>(mFuzzEventHub, mFuzzPolicy,
mFuzzListener, mFdp);
InputDeviceIdentifier identifier;
identifier.name = deviceName;
identifier.location = deviceLocation;
mFuzzDevice = std::make_unique<InputDevice>(mFuzzContext.get(), deviceID, deviceGeneration,
identifier);
mFuzzPolicy->getReaderConfiguration(&mPolicyConfig);
}
~FuzzContainer() {}
void configureDevice() {
nsecs_t arbitraryTime = mFdp->ConsumeIntegral<nsecs_t>();
std::list<NotifyArgs> out;
out += mFuzzDevice->configure(arbitraryTime, mPolicyConfig, /*changes=*/{});
out += mFuzzDevice->reset(arbitraryTime);
for (const NotifyArgs& args : out) {
mFuzzListener.notify(args);
}
}
void addProperty(std::string key, std::string value) {
mFuzzEventHub->addProperty(key, value);
configureDevice();
}
InputReaderConfiguration& getPolicyConfig() { return mPolicyConfig; }
template <class T, typename... Args>
T& getMapper(Args... args) {
int32_t eventhubId = mFdp->ConsumeIntegral<int32_t>();
// ensure a device entry exists for this eventHubId
mFuzzDevice->addEmptyEventHubDevice(eventhubId);
configureDevice();
return mFuzzDevice->template constructAndAddMapper<T>(eventhubId, args...);
}
};
} // namespace android |
#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <stdbool.h>
#include "./include/tempos.h"
// Estrutura para guardar as pinagens
struct Pinagem
{
int VERDE_SEMAFORO_1;
int AMARELO_SEMAFORO_1;
int VERDE_SEMAFORO_2;
int AMARELO_SEMAFORO_2;
int BOTAO_PED_1;
int BOTAO_PED_2;
int SENSOR_PRIN_1;
int SENSOR_PRIN_2;
int SENSOR_AUX_1;
int SENSOR_AUX_2;
int BUZZER;
};
struct Pinagem pinagem;
enum EstadosSemaforo
{
VERDE_PRINCIPAL,
AMARELO_PRINCIPAL,
VERMELHO_PRINCIPAL,
AMARELO_AUXILIAR,
MODO_NOTURNO,
MODO_EMERGENCIA,
};
// Estado inicial do semáforo
enum EstadosSemaforo estadoAtual = VERDE_PRINCIPAL;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int pausarThreadPrincipal = 0;
// Definição de variáveis de tempo
time_t tempo_farol_verde_prin;
time_t tempo_farol_verde_aux;
// Variáveis de controle
int controlaAmareloPrincipal = 0;
int controlaAmareloAuxiliar = 0;
int carroParadoAuxiliar = 0;
int carroDirAuxiliar1 = 0;
int carroDirAuxiliar2 = 0;
int carroDirPrincipal1 = 0;
int carroDirPrincipal2 = 0;
int contagemCarrosPrincipal = 0;
int contagemCarrosAuxiliar = 0;
double velocidadeTotalPrincipal = 0;
double velocidadeTotalAuxiliar = 0;
// Retorno para o server
int avancouVermelho = 0;
int acimaVelocidade = 0;
// Protótipos das funções
void lerPinagemDoArquivo(const char *nomeArquivo);
void definirEstadoSemaforoPrin(int pino1, int pino2);
void definirEstadoSemaforoAux(int pino1, int pino2);
void aguardaPedestre(int botao, time_t tempoPassado, time_t tempoBotaoPress, int tempoMinFarol, void (*definirSemaforo)(enum EstadosSemaforo novoEstado), enum EstadosSemaforo estadoPedestre);
void botao1pressionado();
void botao2pressionado();
void abrirAuxiliar(time_t tempoCarroParou);
unsigned long medirDuracaoBotaoPressionado(int pinoBotao);
void *monitorarSensoresAuxiliares(void *arg);
void *monitorarSensoresPrincipais(void *arg);
void *contagemCarros(void *arg);
void atualizarSemaforo();
void setEstado(enum EstadosSemaforo novoEstado);
void temporizador();
void configurarGPIO();
void controlaSensoresAuxiliares(int pino, int sensor);
void controlaSensoresPrincipais(int pino, int sensor);
double calcularVelocidade(unsigned long duracaoSensor);
void ativarBuzzer(int pinoBuzzer);
void verificarVelocidadeExcessiva(double velocidadeMedida, int via, int sensor);
void enviarArquivoParaServidor(const char *nomeArquivo);
void enviarDadosParaServidor(int clientSocket, const char *dados);
int connectToServer();
void *tentaConectar(void *arg);
void avancouSinal(int sensor);
double calcularVelocidadeMedia(double velocidadeTotal, int contagemCarros);
ssize_t receberDadosDoServidor(int clientSocket, char *buffer, size_t bufferSize);
void *escutaServidor(void *arg);
int main(int argc, char *argv[])
{
// Leia as informações de pinagem do primeiro arquivo
const char *arquivoConfig = argv[1];
lerPinagemDoArquivo(arquivoConfig);
// Iniciando wiringPi
if (wiringPiSetup() == -1)
{
printf("Erro ao inicializar a WiringPi.\n");
return 1; // Encerra o programa com um código de erro
}
// Configuração GPIO
configurarGPIO();
// Thread para botões auxiliares
pthread_t threadSensorAuxiliar;
pthread_t threadSensorPrincipal;
pthread_t contaCarro;
pthread_create(&threadSensorAuxiliar, NULL, monitorarSensoresAuxiliares, NULL);
pthread_create(&threadSensorPrincipal, NULL, monitorarSensoresPrincipais, NULL);
pthread_create(&contaCarro, NULL, contagemCarros, NULL);
// Thread principal do temporizador
temporizador();
// Terminando as threads
pthread_join(threadSensorAuxiliar, NULL);
pthread_join(threadSensorPrincipal, NULL);
pthread_join(contaCarro, NULL);
return 0;
}
// Função para ler as informações de pinagem de um arquivo e atribuí-las à estrutura
void lerPinagemDoArquivo(const char *nomeArquivo)
{
FILE *arquivo = fopen(nomeArquivo, "r");
if (!arquivo)
{
printf("Erro ao abrir o arquivo de configuração.\n");
exit(1);
}
fscanf(arquivo, "%d", &pinagem.VERDE_SEMAFORO_1);
fscanf(arquivo, "%d", &pinagem.AMARELO_SEMAFORO_1);
fscanf(arquivo, "%d", &pinagem.VERDE_SEMAFORO_2);
fscanf(arquivo, "%d", &pinagem.AMARELO_SEMAFORO_2);
fscanf(arquivo, "%d", &pinagem.BOTAO_PED_1);
fscanf(arquivo, "%d", &pinagem.BOTAO_PED_2);
fscanf(arquivo, "%d", &pinagem.SENSOR_PRIN_1);
fscanf(arquivo, "%d", &pinagem.SENSOR_PRIN_2);
fscanf(arquivo, "%d", &pinagem.SENSOR_AUX_1);
fscanf(arquivo, "%d", &pinagem.SENSOR_AUX_2);
fscanf(arquivo, "%d", &pinagem.BUZZER);
fclose(arquivo);
}
// Função para definir o estado do semáforo principal
void definirEstadoSemaforoPrin(int pino1, int pino2)
{
digitalWrite(pinagem.VERDE_SEMAFORO_1, pino1);
digitalWrite(pinagem.AMARELO_SEMAFORO_1, pino2);
}
// Função para definir o estado do semáforo auxiliar
void definirEstadoSemaforoAux(int pino1, int pino2)
{
digitalWrite(pinagem.VERDE_SEMAFORO_2, pino1);
digitalWrite(pinagem.AMARELO_SEMAFORO_2, pino2);
}
// Função de mudança de estado após apertar botão
void aguardaPedestre(int botao, time_t tempoPassado, time_t tempoBotaoPress, int tempoMinFarol, void (*definirSemaforo)(enum EstadosSemaforo novoEstado), enum EstadosSemaforo estadoPedestre)
{
double tempoDecorrido = difftime(tempoBotaoPress, tempoPassado);
if ((tempoDecorrido * 1000) >= (tempoMinFarol * 1000))
{
printf("Botao %d entrou depois do tempo minimo\n", botao);
setEstado(estadoPedestre);
return;
}
else
{
delay((tempoMinFarol - tempoDecorrido) * 1000);
printf("Botao %d entrou antes do tempo minimo\n", botao);
setEstado(estadoPedestre);
return;
}
}
// Interrupção do botão 1
void botao1pressionado()
{
time_t tempoBotaoPress = time(NULL);
controlaAmareloPrincipal = 1;
aguardaPedestre(1, tempo_farol_verde_prin, tempoBotaoPress, TEMPO_VERDE_MIN_PRINCIPAL, setEstado, VERMELHO_PRINCIPAL);
}
// Interrupção do botão 2
void botao2pressionado()
{
time_t tempoBotaoPress = time(NULL);
controlaAmareloAuxiliar = 1;
aguardaPedestre(2, tempo_farol_verde_aux, tempoBotaoPress, TEMPO_VERDE_MIN_AUXILIAR, setEstado, VERDE_PRINCIPAL);
}
// Função para ativar buzzer
void ativarBuzzer(int pinoBuzzer)
{
digitalWrite(pinoBuzzer, HIGH); // Ativa o buzzer
delay(1000);
digitalWrite(pinoBuzzer, LOW); // Desativa o buzzer
}
// Função que abre semaforo auxiliar assim que um carro para
void abrirAuxiliar(time_t tempoCarroParou)
{
// marcador do tempo do farol verde principal == tempo do farol vermelho auxiliar
double tempoDecorrido = difftime(tempoCarroParou, tempo_farol_verde_prin);
if ((tempoDecorrido * 1000) >= (TEMPO_VERMELHO_MIN_AUXILIAR * 1000))
{
setEstado(VERMELHO_PRINCIPAL);
return;
}
else
{
setEstado(VERMELHO_PRINCIPAL);
return;
}
}
// Monitoramento de tempo de botão com filtro
unsigned long medirDuracaoBotaoPressionado(int pinoBotao)
{
unsigned long tempoPressionado = 0;
int estadoAnterior = LOW;
while (digitalRead(pinoBotao) == HIGH)
{
if (estadoAnterior == LOW)
{
tempoPressionado = millis();
}
estadoAnterior = HIGH;
}
unsigned long duracao = millis() - tempoPressionado;
// Aplicar um filtro para evitar valores de tempo anômalos
if (duracao < 10 || duracao > 3000)
{
duracao = 0; // Descarta leituras fora do intervalo desejado
}
return duracao;
}
// Função de sensor de velocidade
double calcularVelocidade(unsigned long duracaoSensor)
{
// A distância média de um carro é de 2 metros
double distanciaCarro = 2;
// Converta o tempo do sensor para segundos (s)
double duracaoSegundos = (double)duracaoSensor / 1000.0; // de ms para s
// velocidade = distância / tempo
double velocidadeCarroAtual = distanciaCarro / duracaoSegundos;
velocidadeCarroAtual = velocidadeCarroAtual * 3.6; // de m/s para km/h
return velocidadeCarroAtual;
}
// Verifica velocidade
void verificarVelocidadeExcessiva(double velocidadeMedida, int via, int sensor)
{
double velocidadeMaxima;
char nomeVia[10];
// Defina a velocidade máxima com base na via (1 == principal ou 2 == auxiliar)
if (via == 1)
{
velocidadeMaxima = LIMITE_VELOCIDADE_PRINCIPAL; // Defina a velocidade máxima da via principal
strcpy(nomeVia, "Principal");
}
else
{
velocidadeMaxima = LIMITE_VELOCIDADE_AUXILIAR; // Defina a velocidade máxima da via auxiliar
strcpy(nomeVia, "Auxiliar");
}
// Verifique se a velocidade medida é maior que a velocidade máxima
if (velocidadeMedida > velocidadeMaxima)
{
printf("1 - Carro passou acima da velocidade permitida na via:%s\nno sensor:%d\n%.2f km/h\n", nomeVia, sensor, velocidadeMedida);
acimaVelocidade++;
ativarBuzzer(pinagem.BUZZER); // Ative o buzzer como sinal de alerta
}
else
{
printf("2 - Carro passou na velocidade permitida na via:%s\nno sensor:%d\n%.2f km/h\n", nomeVia, sensor, velocidadeMedida);
}
}
// Avançou sinal vermelho
void avancouSinal(int sensor)
{
printf("Passou no vermelho no cruzamento %d\n", sensor);
avancouVermelho++;
ativarBuzzer(pinagem.BUZZER);
}
void controlaSensoresAuxiliares(int pino, int sensor)
{
unsigned long duracaoSensorAux = medirDuracaoBotaoPressionado(pino);
double velocidade = calcularVelocidade(duracaoSensorAux);
verificarVelocidadeExcessiva(velocidade, 2, sensor);
if (duracaoSensorAux >= 1000)
{
controlaAmareloPrincipal = 1;
time_t tempoEstado = time(NULL);
abrirAuxiliar(tempoEstado);
}
else if (estadoAtual == VERDE_PRINCIPAL)
{
avancouSinal(sensor);
}
if (sensor == 1)
{
velocidadeTotalAuxiliar += velocidade;
contagemCarrosAuxiliar++;
carroDirAuxiliar1++;
}
else
{
velocidadeTotalAuxiliar += velocidade;
contagemCarrosAuxiliar++;
carroDirAuxiliar2++;
}
}
void controlaSensoresPrincipais(int pino, int sensor)
{
unsigned long duracaoSensorPrin = medirDuracaoBotaoPressionado(pino);
double velocidade = calcularVelocidade(duracaoSensorPrin);
verificarVelocidadeExcessiva(velocidade, 1, sensor);
if (duracaoSensorPrin >= 1000)
{
printf("parou no principal %d\n", sensor);
}
else if (estadoAtual == VERMELHO_PRINCIPAL)
{
avancouSinal(sensor);
}
if (sensor == 1)
{
velocidadeTotalPrincipal += velocidade;
contagemCarrosPrincipal++;
carroDirPrincipal1++;
}
else
{
velocidadeTotalPrincipal += velocidade;
contagemCarrosPrincipal++;
carroDirPrincipal2++;
}
}
// Thread para monitoramento das vias auxiliares e contagem de carros
void *monitorarSensoresAuxiliares(void *arg)
{
while (1)
{
if (digitalRead(pinagem.SENSOR_AUX_1) == HIGH)
{
controlaSensoresAuxiliares(pinagem.SENSOR_AUX_1, 1);
}
else if (digitalRead(pinagem.SENSOR_AUX_2) == HIGH)
{
controlaSensoresAuxiliares(pinagem.SENSOR_AUX_2, 2);
}
delay(25);
}
return NULL;
}
// Thread para monitoramento das vias auxiliares e contagem de carros
void *monitorarSensoresPrincipais(void *arg)
{
while (1)
{
if (digitalRead(pinagem.SENSOR_PRIN_1) == HIGH)
{
controlaSensoresPrincipais(pinagem.SENSOR_PRIN_1, 1);
}
else if (digitalRead(pinagem.SENSOR_PRIN_2) == HIGH)
{
controlaSensoresPrincipais(pinagem.SENSOR_PRIN_2, 2);
}
delay(25);
}
return NULL;
}
ssize_t receberDadosDoServidor(int clientSocket, char *buffer, size_t bufferSize)
{
ssize_t bytesReceived = recv(clientSocket, buffer, bufferSize - 1, 0);
if (bytesReceived < 0)
{
perror("Erro ao receber dados do servidor.");
}
else if (bytesReceived == 0)
{
printf("Servidor desconectado.\n");
}
else
{
buffer[bytesReceived] = '\0'; // Certifique-se de terminar a string corretamente
}
return bytesReceived;
}
void *escutaServidor(void *arg)
{
int clientSocket = *(int *)arg;
char mensagemServidor[1024];
while (1)
{
ssize_t tamanhoMensagem = receberDadosDoServidor(clientSocket, mensagemServidor, sizeof(mensagemServidor));
if (tamanhoMensagem > 0)
{
if (strcmp(mensagemServidor, "MODO_NOTURNO") == 0)
{
setEstado(MODO_NOTURNO);
} else if (strcmp(mensagemServidor, "MODO_EMERGENCIA") == 0){
setEstado(MODO_EMERGENCIA);
} else if (strcmp(mensagemServidor, "NORMAL") == 0){
setEstado(VERDE_PRINCIPAL);
}
}
else if (tamanhoMensagem == 0)
{
printf("Servidor desconectado.\n");
close(clientSocket);
break;
}
else
{
perror("Erro ao receber dados do servidor.");
}
}
return NULL;
}
void enviarDadosParaServidor(int clientSocket, const char *dados)
{
ssize_t bytesSent = send(clientSocket, dados, strlen(dados), 0);
if (bytesSent < 0)
{
perror("Erro ao enviar dados para o servidor.");
close(clientSocket); // Fecha o socket se houver erro
}
}
int connectToServer()
{
struct sockaddr_in serverAddr;
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket == -1)
{
perror("Erro ao criar o socket do cliente.");
return -1;
}
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(SERVER_PORT);
serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP);
if (connect(clientSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1)
{
perror("Erro ao conectar ao servidor.");
close(clientSocket);
return -1;
}
return clientSocket;
}
void *tentaConectar(void *arg)
{
int *clientSocketPtr = (int *)arg;
while (1)
{
*clientSocketPtr = connectToServer();
if (*clientSocketPtr != -1)
{
pthread_t threadEscuta;
if(pthread_create(&threadEscuta, NULL, escutaServidor, clientSocketPtr) != 0)
{
perror("Erro ao criar thread de escuta.");
}
break;
}
sleep(5);
}
return NULL;
}
double calcularVelocidadeMedia(double velocidadeTotal, int contagemCarros)
{
if (contagemCarros == 0)
return 0; // Para evitar divisão por zero
return velocidadeTotal / contagemCarros;
}
// Função unicamente pra voltar resultado dos carros
void *contagemCarros(void *arg)
{
pthread_t threadConexao;
int clientSocket = -1; // Inicializa como inválido
char dados[1024];
double velocidadeMediaPrincipal;
double velocidadeMediaAuxiliar;
// Inicie a thread para tentar se conectar em segundo plano
pthread_create(&threadConexao, NULL, tentaConectar, &clientSocket);
while (1)
{
// Certifique-se de ter uma conexão antes de tentar enviar dados
if (clientSocket == -1)
{
sleep(1); // Espere um pouco antes de verificar novamente
continue;
}
velocidadeMediaPrincipal = calcularVelocidadeMedia(velocidadeTotalPrincipal, contagemCarrosPrincipal);
velocidadeMediaAuxiliar = calcularVelocidadeMedia(velocidadeTotalAuxiliar, contagemCarrosAuxiliar);
printf("Qtd de carros que avançaram o vermelho %d\n", avancouVermelho);
printf("Qtd de carros que passaram acima da velocidade %d\n", acimaVelocidade);
printf("Velocidade média da via principal: %.2f km/h\n", velocidadeMediaPrincipal);
printf("Velocidade média da via auxiliar: %.2f km/h\n", velocidadeMediaAuxiliar);
snprintf(dados, sizeof(dados),
"-----------------------Informações--------------------------\n"
"Qtd. de carros avançaram o vermelho: %d\n"
"Qtd. de carros acima da velocidade: %d\n"
"Velocidade média da via principal: %.2f km/h\n"
"Velocidade média da via auxiliar: %.2f km/h\n"
"Qtd. na via Principal: %d\n"
"Qtd. na via Auxiliar: %d\n"
"------------------------------------------------------------\n",
avancouVermelho, acimaVelocidade,
velocidadeMediaPrincipal, velocidadeMediaAuxiliar,
carroDirPrincipal1 + carroDirPrincipal2,
carroDirAuxiliar1 + carroDirAuxiliar2);
enviarDadosParaServidor(clientSocket, dados);
delay(2000);
}
if (clientSocket != -1)
{
close(clientSocket);
}
return NULL;
}
// Função para atualizar o estado do semáforo
void atualizarSemaforo()
{
switch (estadoAtual)
{
case VERDE_PRINCIPAL:
tempo_farol_verde_prin = time(NULL);
definirEstadoSemaforoPrin(0, 1); // Principal verde
definirEstadoSemaforoAux(1, 1); // Auxiliar Vermelho
delay(TEMPO_VERDE_MAX_PRINCIPAL * 1000);
if (controlaAmareloPrincipal == 0)
{
estadoAtual = AMARELO_PRINCIPAL;
}
else
{
controlaAmareloPrincipal = 0;
estadoAtual = VERMELHO_PRINCIPAL;
}
break;
case AMARELO_PRINCIPAL:
ativarBuzzer(pinagem.BUZZER);
definirEstadoSemaforoPrin(1, 0); // Principal amarelo
delay(TEMPO_AMARELO * 1000);
estadoAtual = VERMELHO_PRINCIPAL;
break;
case VERMELHO_PRINCIPAL:
tempo_farol_verde_aux = time(NULL);
definirEstadoSemaforoPrin(1, 1); // Principal Vermelho
definirEstadoSemaforoAux(0, 1); // Auxiliar Verde
delay(TEMPO_VERMELHO_MAX_PRINCIPAL * 1000);
if (controlaAmareloAuxiliar == 0)
{
estadoAtual = AMARELO_AUXILIAR;
}
else
{
controlaAmareloAuxiliar = 0;
estadoAtual = VERDE_PRINCIPAL;
}
break;
case AMARELO_AUXILIAR:
ativarBuzzer(pinagem.BUZZER);
definirEstadoSemaforoAux(1, 0); // Auxiliar amarelo
delay(TEMPO_AMARELO * 1000);
estadoAtual = VERDE_PRINCIPAL;
break;
case MODO_NOTURNO:
while (1) {
definirEstadoSemaforoAux(1,0);
definirEstadoSemaforoPrin(1,0);
delay(2000);
definirEstadoSemaforoAux(0,0);
definirEstadoSemaforoPrin(0,0);
delay(2000);
}
break;
case MODO_EMERGENCIA:
while (1) {
definirEstadoSemaforoAux(1,1);
definirEstadoSemaforoPrin(0,1);
delay(2000);
}
break;
}
}
// Função para definir manualmente o estado do semáforo
void setEstado(enum EstadosSemaforo novoEstado)
{
pthread_mutex_lock(&mutex);
if (novoEstado == MODO_NOTURNO || novoEstado == MODO_EMERGENCIA) {
pausarThreadPrincipal = 1;
} else {
pausarThreadPrincipal = 0;
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
estadoAtual = novoEstado;
atualizarSemaforo();
}
// Loop de temporização principal
void temporizador()
{
while (1)
{
pthread_mutex_lock(&mutex);
while (pausarThreadPrincipal) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
atualizarSemaforo();
}
}
// Configurando pinos e inicialização
void configurarGPIO()
{
pinMode(pinagem.VERDE_SEMAFORO_1, OUTPUT);
pinMode(pinagem.AMARELO_SEMAFORO_1, OUTPUT);
pinMode(pinagem.VERDE_SEMAFORO_2, OUTPUT);
pinMode(pinagem.AMARELO_SEMAFORO_2, OUTPUT);
pinMode(pinagem.BOTAO_PED_1, INPUT);
pinMode(pinagem.BOTAO_PED_2, INPUT);
pinMode(pinagem.SENSOR_PRIN_1, INPUT);
pinMode(pinagem.SENSOR_PRIN_2, INPUT);
pinMode(pinagem.SENSOR_AUX_1, INPUT);
pinMode(pinagem.SENSOR_AUX_2, INPUT);
pinMode(pinagem.BUZZER, OUTPUT);
pullUpDnControl(pinagem.BOTAO_PED_1, PUD_UP);
pullUpDnControl(pinagem.BOTAO_PED_2, PUD_UP);
pullUpDnControl(pinagem.SENSOR_PRIN_1, PUD_DOWN);
pullUpDnControl(pinagem.SENSOR_PRIN_2, PUD_DOWN);
pullUpDnControl(pinagem.SENSOR_AUX_1, PUD_DOWN);
pullUpDnControl(pinagem.SENSOR_AUX_2, PUD_DOWN);
wiringPiISR(pinagem.BOTAO_PED_1, INT_EDGE_RISING, &botao1pressionado);
wiringPiISR(pinagem.BOTAO_PED_2, INT_EDGE_RISING, &botao2pressionado);
} |
using Microsoft.AspNetCore.Mvc;
using Mvc.Application.Models;
using Mvc.Application.Repository;
namespace Mvc.Application.Controllers;
[Route("[controller]")]
public class ProductsController : Controller
{
private readonly IGenericRepository<Product> _repository;
public ProductsController(IGenericRepository<Product> repository)
{
_repository = repository;
}
// GET: Products
public async Task<IActionResult> Index()
{
return View(await _repository.GetAll());
}
// GET: Products/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return RedirectToAction("Index");
}
var product = await _repository.GetById((int)id);
if (product == null)
{
return NotFound();
}
return View(product);
}
// GET: Products/Create
public IActionResult Create()
{
return View();
}
// POST: Products/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Price,Stock,Color")] Product product)
{
if (ModelState.IsValid)
{
await _repository.Create(product);
return RedirectToAction(nameof(Index));
}
return View(product);
}
// GET: Products/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return RedirectToAction("Index");
}
var product = await _repository.GetById((int)id);
if (product == null)
{
return NotFound();
}
return View(product);
}
// POST: Products/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(int id, [Bind("Id,Name,Price,Stock,Color")] Product product)
{
if (id != product.Id) return NotFound();
if (ModelState.IsValid)
{
_repository.Update(product);
return RedirectToAction(nameof(Index));
}
return View(product);
}
// GET: Products/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id is null) return NotFound();
var product = await _repository.GetById((int)id);
if (product is null) return NotFound();
return View(product);
}
// POST: Products/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var product = await _repository.GetById(id);
if (product is null) return NotFound();
_repository.Delete(product);
return RedirectToAction(nameof(Index));
}
private bool ProductExists(int id)
{
var product = _repository.GetById(id).Result;
if (product == null) return false;
else return true;
}
} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:glizit_app/features/screens/dashboard/view/video.dart';
import '../bloc/dashboard_bloc.dart';
import '../bloc/dashboard_event.dart';
import '../bloc/dashboard_state.dart';
class Dashboard extends StatefulWidget {
const Dashboard({super.key});
@override
State<Dashboard> createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> {
final PostsBloc postsBloc = PostsBloc();
@override
void initState() {
postsBloc.add(PostsInitialFetchEvent());
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.grey,
title: const Text('Dashboard'),
centerTitle: true,
),
body: BlocConsumer<PostsBloc, PostsState>(
bloc: postsBloc,
listenWhen: (previous, current) => current is PostsActionState,
buildWhen: (previous, current) => current is! PostsActionState,
listener: (context, state) {},
builder: (context, state) {
switch (state.runtimeType) {
case PostsFetchingLoadingState:
return const Center(
child: CircularProgressIndicator(),
);
case PostFetchingSuccessfulState:
final successState = state as PostFetchingSuccessfulState;
return ListView.builder(
itemCount: successState.posts.length,
itemBuilder: (context, index) {
return InkWell(
onTap: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => VideoPlayerScreen(
post: successState.posts[index],
))
);
},
child: Container(
color: Colors.grey.shade200,
padding: const EdgeInsets.all(16),
margin: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
successState.posts[index].title!,
style: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
Image.network(
successState.posts[index].thumbnailUrl!,
errorBuilder: (BuildContext context,
Object exception, StackTrace? stackTrace) {
return const SizedBox();
}),
Text(
successState.posts[index].description!,
style: const TextStyle(
fontSize: 14, fontWeight: FontWeight.w500),
)
],
),
),
);
},
);
default:
return const SizedBox();
}
},
));
}
} |
<!--<br> <br> <br>
<div class="container">
<div class="row">
<h1> table des events </h1>
<table>
<thead>
<th>Groups Name</th>
<th>Groups Items</th>
</thead>
<tbody>
<tr *ngFor="let group of events">
<td>{{group.name}}</td>
<td>
<ul>
<li *ngFor="let item of group.user">{{item}}</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
-->
<br><br><br><br><br><br>
<div class="container">
<div style="margin-top: 10px ;" >
<mat-form-field>
<input matInput #filter (keyup)="applyFilter(filter.value)" placeholder="Search">
</mat-form-field>
<!-- <mat-form-field appearance="standard">
<mat-label>Filter</mat-label>
<input matInput (keyup)="applyFilter($event)" placeholder="Ex. Mia" #input>
</mat-form-field> -->
<div class="mat-elevation-z8">
<table mat-table [dataSource]="events" matSort>
<!-- id Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th>
<td mat-cell *matCellDef="let row"> {{row.id}}</td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> name </th>
<td mat-cell *matCellDef="let row"> {{row.nom}} </td>
</ng-container>
<!-- asset Column -->
<ng-container matColumnDef="asset">
<th mat-header-cell *matHeaderCellDef mat-sort-header> type event </th>
<td mat-cell *matCellDef="let row"> {{row.type_event}} </td>
</ng-container>
<!-- picture Column -->
<ng-container matColumnDef="picture">
<th mat-header-cell *matHeaderCellDef mat-sort-header> id user </th>
<td mat-cell *matCellDef="let row"> {{row.id_user}} </td>
</ng-container>
<!-- Note Column -->
<ng-container matColumnDef="note">
<th mat-header-cell *matHeaderCellDef mat-sort-header> id ville </th>
<td mat-cell *matCellDef="let row"> {{row.id_ville}} </td>
</ng-container>
<!-- date Column -->
<ng-container matColumnDef="date">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Date event </th>
<td mat-cell *matCellDef="let row"> {{row.date_event | date}} </td>
</ng-container>
<!-- descripition Column -->
<ng-container matColumnDef="descripition">
<th mat-header-cell *matHeaderCellDef mat-sort-header> date creat </th>
<td mat-cell *matCellDef="let row"> {{row.createdat}} </td>
</ng-container>
<!-- Action Column -->
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Action </th>
<td mat-cell *matCellDef="let row">
<!-- <button mat-icon-button (click)="editEvent(row)" color="primary">
<mat-icon>edit</mat-icon>
</button> -->
<button type="button" (click)="editEvent(row)"class="btn btn-outline-primary">edit</button>
<!-- <button (click)="deleteEvent(row.id)" type="button" class="btn btn-danger">delete</button> -->
<button (click)="deleteEvent(row.id)" type="button" class="btn btn-outline-danger">Delete</button>
<!-- <button (click)="deleteEvent(row.id)" mat-icon-button color="warn">
<mat-icon>delete</mat-icon>
</button> -->
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
<!-- Row shown when there is no matching data. -->
<!-- <tr class="mat-row" *matNoDataRow>
<td class="mat-cell" colspan="4">No data matching the filter "{{input.value}}"</td>
</tr> -->
</table>
<mat-paginator [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page of users"></mat-paginator>
</div>
<mat-toolbar>
<button mat-icon-button class="example-icon" aria-label="Example icon-button with menu icon">
<!-- <mat-icon><mat-icon>supervised_user_circle</mat-icon></mat-icon> -->
</button>
<!-- <img src="assets/img/logo1.jpg" alt=""> -->
<span class="example-spacer"></span>
<button mat-raised-button color="warn" (click)="openDialog()">Add Event</button>
</mat-toolbar>
</div>
</div>
<!-- <router-outlet></router-outlet> --> |
/* eslint-disable react/prop-types */
import { useContext } from "react";
import TodoItem from "../TodoItem/TodoItem";
import { TodoContextObj } from "../../context/TodoContext";
const TodoList = () => {
const { todos, setTodos } = useContext(TodoContextObj);
const changeFinished = (todo, isCompleted) => {
const updatedTodos = todos.map((t) => {
if (t.id === todo?.id) {
t.isCompleted = isCompleted;
}
return t;
});
setTodos(updatedTodos);
};
return (
<div className="todo-container">
{todos.length === 0 ? (
<h1>No Todo</h1>
) : (
todos.map((todo, idx) => {
return (
<TodoItem
todo={todo}
changeFinished={(isCompleted) =>
changeFinished(todo, isCompleted)
}
key={idx}
/>
);
})
)}
</div>
);
};
export default TodoList; |
"use client";
import Link from "next/link";
import { Button, Card } from "react-bootstrap";
import Image from "next/image";
import { auth, db } from "@/firebase/firebase";
import { collection, doc, getDoc, setDoc } from "firebase/firestore";
import { useRouter } from "next/navigation";
import React, { useEffect, useState } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import Aos from "aos";
import "aos/dist/aos.css";
function ProductPastriesCard({ item, show, setShow }) {
Aos.init();
const [user] = useAuthState(auth);
const router = useRouter();
const addToCart = async (product) => {
if (!user) {
router.push("/login");
} else {
const uid = user.uid;
const userRef = doc(db, "cart", uid);
try {
const userSnap = await getDoc(userRef);
const cart = [];
if (userSnap.exists()) {
const userData = userSnap.data();
cart.push(...userData.cart);
}
const productIndex = cart.findIndex((item) => item.id === product.id);
if (productIndex === -1) {
// Add the product to the cart with a quantity of 1
cart.push({ ...product, quantity: 1 });
} else {
// Increase the quantity of the product in the cart by 1
cart[productIndex].quantity += 1;
}
await setDoc(userRef, { cart });
setShow(!show);
} catch (error) {
console.error(error);
}
}
};
return (
<>
{item.map((items) => (
<div data-aos="zoom-in">
<Card
key={items.id}
className="d-flex product-card flex-column align-items-center border border-dark"
style={{
width: "14rem",
height: "350px",
padding: "10px",
backgroundColor: "#191919",
}}
>
<Image
src={items.imageUrl}
alt="imageproduct"
height={200}
width={200}
style={{ height: "180px", borderRadius: "10px" }}
/>
<Card.Body
className="d-flex flex-column justify-content-center"
style={{ justifyContent: "space-between" }}
>
<div>
<h6>{items.name}</h6>
<p>PHP {items.price}</p>
</div>
<div style={{ display: "flex" }}>
<Link href={`/product/${items.id}`}>
<Button variant="secondary" className="card-button">
Explore
</Button>
</Link>
<Button
style={{ backgroundColor: "#d3ad7f" }}
variant="dark"
className="card-button"
onClick={() => addToCart(items)}
>
Buy Now
</Button>
</div>
</Card.Body>
</Card>
</div>
))}
</>
);
}
export default ProductPastriesCard; |
const execute = require('./SIGN.runtime');
module.exports = {
name: 'SIGN',
category: 'Math',
title: 'Return sign of a number',
description: 'Returns -1 if the parameter is a negative number, 1 if it is positive, and 0 if it is zero. Returns `null` if it\'s not a number.',
parameters: [{
type: 'number',
title: 'Number',
description: 'Number to check',
}],
analyze: (params, offset, parameterErrors) => ({
schema: parameterErrors.length ? {
type: 'number',
examples: [1, 0, -1],
} : {
type: 'number',
// Include enum if the parameter is correctly number type
enum: [1, 0, -1],
examples: [1, 0, -1],
},
}),
execute,
examples: [
{ expression: 'SIGN(4)', result: 1 },
{ expression: 'SIGN(-4)', result: -1 },
{ expression: 'SIGN(0)', result: 0 },
],
}; |
import { useState } from "react";
import { Question } from "../types/AppTypes";
import { useQuizContext } from "../hooks/useQuizContext";
import "./QuizQuestion.scss";
const mapper = ["A", "B", "C", "D"];
const QuizQuestion = ({
correctAnswer,
options,
type,
flagUrl,
countryCapital,
}: Question) => {
const isFlagQuestion = type === "flag";
const [isCorrect, setisCorrect] = useState<boolean | null>(null);
const [currentSelected, setcurrentSelected] = useState<string>("");
const [finalAnswer, setfinalAnswer] = useState<string>("");
const { goToNextQuestion, incrementScore, decreaseScore, endQuiz } = useQuizContext();
const handleClick = (option: string) => {
if (finalAnswer) {
// If the final answer has already been submitted, ignore clicks
return;
}
if (currentSelected === option) {
// If the same option is clicked again, unselect it
setcurrentSelected("");
} else {
// Otherwise, select the new option
setcurrentSelected(option);
}
};
const resetState = () => {
setisCorrect(null);
setcurrentSelected("");
setfinalAnswer("");
};
const handleFinalAnswer = () => {
if (currentSelected === "") {
// Ensure that a selection has been made before finalizing the answer
return;
}
setfinalAnswer(currentSelected);
setisCorrect(currentSelected === correctAnswer);
if (currentSelected === correctAnswer) {
incrementScore();
}
if (finalAnswer) {
if (!isCorrect) {
endQuiz();
} else {
// Move to the next question
resetState();
decreaseScore();
goToNextQuestion();
}
}
};
return (
<div className="question-container">
{isFlagQuestion && (
<div className="flag-container">
<img src={flagUrl} alt="flag of the country" />
</div>
)}
<p>
{isFlagQuestion
? "Which country does this flag belong to? "
: `${countryCapital} is the capital of`}
</p>
<ul role="list" className="options">
{options?.map((option, index) => (
<li
key={option}
className={`option ${
currentSelected === option ? "selected" : ""
} ${
finalAnswer && option === correctAnswer
? "correct-answer"
: ""
} ${
isCorrect === false && finalAnswer === option
? "final-answer wrong-answer"
: ""
} ${
isCorrect === true && finalAnswer === option
? "final-answer"
: ""
}`}
>
<button
disabled={finalAnswer ? true : false}
onClick={() => {
handleClick(option);
}}
>
<span className="option-letter">
{mapper[index]}
</span>
<span className="option-name">{option}</span>
</button>
</li>
))}
</ul>
{currentSelected && (
<button className="submit-btn" onClick={handleFinalAnswer}>
{finalAnswer ? "Next" : "Submit"}
</button>
)}
</div>
);
};
export default QuizQuestion; |
// SpecializedListInterface.
//
// Interface for a class that implements a list of bytes
// There can be duplicate elements on the list
// The list has two special properties called the current forward position
// and the current backward position -- the positions of the next element
// to be accessed by getNextItem and by getPriorItem during an iteration
// through the list. Only resetForward and getNextItem affect the current
// forward position. Only resetBackward and getPriorItem affect the current
// backward position. Note that forward and backward iterations may be in
// progress at the same time
//----------------------------------------------------------------------------
package a1;
public interface SpecializedListInterface {
public void resetForward();
//Effect: Initializes current forward position for this list
//Postcondition: Current forward position is first element on this list
public byte getNextItem ();
// Effect: Returns the value of the byte at the current forward
// position on this list and advances the value of the
// current forward position
//
// Preconditions:
// - Current forward position is defined
// - There exists a list element at current forward position
// - No list transformers (i.e. insertion methods) have been called
// since the most recent call of getNextItem; and if list transformer calls
// have been made since the most recent call of getNextItem,
// or getNextItem has never been called on the list,
// then a call must be made to resetForward before calling getNextItem.
//
// Postconditions:
// - Return value = (value of byte at current forward position)
// - If current forward position is the last element then
// current forward position is set to the beginning of this
// list, otherwise it is updated to the next position
public void resetBackward();
// Effect: Initializes current backward position for this list
// Postcondition: Current backward position is last element on this list
public byte getPriorItem ();
// Effect: Returns the value of the byte at the current backward
// position on this list and advances the value of the
// current backward position (towards front of list)
//
// Preconditions:
// - Current backward position is defined
// - There exists a list element at current backward position
// - No list transformers (i.e. insertion methods) have been called
// since the most recent call of getPriorItem; and if list transformer calls
// have been made since the most recent call of getPriorItem,
// or getPriorItem has never been called on the list,
// then a call must be made to resetBackward before calling getPriorItem.
//
// Postconditions:
// - Return value = (value of byte at current backward
// position)
// - If current backward position is the first element then
// current backward position is set to the end of this list;
// otherwise, it is updated to the prior position
public int lengthIs();
//Effect: Determines the number of elements on this list
//Postcondition: Return value = number of elements on this list
public void insertFront (byte item);
//Effect: Adds the value of item to the front of this list
//PostCondition: Value of item is at the front of this list
public void insertEnd (byte item);
//Effect: Adds the value of item to the end of this list
//PostCondition: Value of item is at the end of this list
} |
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
export interface DocumentsIndex {
'docs.count': string;
'docs.deleted': string;
health: 'green' | 'yellow';
index: string;
pri: string;
'pri.store.size': string;
rep: string;
status: 'open' | 'close';
'store.size': string;
uuid: string;
}
export interface IDocType {
[key: string]: any;
}
export interface Document {
_index: string;
_id: string;
_score: number;
_source: IDocType;
}
export interface SearchResults {
took: number;
timed_out: boolean;
_shards: {
total: number;
successful: number;
skipped: number;
failed: number;
};
hits: {
total: {
value: number;
relation: string;
};
max_score: number;
hits: Document[];
};
}
export enum SelectIndexError {
unselected = 'An index is required to compare search results. Select an index.',
}
export enum QueryStringError {
empty = 'A query is required. Enter a query.',
invalid = 'Query syntax is invalid. Enter a valid query.',
}
export interface ErrorResponse {
body: string;
statusCode: number;
}
export interface QueryError {
selectIndex: SelectIndexError | string;
queryString: QueryStringError | string;
errorResponse: ErrorResponse;
}
export const initialQueryErrorState: QueryError = {
selectIndex: '',
queryString: '',
errorResponse: {
body: '',
statusCode: 200,
},
}; |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Magento
* @package Magento_Eav
* @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Magento\Eav\Model\Resource\Form\Element;
/**
* Eav Form Element Resource Collection
*
* @category Magento
* @package Magento_Eav
* @author Magento Core Team <core@magentocommerce.com>
*/
class Collection extends \Magento\Core\Model\Resource\Db\Collection\AbstractCollection
{
/**
* Initialize collection model
*
* @return void
*/
protected function _construct()
{
$this->_init('Magento\Eav\Model\Form\Element', 'Magento\Eav\Model\Resource\Form\Element');
}
/**
* Add Form Type filter to collection
*
* @param \Magento\Eav\Model\Form\Type|int $type
* @return $this
*/
public function addTypeFilter($type)
{
if ($type instanceof \Magento\Eav\Model\Form\Type) {
$type = $type->getId();
}
return $this->addFieldToFilter('type_id', $type);
}
/**
* Add Form Fieldset filter to collection
*
* @param \Magento\Eav\Model\Form\Fieldset|int $fieldset
* @return $this
*/
public function addFieldsetFilter($fieldset)
{
if ($fieldset instanceof \Magento\Eav\Model\Form\Fieldset) {
$fieldset = $fieldset->getId();
}
return $this->addFieldToFilter('fieldset_id', $fieldset);
}
/**
* Add Attribute filter to collection
*
* @param \Magento\Eav\Model\Entity\Attribute\AbstractAttribute|int $attribute
*
* @return $this
*/
public function addAttributeFilter($attribute)
{
if ($attribute instanceof \Magento\Eav\Model\Entity\Attribute\AbstractAttribute) {
$attribute = $attribute->getId();
}
return $this->addFieldToFilter('attribute_id', $attribute);
}
/**
* Set order by element sort order
*
* @return $this
*/
public function setSortOrder()
{
$this->setOrder('sort_order', self::SORT_ORDER_ASC);
return $this;
}
/**
* Join attribute data
*
* @return $this
*/
protected function _joinAttributeData()
{
$this->getSelect()->join(
array('eav_attribute' => $this->getTable('eav_attribute')),
'main_table.attribute_id = eav_attribute.attribute_id',
array('attribute_code', 'entity_type_id')
);
return $this;
}
/**
* Load data (join attribute data)
*
* @param bool $printQuery
* @param bool $logQuery
* @return $this
*/
public function load($printQuery = false, $logQuery = false)
{
if (!$this->isLoaded()) {
$this->_joinAttributeData();
}
return parent::load($printQuery, $logQuery);
}
} |
package jsonschema_test
import (
"fmt"
"reflect"
"testing"
"time"
"github.com/DimmyJing/valise/jsonschema"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
//nolint:forcetypeassert
func TestValueToAny(t *testing.T) { //nolint:funlen
t.Parallel()
//nolint:tagliatelle
type testVal struct {
TestBool bool
TestInt int
TestUint uint
TestFloat float64
TestArray [8]int
TestInterface any
TestNilInterface any
TestPtrInterface any
TestMap map[string]int
TestPtr *string
TestNilPtr *string
TestSlice []int
TestString string
TestBytes []byte
TestTime time.Time
TestIgnore string `json:"-"`
TestName string `json:"testCustomName"`
TestOptional string `json:",omitempty"`
TestOptional2 string `json:",omitempty"`
testNotExported string
}
input := testVal{
TestBool: true,
TestInt: 1,
TestUint: 2,
TestFloat: 3.0,
TestArray: [8]int{1, 2, 3, 4, 5, 6, 7, 8},
TestInterface: "test",
TestNilInterface: nil,
TestPtrInterface: &[]string{"hello"}[0],
TestMap: map[string]int{
"test": 1,
},
TestPtr: &[]string{"hello"}[0],
TestNilPtr: nil,
TestSlice: []int{1, 2, 3, 4, 5, 6, 7, 8},
TestString: "test",
TestBytes: []byte("test"),
TestTime: time.Unix(1, 1).UTC(),
TestIgnore: "test",
TestName: "test",
TestOptional: "test",
TestOptional2: "",
testNotExported: "test",
}
res, err := jsonschema.ValueToAny(reflect.ValueOf(input))
resMap := res.(map[string]any)
assert.NoError(t, err)
assert.Equal(t, true, resMap["testBool"])
assert.Equal(t, int64(1), resMap["testInt"])
assert.Equal(t, uint64(2), resMap["testUint"])
assert.InEpsilon(t, 3.0, resMap["testFloat"], 0.0001)
assert.Equal(t,
[]any{int64(1), int64(2), int64(3), int64(4), int64(5), int64(6), int64(7), int64(8)},
resMap["testArray"],
)
assert.Equal(t, "test", resMap["testInterface"])
assert.Nil(t, resMap["testNilInterface"])
assert.Equal(t, "hello", resMap["testPtrInterface"])
assert.Equal(t, map[string]any{"test": int64(1)}, resMap["testMap"])
assert.Equal(t, "hello", resMap["testPtr"])
assert.Nil(t, resMap["testNilPtr"])
assert.Equal(t,
[]any{int64(1), int64(2), int64(3), int64(4), int64(5), int64(6), int64(7), int64(8)},
resMap["testSlice"],
)
assert.Equal(t, "test", resMap["testString"])
assert.Equal(t, []byte("test"), resMap["testBytes"])
assert.Equal(t, time.Unix(1, 1).UTC(), resMap["testTime"])
assert.Equal(t, "test", resMap["testCustomName"])
assert.Equal(t, "test", resMap["testOptional"])
assert.Nil(t, resMap["testNotExported"])
assert.Nil(t, resMap["testOptional2"])
}
func TestValueToAnyError(t *testing.T) {
t.Parallel()
_, err := jsonschema.ValueToAny(reflect.ValueOf(complex64(1)))
assert.Error(t, err)
_, err = jsonschema.ValueToAny(reflect.ValueOf([]complex64{0}))
assert.Error(t, err)
_, err = jsonschema.ValueToAny(reflect.ValueOf(map[string]complex64{"hello": 1}))
assert.Error(t, err)
_, err = jsonschema.ValueToAny(reflect.ValueOf(map[complex64]string{}))
assert.Error(t, err)
_, err = jsonschema.ValueToAny(reflect.ValueOf(&[]complex64{0}[0]))
assert.Error(t, err)
_, err = jsonschema.ValueToAny(reflect.ValueOf(struct{ A complex64 }{A: 1}))
assert.Error(t, err)
_, err = jsonschema.ValueToAny(reflect.ValueOf([1]complex64{1}))
assert.Error(t, err)
var stringer fmt.Stringer = time.Time{}
_, err = jsonschema.ValueToAny(reflect.ValueOf(&stringer))
assert.Error(t, err)
}
func TestAnyToValue(t *testing.T) { //nolint:funlen
t.Parallel()
//nolint:tagliatelle
type testVal struct {
TestBool bool
TestBool2 bool
TestBool3 bool
TestInt int
TestInt2 int
TestInt3 int
TestUint uint
TestUint2 uint
TestUint3 uint
TestFloat float64
TestFloat2 float64
TestFloat3 float64
TestArray [8]int
TestArray2 [8]int
TestInterface any
TestNilInterface any
TestPtrInterface any
TestMap map[string]int
TestNilMap map[string]int
TestMissingMap map[string]int `json:",omitempty"`
TestPtr *string
TestNilPtr *string
TestSlice []int
TestSlice2 []int
TestNilSlice []int
TestMissingSlice []int `json:",omitempty"`
TestString string
TestString2 string
TestBytes []byte
TestTime time.Time
TestIgnore string `json:"-"`
TestName string `json:"testCustomName"`
TestOptional string `json:",omitempty"`
TestOptional2 string `json:",omitempty"`
TestEnum TestEnum
testNotExported string
}
input := map[string]any{
"testBool": true,
"testBool2": "true",
"testBool3": []string{"true"},
"testInt": int64(1),
"testInt2": "1",
"testInt3": []string{"1"},
"testUint": uint64(2),
"testUint2": "2",
"testUint3": []string{"2"},
"testFloat": 3.0,
"testFloat2": "3.0",
"testFloat3": []string{"3.0"},
"testArray": []any{int64(1), int64(2), int64(3), int64(4), int64(5), int64(6), int64(7), int64(8)},
"testArray2": []string{"1", "2", "3", "4", "5", "6", "7", "8"},
"testInterface": "test",
"testNilInterface": nil,
"testPtrInterface": "hello",
"testMap": map[string]any{"test": int64(1)},
"testNilMap": nil,
"testPtr": "hello",
"testNilPtr": nil,
"testNilSlice": nil,
"testSlice": []any{int64(1), int64(2), int64(3), int64(4), int64(5), int64(6), int64(7), int64(8)},
"testSlice2": []string{"1", "2", "3", "4", "5", "6", "7", "8"},
"testString": "test",
"testString2": []string{"test"},
"testBytes": []byte("test"),
"testTime": time.Unix(1, 1).UTC(),
"testCustomName": "test",
"testOptional": "test",
"testEnum": "A",
}
var val testVal
err := jsonschema.AnyToValue(input, reflect.ValueOf(&val).Elem())
require.NoError(t, err)
assert.True(t, val.TestBool)
assert.Equal(t, 1, val.TestInt)
assert.Equal(t, uint(2), val.TestUint)
assert.InEpsilon(t, 3.0, val.TestFloat, 0.0001)
assert.Equal(t, [8]int{1, 2, 3, 4, 5, 6, 7, 8}, val.TestArray)
assert.Equal(t, "test", val.TestInterface)
assert.Nil(t, val.TestNilInterface)
assert.Equal(t, "hello", val.TestPtrInterface)
assert.Equal(t, map[string]int{"test": 1}, val.TestMap)
assert.Equal(t, map[string]int{}, val.TestNilMap)
assert.Equal(t, map[string]int(nil), val.TestMissingMap)
assert.Equal(t, &[]string{"hello"}[0], val.TestPtr)
assert.Equal(t, (*string)(nil), val.TestNilPtr)
assert.Equal(t, []int{}, val.TestNilSlice)
assert.Equal(t, []int{1, 2, 3, 4, 5, 6, 7, 8}, val.TestSlice)
assert.Equal(t, []int{}, val.TestNilSlice)
assert.Equal(t, []int(nil), val.TestMissingSlice)
assert.Equal(t, "test", val.TestString)
assert.Equal(t, []byte("test"), val.TestBytes)
assert.Equal(t, time.Unix(1, 1).UTC(), val.TestTime)
assert.Equal(t, "test", val.TestName)
assert.Equal(t, "test", val.TestOptional)
assert.Equal(t, "", val.TestOptional2)
assert.Equal(t, TestEnumA, val.TestEnum)
assert.Equal(t, "", val.testNotExported)
assert.True(t, val.TestBool2)
assert.Equal(t, 1, val.TestInt2)
assert.Equal(t, uint(2), val.TestUint2)
assert.InEpsilon(t, 3.0, val.TestFloat2, 0.0001)
assert.Equal(t, [8]int{1, 2, 3, 4, 5, 6, 7, 8}, val.TestArray2)
assert.Equal(t, []int{1, 2, 3, 4, 5, 6, 7, 8}, val.TestSlice2)
assert.True(t, val.TestBool3)
assert.Equal(t, 1, val.TestInt3)
assert.Equal(t, uint(2), val.TestUint3)
assert.InEpsilon(t, 3.0, val.TestFloat3, 0.0001)
assert.Equal(t, "test", val.TestString2)
}
func TestAnyToValueError(t *testing.T) { //nolint:funlen
t.Parallel()
err := jsonschema.AnyToValue(1, reflect.ValueOf(1))
require.Error(t, err)
var valBool bool
err = jsonschema.AnyToValue(1, reflect.ValueOf(&valBool).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue("hello", reflect.ValueOf(&valBool).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue([]string{"hello", "world"}, reflect.ValueOf(&valBool).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue([]string{"hello"}, reflect.ValueOf(&valBool).Elem())
require.Error(t, err)
var valInt int
err = jsonschema.AnyToValue(true, reflect.ValueOf(&valInt).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue("a", reflect.ValueOf(&valInt).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue([]string{"a", "b"}, reflect.ValueOf(&valInt).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue([]string{"a"}, reflect.ValueOf(&valInt).Elem())
require.Error(t, err)
var valUint uint
err = jsonschema.AnyToValue(true, reflect.ValueOf(&valUint).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue("a", reflect.ValueOf(&valUint).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue([]string{"a", "b"}, reflect.ValueOf(&valUint).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue([]string{"a"}, reflect.ValueOf(&valUint).Elem())
require.Error(t, err)
var valFloat float64
err = jsonschema.AnyToValue(true, reflect.ValueOf(&valFloat).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue("a", reflect.ValueOf(&valFloat).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue([]string{"a", "b"}, reflect.ValueOf(&valFloat).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue([]string{"a"}, reflect.ValueOf(&valFloat).Elem())
require.Error(t, err)
var valArray [1]int
err = jsonschema.AnyToValue(true, reflect.ValueOf(&valArray).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue([]string{"a"}, reflect.ValueOf(&valArray).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue([]string{"a", "b"}, reflect.ValueOf(&valArray).Elem())
require.Error(t, err)
var valArray2 [1]int
err = jsonschema.AnyToValue([]any{}, reflect.ValueOf(&valArray2).Elem())
require.Error(t, err)
var valArray3 [1]int
err = jsonschema.AnyToValue([]any{true}, reflect.ValueOf(&valArray3).Elem())
require.Error(t, err)
var stringer fmt.Stringer = time.Time{}
err = jsonschema.AnyToValue(true, reflect.ValueOf(&stringer).Elem())
require.Error(t, err)
var valMap map[int]int
err = jsonschema.AnyToValue(true, reflect.ValueOf(&valMap).Elem())
require.Error(t, err)
var valMap2 map[string]int
err = jsonschema.AnyToValue(map[string]any{"a": true}, reflect.ValueOf(&valMap2).Elem())
require.Error(t, err)
var valMap3 map[string]int
err = jsonschema.AnyToValue(true, reflect.ValueOf(&valMap3).Elem())
require.Error(t, err)
var valPtr *complex64
err = jsonschema.AnyToValue(true, reflect.ValueOf(&valPtr).Elem())
require.Error(t, err)
var valBytes []byte
err = jsonschema.AnyToValue(true, reflect.ValueOf(&valBytes).Elem())
require.Error(t, err)
var valSlice []int
err = jsonschema.AnyToValue([]any{true}, reflect.ValueOf(&valSlice).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue([]string{"a"}, reflect.ValueOf(&valSlice).Elem())
require.Error(t, err)
var valSlice2 []int
err = jsonschema.AnyToValue(true, reflect.ValueOf(&valSlice2).Elem())
require.Error(t, err)
var valEnum TestEnum
err = jsonschema.AnyToValue("C", reflect.ValueOf(&valEnum).Elem())
require.Error(t, err)
var valString string
err = jsonschema.AnyToValue(true, reflect.ValueOf(&valString).Elem())
require.Error(t, err)
err = jsonschema.AnyToValue([]string{"hello", "world"}, reflect.ValueOf(&valString).Elem())
require.Error(t, err)
var valTime time.Time
err = jsonschema.AnyToValue(true, reflect.ValueOf(&valTime).Elem())
require.Error(t, err)
var valStruct struct{ Test string }
err = jsonschema.AnyToValue(map[string]any{"test": true}, reflect.ValueOf(&valStruct).Elem())
require.Error(t, err)
var valStruct2 struct{ Test string }
err = jsonschema.AnyToValue(map[string]any{}, reflect.ValueOf(&valStruct2).Elem())
require.Error(t, err)
var valStruct3 struct{}
err = jsonschema.AnyToValue(map[string]any{"test": true}, reflect.ValueOf(&valStruct3).Elem())
require.Error(t, err)
var valStruct4 struct{}
err = jsonschema.AnyToValue(true, reflect.ValueOf(&valStruct4).Elem())
require.Error(t, err)
} |
<script lang="ts">
import DataTable, { Body, Cell, Head, Row } from "@smui/data-table";
import { onMount } from "svelte";
import type { Currency } from "../models";
import { apiUrl } from "./api";
let currencies: Currency[] = [];
onMount(async () => {
await getCurrencies();
});
const getCurrencies = async () => {
const respose = await fetch(`${apiUrl}/currencies`);
currencies = await respose.json();
};
</script>
<DataTable class="currency-list"
><Head>
<Row>
<Cell>ID</Cell>
<Cell>Ticker</Cell>
<Cell>Name</Cell>
</Row>
</Head>
<Body>
{#each currencies as currency (currency.id)}
<Row>
<Cell>{currency.id}</Cell>
<Cell>{currency.ticker}</Cell>
<Cell>{currency.name}</Cell>
</Row>
{/each}
</Body>
</DataTable>
<style lang="scss">
.currency-list {
display: flex;
flex-flow: column nowrap;
}
</style> |
/******************************************************************************
* Copyright (C) 2022 Xilinx, Inc. All rights reserved.
* Copyright (C) 2022-2023 Advanced Micro Devices, Inc. All rights reserved.
* SPDX-License-Identifier: MIT
******************************************************************************/
/*****************************************************************************/
/**
*
* @file xdfeofdm.h
* @addtogroup dfeofdm Overview
* @{
*
* @cond nocomments
* The RFSoC DFE Orthogonal Frequency Division Multiplexing IP performs
* translation between frequency domain to the time domain and vice versa using
* the hardened FFT IP. Each instance of the IP supports up to eight
* antennas in 1, 2, 4 and 8 combinations and up to 4 ANTENNA INTERLEAVE in
* combinations of 1, 2 and 4. Each instance can also support up to 8 component
* carriers (CC) to be aggregated on a particular antenna. The block performs
* buffering, FFT/IFFT conversion, scaling, and cyclic prefix insertion/removal.
* The block outputs in the case of DL (or accepts in the case of UL) IFFTed
* data as per the time domain sampling requirements using TDMA axi-stream data
* interfaces. An AXI memory mapped interface is provided for configuration and
* control.
*
* The features that the OFDM IP and the driver support are:
*
* - Supports a maximum sampling rate of 491.52 MS/s
* - Supports up to 8 CC both LTE and NR.
* - Supports SCS spacing of 15 KHz and 30 KHz.
* - Currently supports 1K, 2K and 4K FFT sizes.
* - Supports up to 8 DL or UL paths (or antennas)
* - Supports both TDD and FDD modes
* - Using 16 or 18 bit data interface.
* - Enable the user to program CCs via a process interface
* - Supports TDD power down via a processor interface and TUSER input
* - Indication of overflow of FD buffer provided via a status register
* - TUSER/TLAST information accompanying the data is delay match through the IP
* - Does not support SCS above 30 KHz for the time being
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- --- -------- -----------------------------------------------
* 1.0 dc 11/21/22 Initial version
* 1.1 dc 04/05/23 Update documentation
* dc 05/22/23 State and status upgrades
* dc 06/28/23 Add phase compensation calculation
*
* </pre>
* @endcond
******************************************************************************/
#ifndef XDFEOFDM_H_
#define XDFEOFDM_H_
#ifdef __cplusplus
extern "C" {
#endif
/**************************** Includes ***************************************/
#ifdef __BAREMETAL__
#include "xil_types.h"
#ifndef SDT
#include "xparameters.h"
#endif
#include "xstatus.h"
#else
#include <linux/types.h>
#include <assert.h>
#endif
#include "stdbool.h"
#include <metal/sys.h>
/**************************** Macros Definitions *****************************/
#ifndef __BAREMETAL__
#define XDFEOFDM_MAX_NUM_INSTANCES \
(10U) /**< Maximum number of driver instances running at the same time. */
#define XDFEOFDM_INSTANCE_EXISTS(X) (X < XDFEOFDM_MAX_NUM_INSTANCES)
/**
* @cond nocomments
*/
#define Xil_AssertNonvoid(Expression) \
assert(Expression) /**< Assertion for non void return parameter function. */
#define Xil_AssertVoid(Expression) \
assert(Expression) /**< Assertion for void return parameter function. */
#define Xil_AssertVoidAlways() assert(0) /**< Assertion always. */
/**
* @endcond
*/
#ifndef XST_SUCCESS
#define XST_SUCCESS (0U) /**< Success flag */
#endif
#ifndef XST_FAILURE
#define XST_FAILURE (1U) /**< Failure flag */
#endif
#else
#ifndef SDT
#define XDFEOFDM_MAX_NUM_INSTANCES XPAR_XDFEOFDM_NUM_INSTANCES
#define XDFEOFDM_INSTANCE_EXISTS(X) (X < XDFEOFDM_MAX_NUM_INSTANCES)
#else
#define XDFEOFDM_MAX_NUM_INSTANCES \
(10U) /**< Maximum number of driver instances running at the same time. */
#define XDFEOFDM_INSTANCE_EXISTS(X) (XDfeOfdm_ConfigTable[X].Name != NULL)
#endif
#endif
#define XDFEOFDM_NODE_NAME_MAX_LENGTH (50U) /**< Node name maximum length */
#define XDFEOFDM_CC_NUM (16) /**< Maximum CC sequence number */
#define XDFEOFDM_FT_NUM (16) /**< Maximum FT sequence number */
#define XDFEOFDM_CC_SEQ_LENGTH_MAX (16U) /**< Maximum sequence length */
#define XDFEOFDM_FT_SEQ_LENGTH_MAX \
(16U) /**< Maximum Fourier transform sequence length */
#define XDFEOFDM_PHASE_COMPENSATION_MAX \
(112U) /**< Maximum phase compensation weight */
/**************************** Type Definitions *******************************/
/*********** start - common code to all Logiccores ************/
#ifndef __BAREMETAL__
typedef __u32 u32;
typedef __u16 u16;
typedef __u8 u8;
typedef __s32 s32;
typedef __s16 s16;
typedef __u64 u64;
typedef __s64 s64;
typedef __s8 s8;
#else
#define XDFEOFDM_CUSTOM_DEV(_dev_name, _baseaddr, _idx) \
{ \
.name = _dev_name, .bus = NULL, .num_regions = 1, \
.regions = { { \
.virt = (void *)_baseaddr, \
.physmap = &XDfeOfdm_metal_phys[_idx], \
.size = 0x10000, \
.page_shift = (u32)(-1), \
.page_mask = (u32)(-1), \
.mem_flags = 0x0, \
.ops = { NULL }, \
} }, \
.node = { NULL }, .irq_num = 0, .irq_info = NULL, \
}
#endif
typedef enum XDfeOfdm_StateId {
XDFEOFDM_STATE_NOT_READY = 0, /**< Not ready state*/
XDFEOFDM_STATE_READY, /**< Ready state*/
XDFEOFDM_STATE_RESET, /**< Reset state*/
XDFEOFDM_STATE_CONFIGURED, /**< Configured state*/
XDFEOFDM_STATE_INITIALISED, /**< Initialised state*/
XDFEOFDM_STATE_OPERATIONAL /**< Operational state*/
} XDfeOfdm_StateId;
/**
* Logicore version.
*/
typedef struct {
u32 Major; /**< Major version number. */
u32 Minor; /**< Minor version number. */
u32 Revision; /**< Revision number. */
u32 Patch; /**< Patch number. */
} XDfeOfdm_Version;
/**
* Trigger configuration.
*/
typedef struct {
u32 TriggerEnable; /**< [0,1], Enable Trigger:
- 0 = DISABLED: Trigger Pulse and State outputs are disabled.
- 1 = ENABLED: Trigger Pulse and State outputs are enabled and follow
the settings described below. */
u32 Mode; /**< [0-3], Specify Trigger Mode. In TUSER_Single_Shot mode as
soon as the TUSER_Edge_level condition is met the State output will be
driven to the value specified in STATE_OUTPUT. The Pulse output will
pulse high at the same time. No further change will occur until the
trigger register is re-written. In TUSER Continuous mode each time
a TUSER_Edge_level condition is met the State output will be driven to
the value specified in STATE_OUTPUT This will happen continuously until
the trigger register is re-written. The pulse output is disabled in
Continuous mode:
- 0 = IMMEDIATE: Applies the value of STATE_OUTPUT immediatetly
the register is written.
- 1 = TUSER_SINGLE_SHOT: Applies the value of STATE_OUTPUT once when
the TUSER_EDGE_LEVEL condition is satisfied.
- 2 = TUSER_CONTINUOUS: Applies the value of STATE_OUTPUT continually
when TUSER_EDGE_LEVEL condition is satisfied.
- 3 = RESERVED: Reserved - will default to 0 behaviour. */
u32 TuserEdgeLevel; /**< [0-3], Specify either Edge or Level of the TUSER
input as the source condition of the trigger. Difference between Level
and Edge is Level will generate a trigger immediately the TUSER level
is detected. Edge will ensure a TUSER transition has come first:
- 0 = LOW: Trigger occurs immediately after a low-level is seen on TUSER
provided tvalid is high.
- 1 = HIGH: Trigger occurs immediately after a high-level is seen on
TUSER provided tvalid is high.
- 2 = FALLING: Trigger occurs immediately after a high to low transition
on TUSER provided tvalid is high.
- 3 = RISING: Trigger occurs immediately after a low to high transition
on TUSER provided tvalid is high. */
u32 StateOutput; /**< [0,1], Specify the State output value:
- 0 = DISABLED: Place the State output into the Disabled state.
- 1 = ENABLED: Place the State output into the Enabled state. */
u32 TUSERBit; /**< [0-255], Specify which DIN TUSER bit to use as the source
for the trigger when MODE = 1 or 2. */
} XDfeOfdm_Trigger;
/**
* All IP triggers.
*/
typedef struct {
XDfeOfdm_Trigger Activate; /**< Switch between "Initialized",
ultra-low power state, and "Operational". One-shot trigger,
disabled following a single event. */
XDfeOfdm_Trigger LowPower; /**< Switch between "Low-power"
and "Operational" state. */
XDfeOfdm_Trigger CCUpdate; /**< Transition to next CC
configuration. Will initiate flush based on CC configuration. */
} XDfeOfdm_TriggerCfg;
/**
* Defines a CCID sequence.
*/
typedef struct {
u32 Length; /**< [1-16] Sequence length. */
s32 CCID[XDFEOFDM_CC_SEQ_LENGTH_MAX]; /**< Array of CCID's arranged in
the order the CC samples are output on CC Interfaces */
} XDfeOfdm_CCSequence;
/**
* Defines a FT sequence.
*/
typedef struct {
u32 Length; /**< [1-16] Sequence length. */
s32 CCID[XDFEOFDM_FT_SEQ_LENGTH_MAX]; /**< Array of CCID's arranged in
the order of Fourier Transforms output on FT Interfaces */
} XDfeOfdm_FTSequence;
/*********** end - common code to all Logiccores ************/
/**
* Orthogonal Frequency Division Multiplexing model parameters structure. Data
* defined in Device tree or xparameters.h for BM.
*/
typedef struct {
u32 NumAntenna; /**< [1-8] Number of antenas */
u32 AntennaInterleave; /**< [1-8] Antenna interleave */
u32 PhaseCompensation; /**< [0,1] Phase compesation
0 - Phase compesation disabled
1 - Phase compesation enabled */
} XDfeOfdm_ModelParameters;
/**
* Configuration.
*/
typedef struct {
XDfeOfdm_Version Version; /**< Logicore version */
XDfeOfdm_ModelParameters ModelParams; /**< Logicore
parameterization */
} XDfeOfdm_Cfg;
/**
* Initialization, "one-time" configuration parameters.
*/
typedef struct {
u32 CCSequenceLength; /**< CC Sequence Length */
} XDfeOfdm_Init;
/**
* Configuration for a single CC.
*/
typedef struct {
/* FT CONFIG */
u32 Numerology; /**< [0-6] Numerology (Mu) value for this CC.
- 0 = 15 kHz
- 1 = 30 kHz
- 2 = 60 KHz
- 3 = 120 KHz
- 4 = 240 KHz
- 5 = 480 KHz
- 6 = 960 KHz
Numerology must be 0 for LTE. */
u32 FftSize; /**< [10,11,12] FFT size to be used for FFT of the CC.
Valid sizes are:
- 1024 = 0xA
- 2048 = 0xB
- 4096 = 0xC */
u32 NumSubcarriers; /**< [0-14] Number of non-null subcarriers
in this CC. */
u32 ScaleFactor; /**< [0-1023] Scaling factor for FFT output for this
CC, represented as a fixed-point value in 0.10 fixed-point
format. 0=>(multiple of 0), 1=>(multiple of 0.999) */
u32 CommsStandard; /**< [0-1]
- 1 = LTE
- 0 = 5G NR */
/* CC slot delay */
u32 OutputDelay; /** [0-2047] Delay required before outputting CC
in order to balance CC Filter group delay. */
u32 PhaseCompensation[XDFEOFDM_PHASE_COMPENSATION_MAX]; /** Phase weight is
a complex number with 0 to 15 bits providing the I and 16 to 31
bits the Q part of the weight. */
} XDfeOfdm_CarrierCfg;
/**
* Internal configuration for a single CC.
*/
typedef struct {
u32 Enable; /**< [0,1] (Private) Enable the CC. This is distinct from
removing from the CC from the sequence. When enable is not set,
the associated CCID will appear in sequence, but its valid will
not propagate. */
/* FT CONFIG */
u32 Numerology; /**< [0-6] Numerology (Mu) value for this CC.
- 0 = 15 kHz
- 1 = 30 kHz
- 2 = 60 KHz
- 3 = 120 KHz
- 4 = 240 KHz
- 5 = 480 KHz
- 6 = 960 KHz
Numerology must be 0 for LTE. */
u32 FftSize; /**< [10,11,12] FFT size to be used for FFT of the CC.
Valid sizes are:
- 1024 = 0xA
- 2048 = 0xB
- 4096 = 0xC */
u32 NumSubcarriers; /**< [0-14] Number of non-null subcarriers in this
CC. */
u32 ScaleFactor; /**< [0-1023] Scaling factor for FFT output for this
CC, represented as a fixed-point value in 0.10 fixed-point
format. 0=>(multiple of 0), 1=>(multiple of 0.999) */
u32 CommsStandard; /**< [0-1]
- 1 = LTE
- 0 = 5G NR */
/* CC slot delay */
u32 OutputDelay; /** [0-2047] Delay required before outputting CC
in order to balance CC Filter group delay. */
u32 PhaseCompensation[XDFEOFDM_PHASE_COMPENSATION_MAX]; /** Phase weight is
a complex number with 0 to 15 bits providing the I and 16 to 31
bits the Q part of the weight. */
} XDfeOfdm_InternalCarrierCfg;
/**
* Full CC configuration.
*/
typedef struct {
XDfeOfdm_CCSequence CCSequence; /**< CCID sequence */
XDfeOfdm_FTSequence FTSequence; /**< CCID sequence */
XDfeOfdm_InternalCarrierCfg
CarrierCfg[XDFEOFDM_CC_NUM]; /**< CC configurations */
} XDfeOfdm_CCCfg;
/**
* Orthogonal Division Multiplexing Status.
*/
typedef struct {
u32 SaturationCCID; /**< [0,15] CCID in which saturation event
occurred. */
u32 SaturationCount; /**< [0,2**14-1] Saturation events count across
real and imaginary components. */
u32 CCUpdate; /**< [0,1] There has been an overflow or underflow in
the filter for one or more of the antennas and CCIDs. */
u32 FTCCSequenceError; /**< [0,1] TRIGGER.CC_UPDATE has been
triggered. */
u32 Saturation; /**< [0,1] A difference between CC_CONFIGURATION.
SEQUENCE and DIN TID has been detected. */
u32 Overflow; /**< [0,1] UL OFDM receives tready low during packet
transaction */
} XDfeOfdm_Status;
/**
* Interrupt mask.
*/
typedef struct {
u32 CCUpdate; /**< [0,1] Mask CC update events */
u32 FTCCSequenceError; /**< [0,1] Mask sequence mismatch events */
u32 Saturation; /**< [0,1] Mask Saturation events */
u32 Overflow; /**< [0,1] Mask Overflow events */
} XDfeOfdm_InterruptMask;
/**
* OFDM Config Structure.
*/
typedef struct {
#ifndef SDT
u32 DeviceId; /**< The component instance Id */
#else
char *Name; /**< Unique name of the device */
#endif
metal_phys_addr_t BaseAddr; /**< Instance base address */
u32 NumAntenna; /**< Number of antenas */
u32 AntennaInterleave; /**< Antenna interleave */
u32 PhaseCompensation; /**< [0,1] Phase compesation
0 - Phase compesation disabled
1 - Phase compesation enabled */
} XDfeOfdm_Config;
/**
* OFDM Structure.
*/
typedef struct {
XDfeOfdm_Config Config; /**< Config Structure */
XDfeOfdm_StateId StateId; /**< StateId */
s32 NotUsedCCID; /**< Not used CCID */
u32 CCSequenceLength; /**< Exact sequence length */
char NodeName[XDFEOFDM_NODE_NAME_MAX_LENGTH]; /**< Node name */
struct metal_io_region *Io; /**< Libmetal IO structure */
struct metal_device *Device; /**< Libmetal device structure */
} XDfeOfdm;
/************************** Variable Definitions *****************************/
#ifdef __BAREMETAL__
extern XDfeOfdm_Config XDfeOfdm_ConfigTable[XDFEOFDM_MAX_NUM_INSTANCES];
#endif
/**************************** API declarations *******************************/
/* System initialization API */
XDfeOfdm *XDfeOfdm_InstanceInit(const char *DeviceNodeName);
void XDfeOfdm_InstanceClose(XDfeOfdm *InstancePtr);
/**
* @cond nocomments
*/
/* Register access API */
void XDfeOfdm_WriteReg(const XDfeOfdm *InstancePtr, u32 AddrOffset, u32 Data);
u32 XDfeOfdm_ReadReg(const XDfeOfdm *InstancePtr, u32 AddrOffset);
/**
* @endcond
*/
/* DFE OFDM component initialization API */
void XDfeOfdm_Reset(XDfeOfdm *InstancePtr);
void XDfeOfdm_Configure(XDfeOfdm *InstancePtr, XDfeOfdm_Cfg *Cfg);
void XDfeOfdm_Initialize(XDfeOfdm *InstancePtr, XDfeOfdm_Init *Init);
void XDfeOfdm_Activate(XDfeOfdm *InstancePtr, bool EnableLowPower);
void XDfeOfdm_Deactivate(XDfeOfdm *InstancePtr);
XDfeOfdm_StateId XDfeOfdm_GetStateID(XDfeOfdm *InstancePtr);
/* User APIs */
void XDfeOfdm_GetCurrentCCCfg(const XDfeOfdm *InstancePtr,
XDfeOfdm_CCCfg *CCCfg);
void XDfeOfdm_GetEmptyCCCfg(const XDfeOfdm *InstancePtr, XDfeOfdm_CCCfg *CCCfg);
void XDfeOfdm_GetCarrierCfg(const XDfeOfdm *InstancePtr, XDfeOfdm_CCCfg *CCCfg,
s32 CCID, u32 *CCSeqBitmap,
XDfeOfdm_CarrierCfg *CarrierCfg);
u32 XDfeOfdm_AddCCtoCCCfg(XDfeOfdm *InstancePtr, XDfeOfdm_CCCfg *CCCfg,
s32 CCID, u32 CCSeqBitmap,
const XDfeOfdm_CarrierCfg *CarrierCfg,
XDfeOfdm_FTSequence *FTSeq);
u32 XDfeOfdm_RemoveCCfromCCCfg(XDfeOfdm *InstancePtr, XDfeOfdm_CCCfg *CCCfg,
s32 CCID, XDfeOfdm_FTSequence *FTSeq);
u32 XDfeOfdm_UpdateCCinCCCfg(XDfeOfdm *InstancePtr, XDfeOfdm_CCCfg *CCCfg,
s32 CCID, const XDfeOfdm_CarrierCfg *CarrierCfg,
XDfeOfdm_FTSequence *FTSeq);
void XDfeOfdm_SetNextCCCfg(const XDfeOfdm *InstancePtr,
const XDfeOfdm_CCCfg *NextCCCfg);
u32 XDfeOfdm_EnableCCUpdateTrigger(const XDfeOfdm *InstancePtr);
u32 XDfeOfdm_SetNextCCCfgAndTrigger(const XDfeOfdm *InstancePtr,
XDfeOfdm_CCCfg *CCCfg);
u32 XDfeOfdm_AddCC(XDfeOfdm *InstancePtr, s32 CCID, u32 CCSeqBitmap,
const XDfeOfdm_CarrierCfg *CarrierCfg,
XDfeOfdm_FTSequence *FTSeq);
u32 XDfeOfdm_RemoveCC(XDfeOfdm *InstancePtr, s32 CCID,
XDfeOfdm_FTSequence *FTSeq);
u32 XDfeOfdm_UpdateCC(XDfeOfdm *InstancePtr, s32 CCID,
const XDfeOfdm_CarrierCfg *CarrierCfg,
XDfeOfdm_FTSequence *FTSeq);
void XDfeOfdm_GetTriggersCfg(const XDfeOfdm *InstancePtr,
XDfeOfdm_TriggerCfg *TriggerCfg);
void XDfeOfdm_SetTriggersCfg(const XDfeOfdm *InstancePtr,
XDfeOfdm_TriggerCfg *TriggerCfg);
void XDfeOfdm_SetTuserOutFrameLocation(const XDfeOfdm *InstancePtr,
u32 TuserOutFrameLocation);
u32 XDfeOfdm_GetTuserOutFrameLocation(const XDfeOfdm *InstancePtr);
void XDfeOfdm_GetEventStatus(const XDfeOfdm *InstancePtr,
XDfeOfdm_Status *Status);
void XDfeOfdm_ClearEventStatus(const XDfeOfdm *InstancePtr,
const XDfeOfdm_Status *Status);
void XDfeOfdm_SetInterruptMask(const XDfeOfdm *InstancePtr,
const XDfeOfdm_InterruptMask *Mask);
void XDfeOfdm_GetInterruptMask(const XDfeOfdm *InstancePtr,
XDfeOfdm_InterruptMask *Mask);
void XDfeOfdm_SetTUserDelay(const XDfeOfdm *InstancePtr, u32 Delay);
u32 XDfeOfdm_GetTUserDelay(const XDfeOfdm *InstancePtr);
u32 XDfeOfdm_GetDataLatency(const XDfeOfdm *InstancePtr);
void XDfeOfdm_GetVersions(const XDfeOfdm *InstancePtr,
XDfeOfdm_Version *SwVersion,
XDfeOfdm_Version *HwVersion);
#ifdef __cplusplus
}
#endif
#endif
/** @} */ |
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lesson 2.7</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<form>
<!-- label привязывается к инпуту через атрибут for="..." к айдишнику инпута -->
<label for="nameOfInput">Имя</label>
<input id="nameOfInput" name="FIO" type="text" placeholder="Введите ваше ФИО">
<!-- скрытый лейбл для роботов - можно, но не рекомендуется -->
<input aria-label="email" name="email" type="email">
<input id="password" name="password" type="password">
<!--не стоит использовать type="number", если только
для количественных штук-->
<input id="number" name="number" type="number">
<input id="tel" name="tel" type="tel">
<!--не используется-->
<input type="color">
<input type="date">
<input type="datetime-local">
<!--используется-->
<input type="file">
<div>
<input id="checkbox-1" type="checkbox" name="colors" value="RED">
<label for="checkbox-1">Красный</label>
</div>
<div>
<input id="checkbox-2" type="checkbox" name="colors" value="YELLOW">
<label for="checkbox-2">Желтый</label>
</div>
<div>
<input id="checkbox-3" type="checkbox" name="colors" value="WHITE">
<label for="checkbox-3">Белый</label>
</div>
<div>
<div class="form__radio"></div>
<input id="radio-1" type="radio" name="gender" value="male">
<label for="radio-1">Мужчина</label>
<input id="radio-2" type="radio" name="gender" value="female">
<label for="radio-2">Женщина</label>
</div>
<label for="language">Язык</label>
<select name="laguage" id="language">
<option value="RU">Русский</option>
<option value="EN">Английский</option>
<option value="FR">Французкий</option>
</select>
<label for="textarea">о себе</label>
<textarea id="textarea" name="textarea"></textarea>
<!--можно использовать инпут для кнопки, но не стоит-->
<input type="button" value="Отправить">
<input type="submit" value="Отправить">
<!--лучше использовать тег баттон, которая имеет
тип сабмит по умолчанию-->
<button>Отправить</button>
</form>
</body>
</html> |
#include <arcxx.hpp>
#include <iostream>
struct Goods : public arcxx::model<Goods> {
static constexpr auto table_name = "goods_table";
struct ID : public arcxx::attributes::integer<Goods, ID, std::size_t> {
using integer<Goods, ID, std::size_t>::integer;
static constexpr auto column_name = "id";
inline static const auto constraints = { primary_key, not_null };
} id;
struct Name : public arcxx::attributes::string<Goods, Name> {
using string<Goods, Name>::string;
static constexpr auto column_name = "name";
inline static const auto constraints = { not_null };
} name;
struct Price : public arcxx::attributes::integer<Goods, Price, uint32_t> {
using integer<Goods, Price, uint32_t>::integer;
static constexpr auto column_name = "price";
inline static const auto constraints = { not_null };
} price;
};
auto setup() -> arcxx::expected<arcxx::sqlite3::connector, arcxx::string>{
using namespace arcxx;
// Connect and create table
auto conn = sqlite3::connector::open("insert_data_example.sqlite3", sqlite3::options::create);
if (conn.has_error()) return make_unexpected(conn.error_message());
if(const auto result = conn.template create_table<Goods>(); result){
return conn;
}
else{
return make_unexpected(result.error());
}
}
int main(){
using namespace arcxx;
auto setup_result = setup();
if(!setup_result) {
std::cout << "Setup failed" << std::endl;
std::cout << "Error message:" << setup_result.error() << std::endl;
return -1;
}
auto conn = std::move(setup_result.value());
// Inserting data
Goods apple = {
.id = 1,
.name = "apple",
.price = 100
};
const auto insert_stmt = Goods::insert(apple);
std::cout << "SQL Statement:\n" << insert_stmt.to_sql<decltype(conn)>() << std::endl;
if(const auto result = insert_stmt.exec(conn); !result){
std::cout << "Error message:" << result.error() << std::endl;
return -1;
}
std::cout << "Done!!" << std::endl;
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.