text
stringlengths 184
4.48M
|
|---|
@component('admin.layouts.main')
@slot('title')
Admin - Manage Customers - {{ config('app.name') }}
@endslot
<?php
$back_url = (request()->has('back_url'))?request('back_url'):'';
?>
<div class="row">
<div class="col-md-12">
<div class="titlehead">
<h1 class="pull-left">Orders View </h1>
<?php
if(!empty($back_url)){
?>
<a href="{{ url($back_url) }}" class="btn btn-sm btn-success pull-right">Back</a>
<?php
}
?>
</div>
</div>
</div>
<div class="row">
<?php
if(!empty($res) && $res->count() > 0){
//pr($res); ?>
<div class="table-responsive">
<div class="col-md-12">
<table class="table table-striped" >
<tr>
<td><b>Order Id :</b> {{$res->order_id}}
<br><b>Added on: </b> <?php $added_on = CustomHelper::DateFormat($res->created_at, 'd F y'); ?>{{$added_on}}
<br><b>Order Status: </b> <?php echo $order_model->orderStatus($res->order_status); ?>
<br><b>
Payment Status: </b> <?php echo ($res->payment_status==1)?'Recieved':'Pending'; ?>
</td>
<td><b>Billing Address</b> <br>
Name : {{$res->billing_first_name.' '.$res->billing_last_name}}<br>
Email : {{$res->billing_email}} <br>
Phone : {{$res->billing_phone}} <br>
Address1 : {{$res->billing_address1}} <br>
Address2 : {{$res->billing_address2}}<br>
City : {{$billing_city->name}} <br>
Pin Code : {{$res->billing_pincode}} <br>
State : {{$billing_state->name}} <br>
Country : {{$billing_country->name}}
<br><b>Shipping Address</b> <br>
Name : {{$res->shipping_first_name.' '.$res->shipping_last_name}}<br>
Email : {{$res->shipping_email}} <br>
Phone : {{$res->shipping_phone}} <br>
Address1 : {{$res->shipping_address1}} <br>
Address2 : {{$res->shipping_address2}} <br>
City : {{$shipping_city->name}} <br>
Pin Code : {{$res->shipping_pincode}} <br>
State : {{$shipping_state->name}} <br>
Country : {{$shipping_country->name}} <br>
</td>
</tr>
</table>
</div>
<?php if($res->order_products->count()) { ?>
<table class="table table-striped">
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Total (Rs)</th>
</tr>
<?php foreach($res->order_products as $items) { ?>
<tr>
<td>{{$items->product_name}} <br>
<?php
if(!empty($items->products_images))
{
?>
<img src="{{ url($items->products_images) }}" style="width: 75px; height: 75;"> <br>
<?php } ?>
<?php if(!empty($items->size)) { ?>
<b>Size :</b> {{$items->size}} <br>
<?php } ?>
<?php if(!empty($items->length)) { ?>
<b>Length :</b> {{$items->length}} Meter <br>
<?php } ?>
<?php
$design_data = [];
if(!empty($items->fabric_generator))
{
$design_data = json_decode($items->fabric_generator);
//pr($design_data);?>
<?php if(!empty($design_data->layout)) { ?>
<b>Layout :</b> {{$design_data->layout}} <br>
<?php } ?>
<b>Rotate :</b> {{$design_data->rotate}} <br>
<b>Scale :</b> {{$design_data->scale}} <br>
<?php } ?>
</td>
<td>{{$items->price}}</td>
<td>{{$items->qty}}</td>
<td>{{$items->price*$items->qty}}</td>
</tr>
<?php } ?>
<tr>
<td></td>
<td></td>
<td><b>Sub Total</b></td>
<td>{{$res->sub_total}}</td>
</tr>
<?php if($res->discount > 0){?>
<tr>
<td></td>
<td></td>
<td><b>Discount</b></td>
<td>{{$res->discount}}</td>
</tr>
<?php } ?>
<?php if($res->tax > 0){?>
<tr>
<td></td>
<td></td>
<td><b>Tax</b></td>
<td>{{$res->tax}}</td>
</tr>
<?php } ?>
<?php if($res->shipping_charge > 0){?>
<tr>
<td></td>
<td></td>
<td><b>Shipping Charge</b></td>
<td>{{$res->shipping_charge}}</td>
</tr>
<?php } ?>
<?php if($res->used_wallet_amount > 0){?>
<tr>
<td></td>
<td></td>
<td><b>Used Wallet Amount</b></td>
<td>{{$res->used_wallet_amount}}</td>
</tr>
<?php } ?>
<tr>
<td></td>
<td></td>
<td><b>Total</b></td>
<td>{{$res->total}}</td>
</tr>
</table>
<?php } ?>
</div>
<?php
}
?>
</div>
<div class="row">
<div class="col-md-12">
<h3>Change Order Status </h3>
</div>
</div>
<form method="POST" action="" accept-charset="UTF-8" role="form">
{{ csrf_field() }}
<div class="row">
<table class="table table-striped">
<tr>
<th>Payent Status</th>
<th>Order Status</th>
<th>Comment *</th>
</tr>
<tr>
<td>
<select class="form-control" name="payment_status">
<option value="">Please Select</option>
<option <?php if($res->payment_status==0) { echo 'selected'; } ?> value="0">Pending</option>
<option <?php if($res->payment_status==1) { echo 'selected'; } ?> value="1">Recieved</option>
</select>
</td>
<td> <select class="form-control" name="order_status">
<?php foreach($order_status_list as $osl) { ?>
<option <?php if($res->order_status==$osl->status_id) { echo 'selected'; } ?> value="{{$osl->status_id}}">{{$osl->status}}</option>
<?php } ?>
</select></td>
<td><textarea class="form-control" name="comment"></textarea></td>
@include('snippets.errors_first', ['param' => 'comment'])
</th>
</tr>
<tr>
<td>
<input class="btn btn-sm btn-success" type="submit" name="change_order_status" value="Save">
</td>
</tr>
</table>
</div>
</form>
<div class="row">
<div class="col-md-12">
<h3>Order History </h3>
<?php if(!empty($order_history) && $order_history->count() )
{ ?>
<table class="table table-striped">
<tr>
<th>Order Status</th>
<th>Comment</th>
<th>Added On</th>
</tr>
<?php foreach($order_history as $oh)
{
$added_on = CustomHelper::DateFormat($oh->created_at, 'd F y');
?>
<tr>
<td>
<?php
foreach($order_status_list as $osl)
{
if($osl->status_id==$oh->status_id)
{
echo $osl->status;
}
}
?></td>
<td>{{$oh->comment}}</td>
<td>{{ $added_on}}</td>
</tr>
<?php } ?>
</table>
<?php } else echo 'No history found'; ?>
</div>
</div>
@endcomponent
|
/* eslint-disable no-unused-vars */
import React, {useState, useEffect} from 'react'
import { Form, Input, message } from 'antd'
import { Link , useNavigate} from 'react-router-dom'
import axios from '../Services/instance'
import Spinner from '../components/Spinner'
const LoginPage = () => {
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const submitHandler = async (values) => {
try {
setLoading(true);
const {data} =await axios.post('/users/login', values);
setLoading(false);
message.success('Login Successful');
localStorage.setItem('user', JSON.stringify({...data.user, password:""}));
navigate('/')
} catch (error) {
message.error('Something went wrong');
setLoading(false);
}
}
// prevent for login user
useEffect(() => {
if(localStorage.getItem("user")) {
navigate('/')
}
}, [navigate]);
return (
<>
<div className="register-page ">
<Form layout='vertical' onFinish={submitHandler}>
<h1>Login Page</h1>
<Form.Item label="Email" name='email'>
<Input type='email' />
</Form.Item>
<Form.Item label="Password" name='password'>
<Input type='password' />
</Form.Item>
{loading && <Spinner/>}
<div className="d-flex justify-content-between">
<Link to='/register'>Dont have an account? Register Here</Link>
</div>
<button className='btn btn-primary m-2'> Login</button>
</Form>
</div>
</>
)
}
export default LoginPage
|
<?php
namespace App\Http\Controllers;
use App\Branch;
use App\Product;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade as PDF;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Session;
class ProductController extends Controller
{
// Important properties
public $parentModel = Product::class;
public $parentRoute = 'product';
public $parentView = "admin.product";
/**
* This function return get totals
*
* @author Md. Al-Mahmud <mamun120520@gmail.com>
* @version 1.0
* @see
* @since 11/12/2022
* Time 13:18:45
* @param
* @return
*/
public function get_count()
{
# code...
$data = [];
if (Cache::get('total_products') && Cache::get('total_products') != null) {
$data['total_products'] = Cache::get('total_products');
} else {
$data['total_products'] = $this->parentModel::count();
Cache::put('total_products', $data['total_products']);
}
if (Cache::get('total_trashed_products') && Cache::get('total_trashed_products') != null) {
$data['total_trashed_products'] = Cache::get('total_trashed_products');
} else {
$data['total_trashed_products'] = $this->parentModel::onlyTrashed()->count();
Cache::put('total_trashed_products', $data['total_trashed_products']);
}
return $data;
}
#end
/**
* This function forget count
*
* @author Md. Al-Mahmud <mamun120520@gmail.com>
* @version 1.0
* @see
* @since 11/12/2022
* Time 14:23:01
* @param
* @return
*/
public function forget_count()
{
# code...
Cache::forget('total_trashed_products');
Cache::forget('total_products');
}
#end
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$items = $this->parentModel::with('branch')->orderBy('created_at', 'desc')->paginate(60);
return view($this->parentView . '.index', $this->get_count())->with('items', $items);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$data['branches'] = Branch::orderBy('created_at', 'desc')->get();
$data['flatTypes'] = [
'A' => 'A',
'B' => 'B',
'C' => 'C',
'D' => 'D',
'E' => 'E',
'G' => 'F',
'H' => 'I',
'J' => 'J',
'K' => 'K',
];
$data['floor_numbers'] = [
'1st' => '1st',
'2nd' => '2nd',
'3rd' => '3rd',
'4th' => '4th',
'5th' => '5th',
'6th' => '6th',
'7th' => '7th',
'8th' => '8th',
'9th' => '9th',
'10th' => '10th',
'12th' => '12th',
'13th' => '13th',
'14th' => '14th',
'15th' => '15th',
'16th' => '16th',
'17th' => '17th',
'18th' => '18th',
'19th' => '19th',
'20th' => '20th',
];
return view($this->parentView . '.create', $data);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request["product_unique_id"] = $request->branch_id . '-' . $request->flat_type . '-' . $request->floor_number;
$request->validate([
'branch_id' => 'required',
'flat_type' => 'required',
'floor_number' => 'required',
'flat_size' => 'required',
'unite_price' => 'required',
'total_flat_price' => 'required',
'net_sells_price' => 'required',
'product_unique_id' => 'required|unique:products',
], [
'product_unique_id.unique' => "Your product alreay exist. You should change project name, flat type or floor number."
]);
if (!$request->total_flat_price == $request->flat_size * $request->unite_price) {
Session::flash('error', "Total Flat Price Not equal to (Flat Size X Unite Price)");
return redirect()->back();
}
$netSallsPrice = $request->total_flat_price;
if (!empty($request->car_parking_charge)) {
$netSallsPrice += $request->car_parking_charge;
}
if (!empty($request->utility_charge)) {
$netSallsPrice += $request->utility_charge;
}
if (!empty($request->additional_work_charge)) {
$netSallsPrice += $request->additional_work_charge;
}
if (!empty($request->other_charge)) {
$netSallsPrice += $request->other_charge;
}
if (!empty($request->discount_or_deduction)) {
$netSallsPrice -= $request->discount_or_deduction;
}
if (!empty($request->refund_additional_work_charge)) {
$netSallsPrice -= $request->refund_additional_work_charge;
}
if ($request->net_sells_price != $netSallsPrice) {
Session::flash('error', "Net Sells Price Not Match");
return redirect()->back();
}
$product_new_img = '';
if ($request->hasFile('product_img')) {
$product_img = $request->product_img;
$temporaryName = time() . $product_img->getClientOriginalName();
$product_img->move("upload/product/", $temporaryName);
$product_new_img = 'upload/product/' . $temporaryName;
}
try {
$this->parentModel::create([
'product_unique_id' => $request->product_unique_id,
'branch_id' => $request->branch_id,
'flat_type' => $request->flat_type,
'floor_number' => $request->floor_number,
'flat_size' => $request->flat_size,
'unite_price' => $request->unite_price,
'total_flat_price' => $request->total_flat_price,
'car_parking_charge' => $request->car_parking_charge,
'utility_charge' => $request->utility_charge,
'additional_work_charge' => $request->additional_work_charge,
'other_charge' => $request->other_charge,
'discount_or_deduction' => $request->discount_or_deduction,
'refund_additional_work_charge' => $request->refund_additional_work_charge,
'net_sells_price' => $request->net_sells_price,
'product_img' => $product_new_img,
'description' => $request->description,
'create_by' => auth()->user()->email,
]);
Session::flash('success', "Successfully Create");
return redirect()->back();
} catch (\Exception $e) {
if ($e->getCode() == 23000) {
Session::flash('error', 'Your product alreay exist. You should change project name, flat type or floor number.');
} else {
Session::flash('error', $e->getMessage());
}
return redirect()->back()->withInput($request->all());
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Request $request)
{
$item = $this->parentModel::find($request->id);
if (empty($item)) {
Session::flash('error', "Item not found");
return redirect()->back();
}
return view($this->parentView . '.show')->with('items', $item);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$data['item'] = $this->parentModel::find($id);
$data['branches'] = Branch::orderBy('created_at', 'desc')->get();
$data['flatTypes'] = [
'A' => 'A',
'B' => 'B',
'C' => 'C',
'D' => 'D',
'E' => 'E',
'G' => 'F',
'H' => 'I',
'J' => 'J',
'K' => 'K',
];
$data['floor_numbers'] = [
'1st' => '1st',
'2nd' => '2nd',
'3rd' => '3rd',
'4th' => '4th',
'5th' => '5th',
'6th' => '6th',
'7th' => '7th',
'8th' => '8th',
'9th' => '9th',
'10th' => '10th',
'12th' => '12th',
'13th' => '13th',
'14th' => '14th',
'15th' => '15th',
'16th' => '16th',
'17th' => '17th',
'18th' => '18th',
'19th' => '19th',
'20th' => '20th',
];
if (empty($data['item'])) {
Session::flash('error', "Item not found");
return redirect()->back();
}
return view($this->parentView . '.edit', $data);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'flat_size' => 'required',
'unite_price' => 'required',
'total_flat_price' => 'required',
'net_sells_price' => 'required'
]);
if (!$request->total_flat_price == $request->flat_size * $request->unite_price) {
Session::flash('error', "Total Flat Price Not equal to (Flat Size X Unite Price)");
return redirect()->back();
}
$netSallsPrice = $request->total_flat_price;
if (!empty($request->car_parking_charge)) {
$netSallsPrice += $request->car_parking_charge;
}
if (!empty($request->utility_charge)) {
$netSallsPrice += $request->utility_charge;
}
if (!empty($request->additional_work_charge)) {
$netSallsPrice += $request->additional_work_charge;
}
if (!empty($request->other_charge)) {
$netSallsPrice += $request->other_charge;
}
if (!empty($request->discount_or_deduction)) {
$netSallsPrice -= $request->discount_or_deduction;
}
if (!empty($request->refund_additional_work_charge)) {
$netSallsPrice -= $request->refund_additional_work_charge;
}
if ($request->net_sells_price != $netSallsPrice) {
Session::flash('error', "Net Sells Price Not Match");
return redirect()->back();
}
$items = $this->parentModel::find($id);
$product_new_img = '';
if ($request->hasFile('product_img')) {
if (!empty($items->product_img)) {
unlink($items->product_img); // Delete previous image file
}
$product_img = $request->product_img;
$temporaryName = time() . $product_img->getClientOriginalName();
$product_img->move("upload/product/", $temporaryName);
$product_new_img = 'upload/product/' . $temporaryName;
}
$items->flat_size = $request->flat_size;
$items->unite_price = $request->unite_price;
$items->total_flat_price = $request->total_flat_price;
$items->car_parking_charge = $request->car_parking_charge;
$items->utility_charge = $request->utility_charge;
$items->additional_work_charge = $request->additional_work_charge;
$items->other_charge = $request->other_charge;
$items->discount_or_deduction = $request->discount_or_deduction;
$items->refund_additional_work_charge = $request->refund_additional_work_charge;
$items->net_sells_price = $request->net_sells_price;
$items->description = $request->description;
$items->updated_by = auth()->user()->email;
try {
$items->save();
Session::flash('success', "Update Successfully");
return redirect()->route($this->parentRoute);
} catch (\Exception $e) {
dd($e);
Session::flash('error', $e->getMessage());
return redirect()->route($this->parentRoute);
}
}
public function pdf(Request $request)
{
$item = $this->parentModel::find($request->id);
if (empty($item)) {
Session::flash('error', "Item not found");
return redirect()->back();
}
$now = new \DateTime();
$date = $now->format(Config('settings.date_format') . ' h:i:s');
$extra = array(
'current_date_time' => $date,
'module_name' => 'Product Manage'
);
$pdf = PDF::loadView($this->parentView . '.pdf', ['items' => $item, 'extra' => $extra])->setPaper('a4', 'landscape');
//return $pdf->stream('invoice.pdf');
return $pdf->download($extra['current_date_time'] . '_' . $extra['module_name'] . '.pdf');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$items = $this->parentModel::with('sell')->find($id);
if ($items->sell != null && $items->sell->count() > 0) {
Session::flash('error', "You can not delete it. Because it has some item");
return redirect()->back();
}
$items->deleted_by = auth()->user()->email;
$items->save();
$items->delete();
// forget count
$this->forget_count();
Session::flash('success', "Successfully Trashed");
return redirect()->back();
}
public function trashed()
{
$items = $this->parentModel::with('branch')->onlyTrashed()->paginate(60);
return view($this->parentView . '.trashed', $this->get_count())->with("items", $items);
}
public function restore($id)
{
$items = $this->parentModel::onlyTrashed()->where('id', $id)->first();
$items->restore();
// forget count
$this->forget_count();
Session::flash('success', 'Successfully Restore');
return redirect()->back();
}
public function kill($id)
{
$item = $this->parentModel::withTrashed()->with('sell')->where('id', $id)->first();
if ($item->sell != null && $item->sell->count() > 0) {
Session::flash('error', "You can not delete it. Because it already Sold");
return redirect()->back();
}
$item->forceDelete();
Session::flash('success', 'Permanently Delete');
// forget count
$this->forget_count();
return redirect()->back();
}
public function activeSearch(Request $request)
{
$request->validate([
'search' => 'min:1'
]);
$search = $request["search"];
$items = $this->parentModel::where('flat_type', 'like', '%' . $search . '%')
->orWhereHas('branch', function ($query) use ($search) {
$query->where('name', 'like', '%' . $search . '%');
})
->orWhere('product_unique_id', 'like', '%' . $search . '%')
->orWhere('floor_number', 'like', '%' . $search . '%')
->orWhere('flat_size', 'like', '%' . $search . '%')
->orWhere('unite_price', 'like', '%' . $search . '%')
->orWhere('total_flat_price', 'like', '%' . $search . '%')
->orWhere('car_parking_charge', 'like', '%' . $search . '%')
->orWhere('utility_charge', 'like', '%' . $search . '%')
->orWhere('additional_work_charge', 'like', '%' . $search . '%')
->orWhere('other_charge', 'like', '%' . $search . '%')
->orWhere('discount_or_deduction', 'like', '%' . $search . '%')
->orWhere('refund_additional_work_charge', 'like', '%' . $search . '%')
->orWhere('net_sells_price', 'like', '%' . $search . '%')
->paginate(60);
return view($this->parentView . '.index', $this->get_count())
->with('items', $items);
}
public function trashedSearch(Request $request)
{
$request->validate([
'search' => 'min:1'
]);
$search = $request["search"];
$items = $this->parentModel::where('flat_type', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhereHas('branch', function ($query) use ($search) {
$query->where('name', 'like', '%' . $search . '%');
})
->onlyTrashed()
->orWhere('product_unique_id', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhere('floor_number', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhere('flat_size', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhere('unite_price', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhere('total_flat_price', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhere('car_parking_charge', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhere('utility_charge', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhere('additional_work_charge', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhere('other_charge', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhere('discount_or_deduction', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhere('refund_additional_work_charge', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhere('net_sells_price', 'like', '%' . $search . '%')
->onlyTrashed()
->orWhere('description', 'like', '%' . $search . '%')
->onlyTrashed()
->paginate(60);
return view($this->parentView . '.trashed', $this->get_count())
->with('items', $items);
}
// Fixed Method for all
public function activeAction(Request $request)
{
$request->validate([
'items' => 'required'
]);
if ($request->apply_comand_top == 3 || $request->apply_comand_bottom == 3) {
foreach ($request->items["id"] as $id) {
$this->destroy($id);
}
return redirect()->back();
} elseif ($request->apply_comand_top == 2 || $request->apply_comand_bottom == 2) {
foreach ($request->items["id"] as $id) {
$this->kill($id);
}
return redirect()->back();
} else {
Session::flash('error', "Something is wrong.Try again");
return redirect()->back();
}
}
public function trashedAction(Request $request)
{
$request->validate([
'items' => 'required'
]);
if ($request->apply_comand_top == 1 || $request->apply_comand_bottom == 1) {
foreach ($request->items["id"] as $id) {
$this->restore($id);
}
} elseif ($request->apply_comand_top == 2 || $request->apply_comand_bottom == 2) {
foreach ($request->items["id"] as $id) {
$this->kill($id);
}
return redirect()->back();
} else {
Session::flash('error', "Something is wrong.Try again");
return redirect()->back();
}
return redirect()->back();
}
}
|
package maison;
public abstract class Piece {
private double superficie;
private Integer numeroEtage;
private String type;
/**
* @param superficie
* @param numeroEtage
*/
public Piece(double superficie, Integer numeroEtage) {
super();
if (superficie < 0 || superficie == 0.0) {
throw new IllegalArgumentException("La superficie ne peut pas être ni négative ni null.");
}
if (numeroEtage == null) {
throw new IllegalArgumentException("Le numéro d'étage ne peut pas être null.");
}
this.superficie = superficie;
this.numeroEtage = numeroEtage;
}
/**
* @return the superficie
*/
public double getSuperficie() {
return superficie;
}
/**
* @param superficie the superficie to set
*/
public void setSuperficie(double superficie) {
if (superficie < 0 || superficie == 0.0) {
throw new IllegalArgumentException("La superficie ne peut pas être ni négative ni null.");
}
this.superficie = superficie;
}
/**
* @return the numeroEtage
*/
public Integer getNumeroEtage() {
return numeroEtage;
}
/**
* @param numeroEtage the numeroEtage to set
*/
public void setNumeroEtage(Integer numeroEtage) {
if (numeroEtage == null) {
throw new IllegalArgumentException("Le numéro d'étage ne peut pas être null.");
}
this.numeroEtage = numeroEtage;
}
@Override
public String toString() {
return "Piece [superficie=" + superficie + ", numeroEtage=" + numeroEtage + "]";
}
/**
* @return the type
*/
public String getType() {
return type;
}
}
|
import React, {useState} from 'react';
import {Button, Dialog, DialogContent, DialogTitle, Paper} from '@mui/material';
import styles from '../styles/Post.module.css';
import Link from 'next/link';
import {Vote, VoteDocument} from '../dal/generated/graphql';
import {useMutation} from '@apollo/client';
import {spans} from 'next/dist/build/webpack/plugins/profiling-plugin';
type PostProps = {
description: string
linkURL: string
postId: string
votes: Vote[]
}
export const Post = (props: PostProps) => {
const {description, linkURL, postId, votes} = props;
const [vote, {data}] = useMutation(VoteDocument);
const [votesList, setVotesList] = useState(votes.slice(0, 6));
const [open, setOpen] = useState(false)
const votesLength = votes.length;
const restVotes = votesLength - votesList.length
const voteHandler = async () => {
try {
const res = await vote({
variables: {
linkId: postId
},
context: {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`
}
}
});
} catch (e) {
console.error(e);
}
};
return (
<Paper className={styles.postWrapper} elevation={12}>
<div className={styles.description}>
<Link href={linkURL}>
<a target={'_blank'}>
<h2>{description}</h2>
</a>
</Link>
</div>
<div className={styles.actionsArea}>
<div>
<Button onClick={voteHandler} disabled={ !!data}>Upvote</Button>
</div>
<div className={styles.votes} onClick={()=>setOpen(true)}>
{votes.length > 0 ? votesList.map(el => {
return <div className={styles.voters}
key={el.id}>{el.user.name[0] ? el.user.name[0].toUpperCase()
: 'U'
}</div>;
})
: <div className={styles.votes}>not upvote</div>
}
{restVotes > 0 ? '+' + restVotes : ''}
</div>
</div>
<Dialog
open={open}
onClose={()=>setOpen(false)}>
<DialogTitle>Upvotes</DialogTitle>
<DialogContent>
<div style={{"width": '300px'}}>
{votes.length > 0 ? votes.map(el => {
return (
<><span className={styles.voters}
key={el.id}>{el.user.name[0] ? el.user.name[0].toUpperCase()
: 'U'
}</span>
<span>{el.user.name}</span>
</>
)
})
: <div className={styles.votes}>not upvote</div>
}
</div>
</DialogContent>
</Dialog>
</Paper>
);
};
|
# Documentation for YouTube Video Processing and Meeting Minutes Generator
## Overview
This application processes YouTube videos to transcribe the audio, generate meeting minutes, and interactively display this information on a Streamlit web interface. It extracts abstract summaries, key points, and action items from the transcribed text, and offers interactive features for user engagement with the AI-generated content.
## Installation
### Prerequisites
- Python 3.x
- Streamlit
- OpenAI API key
### Dependencies
Install the required libraries using pip:
```bash
pip install openai streamlit python-dotenv langchain-community youtube-dl python-docx
```
# Environment Setup
1. Obtain an API key from OpenAI.
2. Create a .env file in the project root and add your OpenAI API key:
```plaintext
OPENAI_API_KEY=your_openai_api_key_here
```
3. Load the environment variables in your script by calling load_dotenv().
# Application Functions
## transcribe_audio(audio_file_path)
Transcribes audio content from a specified file using OpenAI's Whisper model.
- Parameters:
- audio_file_path: Path to the audio file.
- Returns:
- The transcribed text as a string.
## abstract_summary_extraction(transcription)
Generates an abstract summary from the provided transcription.
- Parameters:
- transcription: The text of the transcription.
- Returns:
- An abstract summary as a string.
## key_points_extraction(transcription)
Identifies key points from the transcription.
- Parameters:
- transcription: The text of the transcription.
- Returns:
- A string listing the key points.
## action_item_extraction(transcription)
Extracts actionable items from the transcription.
- Parameters:
- transcription: The text of the transcription.
- Returns:
- A string listing the action items.
## meeting_minutes(transcription)
Combines the outputs of abstract summary, key points, and action item extractions into a structured format.
- Parameters:
- transcription: The text of the transcription.
- Returns:
- A dictionary with the abstract summary, key points, and action items.
## save_as_docx(minutes, filename)
Saves the meeting minutes into a DOCX file.
- Parameters:
- minutes: Dictionary containing meeting minutes sections.
- filename: Desired filename for the DOCX document.
## process_youtube_video(url)
Processes a YouTube video URL to extract and transcribe audio, then generates meeting minutes.
- Parameters:
- url: YouTube video URL.
- Returns:
- Transcription text, meeting minutes dictionary, and DOCX filename.
Streamlit UI Components
This section of the script initializes and manages the Streamlit user interface, facilitating user interaction with the video processing and meeting minutes features. It includes text inputs, video displays, expanders for content display, and chat functionality for dynamic interaction with the AI
|
require 'rails_helper'
RSpec.describe Item, type: :model do
it 'soft deletes the item' do
item = Item.create(name: 'Test Item')
item.soft_delete
expect(item.deleted_at).not_to be_nil
end
it 'restores the item' do
item = Item.create(name: 'Test Item', deleted_at: Time.current)
item.restore
expect(item.deleted_at).to be_nil
end
it 'excludes soft-deleted items from default scope' do
Item.create(name: 'Test Item', deleted_at: Time.current)
expect(Item.all).to be_empty
end
end
|
const starCSV = [["StarID", "Name", "X", "Y", "Z"],
["100", "Jasper", "0.55", "0.9", "3.4"],
["101", "Isabelle", "0.7", "1.8", "8.9"]];
const studentCSV = [["Name", "GradYear", "Height", "Weight"],
["Jasper", "2027", "70", "180"],
["Charlie", "2026", "72", "170"],
["Ashley", "2025", "67", "120"],
["Lucas", "2024", "80", "220"]];
const noHeadersStudentCSV = [["Jasper", "2027", "70", "180"],
["Charlie", "2026", "72", "170"],
["Ashley", "2025", "67", "120"],
["Lucas", "2024", "80", "220"]];
const noHeadersStarCSV = [["100", "Jasper", "0.55", "0.9", "3.4"],
["101", "Isabelle", "0.7", "1.8", "8.9"]];
const blankCSV = [[""]];
const csvFileMap: Map<string, string[][]> = new Map([
["./star_csv", starCSV],
["./student_csv", studentCSV],
["./blank_csv", blankCSV],
["./star_csv_no_headers", noHeadersStarCSV],
["./student_csv_no_headers", noHeadersStudentCSV]
]);
const fileNameToArgs: Map<string[][], string[][]> = new Map([
[starCSV, [["Name", "Jasper"], ["1", "Jasper"]]],
[studentCSV, [["Height", "72"], ["2", "72"]]],
[noHeadersStarCSV, [["1", "Jasper"]]],
[noHeadersStudentCSV, [["2", "72"]]]
]);
const starResults = [["100", "Jasper", "0.5", "0.9", "3.4"]]
const studentResults = [["Charlie", "2026", "72", "170"]];
const csvSearchMap: Map<string[][], string[][]> = new Map([
[starCSV, starResults],
[studentCSV, studentResults],
[noHeadersStarCSV, starResults],
[noHeadersStudentCSV, studentResults]
]);
var currentCSV = [[""]];
var isLoaded = false;
/**
* Checks if the array of string arrays contains a specific string array
*
* @param arrays - An array of arrays of strings to check within
* @param targetArray - an array of strings that we are checking whether it lies within 'arrays'
* @return true if the targetArray was found in array, false otherwise.
*/
function containsArray(arrays: string[][], targetArray: string[]): boolean {
return arrays.some(array => array.every((value, index) => value === targetArray[index]));
}
/**
* Displays the loaded csv file as a table, or displays a failure message
*
* @param args - An array of the strings which are the arguments provided by the user that followed the 'view' command
* @return a react element containing either the failure message or the file table
*/
export function view(args: string[]){
if (!isLoaded){
return(
<span>View requires a file to have been loaded using load_file but no file is loaded yet</span>
);
}
if(args.length != 0){
return(
<span>View requires 0 arguments but you provided {args.length}</span>
);
}
return convertStringList(currentCSV);
}
/**
* Loads the provided csv file into the 'currentCSV' variable to be viewed or searched accordingly
*
* @param args - An array of the strings which are the arguments provided by the user that followed the 'load_file' command
* @return a ReactElement containing either a success response or a failure method
*/
export function loadFile(args: string[]){
if(args.length != 1){
return(
<span>Load requires 1 argument but you provided {args.length}</span>
);
}
const fileName = args[0];
const successResponse = <span>Successfully loaded</span>;
if(fileName == "./malformed_csv"){
return <span>Malformed csv file</span>;
}
if(csvFileMap.has(fileName)){
currentCSV = csvFileMap.get(fileName)!;
setLoadedTrue();
return successResponse;
}else{
return <span>File '{fileName}' not found</span>;
}
}
function setLoadedTrue(){
if(!isLoaded){
isLoaded = true;
}
}
//search (from server) returns "error_bad_request" for any bad inputs. thus no checking parameters?
//args should be
/**
* Searches the currently loaded csv file by the column and value provided, outputting the row(s) that contain the
* specified value in the specified column
*
* @param args - An array of the strings which are the arguments provided by the user that followed the 'search' command
* @return a ReactElement containing either the row(s) that match the search or a failure method
*/
export function search(args: string[]){
if (!isLoaded){
return(
<span>Search requires a file to have been loaded using load_file but no file is loaded yet</span>
);
}
if(args.length != 2){
return(
<span>Search requires 2 arguments but you provided {args.length}</span>
);
}
if(fileNameToArgs.has(currentCSV)){
if(containsArray(fileNameToArgs.get(currentCSV)!, args)){
return convertStringList(csvSearchMap.get(currentCSV)!);
}
}
return <span>Search unsuccessful</span>
}
/**
* Converts a provided array of string arrays to a ReactElement table
*
* @param data - A list of lists of strings to be converted to a ReactElement table
* @return a ReactElement table generated from the provided list of lists of strings
*/
function convertStringList(data: string[][]){
return (
<table>
{data.map((row) =>
<tr>
{row.map((element) =>
<td>{element}</td>)}
</tr>)
}
</table>
);
}
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: '',
redirectTo: 'layout',
pathMatch: 'full',
},
{
path: 'layout',
loadChildren: () => import('./iris-modules/layouts/secure-layout/secure-layout.module').then((x) => x.SecureLayoutModule),
},
{
path: 'auth',
loadChildren: () => import('./iris-modules/layouts/public-layout/public-layout.module').then((x) => x.PublicLayoutModule)
},
{ path: '**', redirectTo: '' },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
#pragma once
#include <RecastPlugin/RecastPluginDLL.h>
#include <Core/World/WorldModule.h>
class dtCrowd;
class dtCrowdAgent;
class plRecastWorldModule;
struct plDetourCrowdAgentParams
{
/// \brief Agent radius. [Limit: >= 0]
float m_fRadius;
/// \brief Agent height. [Limit: > 0]
float m_fHeight;
/// \brief Maximum allowed acceleration. [Limit: >= 0]
float m_fMaxAcceleration;
/// \brief Maximum allowed speed. [Limit: >= 0]
float m_fMaxSpeed;
/// \brief How aggresive the agent manager should be at avoiding collisions with this agent. [Limit: >= 0]
float m_fSeparationWeight;
void* m_pUserData;
static inline plDetourCrowdAgentParams Default()
{
plDetourCrowdAgentParams params;
params.m_fRadius = 0.3f;
params.m_fHeight = 1.8f;
params.m_fMaxAcceleration = 10.0f;
params.m_fMaxSpeed = 3.5f;
params.m_fSeparationWeight = 2.0f;
params.m_pUserData = nullptr;
return params;
}
};
class PL_RECASTPLUGIN_DLL plDetourCrowdWorldModule : public plWorldModule
{
PL_DECLARE_WORLD_MODULE();
PL_ADD_DYNAMIC_REFLECTION(plDetourCrowdWorldModule, plWorldModule);
public:
plDetourCrowdWorldModule(plWorld* pWorld);
~plDetourCrowdWorldModule();
virtual void Initialize() override;
virtual void Deinitialize() override;
bool IsInitializedAndReady() const;
const dtCrowdAgent* GetAgentById(plInt32 iAgentId) const;
/// \brief Tries to create a new crowd agent and returns its ID or -1.
plInt32 CreateAgent(const plVec3& vPos, const plDetourCrowdAgentParams& params);
void DestroyAgent(plInt32 iAgentId);
void SetAgentTargetPosition(plInt32 iAgentId, const plVec3& vPos, const plVec3& vQueryHalfExtents = plVec3(0.5f, 0.5f, 0.5f));
void ClearAgentTargetPosition(plInt32 iAgentId);
void UpdateAgentParams(plInt32 iAgentId, const plDetourCrowdAgentParams& params);
private:
void UpdateNavMesh(const UpdateContext& ctx);
void UpdateCrowd(const UpdateContext& ctx);
void VisualizeCrowd(const UpdateContext& ctx);
void FillDtCrowdAgentParams(const plDetourCrowdAgentParams& params, struct dtCrowdAgentParams& out_params) const;
plInt32 m_iMaxAgents = 128;
float m_fMaxAgentRadius = 2.0f;
dtCrowd* m_pDtCrowd = nullptr;
plRecastWorldModule* m_pRecastModule = nullptr;
};
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.edu.ifnmg.trabalho.telas;
import br.edu.ifnmg.trabalho.DataAccess.ClienteDao;
import br.edu.ifnmg.trabalho.DataAccess.ClienteFuncionarioDao;
import br.edu.ifnmg.trabalho.classes.Cliente;
import br.edu.ifnmg.trabalho.classes.Email;
import br.edu.ifnmg.trabalho.classes.Endereco;
import br.edu.ifnmg.trabalho.classes.ErroValidacaoException;
import br.edu.ifnmg.trabalho.classes.Pessoa;
import br.edu.ifnmg.trabalho.classes.Telefone;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
/**
*
* @author emerson
*/
public class frmClienteListar extends javax.swing.JInternalFrame {
ClienteDao dao;
ClienteFuncionarioDao cfdao;
/**
* Creates new form frmListarProduto
*/
public frmClienteListar() throws ErroValidacaoException, ParseException {
initComponents();
dao = new ClienteDao();
cfdao = new ClienteFuncionarioDao();
List<Cliente> clientes = dao.listarTodos();
List<Telefone> telefones = cfdao.listarTodosTelefone();
List<Email> emails = cfdao.listarTodosEmail();
List<Endereco> enderecos = cfdao.listarTodosEndereco();
preencheTabela(clientes);
preencheTabelaTele(telefones);
preencheTabelaEmail(emails);
preencheTabelaEndereco(enderecos);
}
//Metodo para listar Produtos na Tabela tblListagemProd
private void preencheTabela(List<Cliente> lista) {
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Id");
model.addColumn("Nome");
model.addColumn("Cpf");
model.addColumn("Rg");
model.addColumn("Nascimento");
for (Cliente clientes : lista) {
Vector valores = new Vector();
valores.add(0,clientes.getId());
valores.add(1,clientes.getNome());
valores.add(2,clientes.getCpf());
valores.add(3,clientes.getRg());
valores.add(4,clientes.getDataRetorno());
model.addRow(valores);
}
tblListagemCliente.setModel(model);
tblListagemCliente.repaint();
}
private void preencheTabelaTele(List<Telefone> lista) {
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Id");
model.addColumn("Telefone");
for (Telefone telefones : lista) {
Vector valores = new Vector();
valores.add(0,telefones.getId());
valores.add(1,telefones.getNum());
model.addRow(valores);
}
jtbTelefone.setModel(model);
jtbTelefone.repaint();
}
private void preencheTabelaEmail(List<Email> lista) {
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Id");
model.addColumn("Email");
for (Email emails : lista) {
Vector valores = new Vector();
valores.add(0,emails.getId());
valores.add(1,emails.getEmail_nome());
model.addRow(valores);
}
jtbEmails.setModel(model);
jtbEmails.repaint();
}
private void preencheTabelaEndereco(List<Endereco> lista) {
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Id");
model.addColumn("Rua");
model.addColumn("Num");
model.addColumn("Bairro");
for (Endereco ends : lista) {
Vector valores = new Vector();
valores.add(0,ends.getId());
valores.add(1,ends.getRua());
valores.add(2,ends.getNum());
valores.add(3,ends.getBairro());
model.addRow(valores);
}
jtbEndereco.setModel(model);
jtbEndereco.repaint();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lblNomeProd = new javax.swing.JLabel();
txtFiltrarC = new javax.swing.JTextField();
btnFiltrarCliente = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tblListagemCliente = new javax.swing.JTable();
jpTituloProdutoListar = new javax.swing.JPanel();
lblTituloProdutoListar = new javax.swing.JLabel();
lblTituloClienteListar = new javax.swing.JLabel();
jpRemoverItemtbEndereco = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jtbTelefone = new javax.swing.JTable();
jScrollPane3 = new javax.swing.JScrollPane();
jtbEndereco = new javax.swing.JTable();
jScrollPane4 = new javax.swing.JScrollPane();
jtbEmails = new javax.swing.JTable();
setClosable(true);
setPreferredSize(new java.awt.Dimension(1000, 420));
lblNomeProd.setText("Nome");
btnFiltrarCliente.setText("Filtrar");
btnFiltrarCliente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFiltrarClienteActionPerformed(evt);
}
});
tblListagemCliente.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
tblListagemCliente.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tblListagemClienteMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tblListagemCliente);
jpTituloProdutoListar.setBackground(new java.awt.Color(0, 102, 153));
lblTituloProdutoListar.setFont(new java.awt.Font("Dialog", 2, 10)); // NOI18N
lblTituloProdutoListar.setText("Clique sobre o produto para editar.");
lblTituloClienteListar.setFont(new java.awt.Font("Dialog", 2, 24)); // NOI18N
lblTituloClienteListar.setText("Listagem de Clientes");
javax.swing.GroupLayout jpTituloProdutoListarLayout = new javax.swing.GroupLayout(jpTituloProdutoListar);
jpTituloProdutoListar.setLayout(jpTituloProdutoListarLayout);
jpTituloProdutoListarLayout.setHorizontalGroup(
jpTituloProdutoListarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jpTituloProdutoListarLayout.createSequentialGroup()
.addGap(364, 364, 364)
.addGroup(jpTituloProdutoListarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblTituloClienteListar)
.addGroup(jpTituloProdutoListarLayout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(lblTituloProdutoListar)))
.addContainerGap(385, Short.MAX_VALUE))
);
jpTituloProdutoListarLayout.setVerticalGroup(
jpTituloProdutoListarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpTituloProdutoListarLayout.createSequentialGroup()
.addComponent(lblTituloClienteListar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblTituloProdutoListar))
);
jpRemoverItemtbEndereco.setBackground(new java.awt.Color(0, 102, 153));
jLabel3.setFont(new java.awt.Font("Dialog", 2, 12)); // NOI18N
jLabel3.setText("Clique sobre algum campo para ver versão FULL ");
javax.swing.GroupLayout jpRemoverItemtbEnderecoLayout = new javax.swing.GroupLayout(jpRemoverItemtbEndereco);
jpRemoverItemtbEndereco.setLayout(jpRemoverItemtbEnderecoLayout);
jpRemoverItemtbEnderecoLayout.setHorizontalGroup(
jpRemoverItemtbEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpRemoverItemtbEnderecoLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3)
.addGap(113, 113, 113))
);
jpRemoverItemtbEnderecoLayout.setVerticalGroup(
jpRemoverItemtbEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jpRemoverItemtbEnderecoLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jtbTelefone.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jScrollPane2.setViewportView(jtbTelefone);
jtbEndereco.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jScrollPane3.setViewportView(jtbEndereco);
jtbEmails.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jScrollPane4.setViewportView(jtbEmails);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jpTituloProdutoListar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jpRemoverItemtbEndereco, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(lblNomeProd)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtFiltrarC, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnFiltrarCliente))
.addComponent(jScrollPane1))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 418, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jpTituloProdutoListar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtFiltrarC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblNomeProd)
.addComponent(btnFiltrarCliente))
.addGap(34, 34, 34)
.addComponent(jpRemoverItemtbEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(32, 32, 32))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnFiltrarClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFiltrarClienteActionPerformed
Cliente c = new Cliente();
try{
c.setNome(txtFiltrarC.getText());
}catch(Exception ex){
System.out.printf("Erro");
}
List<Cliente> lista = null;
try {
lista = dao.buscar(c);
} catch (ErroValidacaoException ex) {
System.out.printf("Erro");
}
preencheTabela(lista);
}//GEN-LAST:event_btnFiltrarClienteActionPerformed
private void tblListagemClienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblListagemClienteMouseClicked
Object valor = tblListagemCliente.getValueAt( tblListagemCliente.getSelectedRow(), 0);
Cliente cliente = null;
try {
cliente = dao.Abrir((int)valor);
} catch (ErroValidacaoException ex) {
System.out.printf("Erro"); }
frmClienteEditar janela = null;
try {
janela = new frmClienteEditar(cliente, dao);
} catch (ErroValidacaoException ex) {
Logger.getLogger(frmClienteListar.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParseException ex) {
Logger.getLogger(frmClienteListar.class.getName()).log(Level.SEVERE, null, ex);
}
this.getParent().add(janela);
janela.setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_tblListagemClienteMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnFiltrarCliente;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JPanel jpRemoverItemtbEndereco;
private javax.swing.JPanel jpTituloProdutoListar;
private javax.swing.JTable jtbEmails;
private javax.swing.JTable jtbEndereco;
private javax.swing.JTable jtbTelefone;
private javax.swing.JLabel lblNomeProd;
private javax.swing.JLabel lblTituloClienteListar;
private javax.swing.JLabel lblTituloProdutoListar;
private javax.swing.JTable tblListagemCliente;
private javax.swing.JTextField txtFiltrarC;
// End of variables declaration//GEN-END:variables
}
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:todo_app/core/functions/custom_toast.dart';
import 'package:todo_app/core/functions/navigation.dart';
import 'package:todo_app/core/functions/date_service.dart';
import 'package:todo_app/core/utils/app_colors.dart';
import 'package:todo_app/core/utils/app_strings.dart';
import 'package:todo_app/core/widgets/custom_btn.dart';
import 'package:todo_app/features/create_task/presentation/cubit/task_cubit.dart';
import 'package:todo_app/features/create_task/presentation/cubit/task_state.dart';
import '../../../../core/utils/app_assets.dart';
class CreateTask extends StatefulWidget {
final Size? size;
const CreateTask({super.key, this.size});
@override
State<CreateTask> createState() => _CreateTaskState();
}
class _CreateTaskState extends State<CreateTask> {
TaskCubit? taskCubit;
DateTime currentDateTime = DateTime.now();
DateTime? datePicked;
TextEditingController taskTitle = TextEditingController();
TextEditingController taskDate = TextEditingController();
Widget _addTaskForm(BuildContext context) {
return Form(
key: taskCubit?.addTaskFormKey,
child: Column(
children: [
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(10),
),
fillColor: AppColors.grey,
filled: true,
hintText: AppStrings.taskTitleHint,
hintStyle: const TextStyle(color: Colors.black26),
contentPadding: const EdgeInsets.symmetric(horizontal: 10)),
style: const TextStyle(fontSize: 18),
controller: taskTitle,
),
20.height,
TextField(
readOnly: true,
onTap: () async {
datePicked = await selectDate(context, currentDateTime);
if (datePicked != null && datePicked != currentDateTime) {
setState(() {
String formattedDate = parseDate(datePicked!);
taskDate.text = formattedDate;
});
}
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(10),
),
fillColor: AppColors.grey,
filled: true,
hintText: AppStrings.dateHint,
hintStyle: const TextStyle(color: Colors.black26),
contentPadding: const EdgeInsets.symmetric(horizontal: 10)),
style: const TextStyle(fontSize: 18),
controller: taskDate,
),
],
));
}
@override
Widget build(BuildContext context) {
return BlocConsumer<TaskCubit, TaskStat>(listener: (context, state) {
if (state is TaskSuccessState) {
customReplacementNavigate(context, '/home');
} else if (state is TaskFailureState) {
showToast(state.errMessage);
}
}, builder: (context, state) {
taskCubit = BlocProvider.of<TaskCubit>(context);
return SizedBox(
height: widget.size!.height * 0.5,
child: Card(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Column(
children: [
10.height,
Align(
alignment: Alignment.centerRight,
child: Image.asset(Assets.imagesIcCancel,
width: 30, height: 30)
.onTap(() {
finish(context);
}),
),
20.height,
const Text(
AppStrings.createNewTask,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
30.height,
_addTaskForm(context),
30.height,
CustomBtn(
text: AppStrings.saveTask,
onPressed: () async {
if (taskCubit!.addTaskFormKey.currentState!.validate()) {
taskCubit?.taskTitle = taskTitle.text;
taskCubit?.timeStamp = currentDateTime;
taskCubit?.taskDate = datePicked;
await taskCubit?.createNewTask();
}
},
)
],
)),
),
);
});
}
}
|
package io.github.Speciallist.vendasapi.rest.clientes;
import java.time.LocalDate;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.github.Speciallist.vendasapi.model.Cliente;
public class ClienteFormRequest {
private Long id;
private String nome;
private String cpf;
@JsonFormat(pattern = "dd/MM/yyyy")
private LocalDate dataNascimento;
private String endereco;
private String email;
private String telefone;
@JsonFormat(pattern = "dd/MM/yyyy")
private LocalDate dataCadastro;
public ClienteFormRequest() {
super();
// TODO Auto-generated constructor stub
}
public ClienteFormRequest(Long id, String nome, String cpf, LocalDate dataNascimento, String endereco, String email,
String telefone, LocalDate dataCadastro) {
super();
this.id = id;
this.nome = nome;
this.cpf = cpf;
this.dataNascimento = dataNascimento;
this.endereco = endereco;
this.email = email;
this.telefone = telefone;
this.dataCadastro = dataCadastro;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public LocalDate getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(LocalDate dataNascimento) {
this.dataNascimento = dataNascimento;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public LocalDate getDataCadastro() {
return dataCadastro;
}
public void setDataCadastro(LocalDate dataCadastro) {
this.dataCadastro = dataCadastro;
}
public Cliente toModel() {
return new Cliente(id, dataNascimento, cpf, nome, endereco, telefone, email, dataCadastro);
}
public static ClienteFormRequest fromModel(Cliente cliente) {
return new ClienteFormRequest(cliente.getId(), cliente.getNome(), cliente.getCpf(), cliente.getDataNascimento(),
cliente.getEndereco(), cliente.getEmail(), cliente.getTelefone(), cliente.getDataCadastro());
}
}
|
object pairs {
def isPrime(n: Int): Boolean = (2 until n) forall (d => n % d != 0)
def primePairsComplex(n: Int): Seq[(Int, Int)] =
(1 until n) flatMap (i =>
(1 until i) map (j => (i, j))) filter (pair =>
isPrime(pair._1 + pair._2))
def primePairs(n: Int): Seq[(Int, Int)] =
for {
i <- 1 until n
j <- 1 until i
if isPrime(i + j)
} yield (i, j)
primePairsComplex(7)
primePairs(7)
def scalarProduct(xs: Vector[Double], ys: Vector[Double]): Double =
(for ((x, y) <- xs zip ys) yield (x * y)).sum
scalarProduct(Vector(1, 2, 3), Vector(1, 2, 3))
}
|
<template>
<div>
<el-button @click="openDialog()">
新增
</el-button>
<el-table
v-loading="loading"
:data="roles"
>
<el-table-column
prop="name"
label="商品名"
/>
<el-table-column
label="创建时间"
>
<template #default="scope">
{{ $filters.formatTime(scope.row.createdAt) }}
</template>
</el-table-column>
<el-table-column
label="操作"
>
<template #default="scope">
<el-button @click="openDialog(scope.row)">
修改
</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog
v-model="dialogVisible"
title="权限设置"
width="30%"
>
<el-input v-model="dialogData.name" />
<el-tree
ref="treeRef"
:data="permisstionList"
show-checkbox
node-key="id"
>
<template #default="{ data }">
<span>{{ data.name }}</span>
</template>
</el-tree>
<el-button @click="change">
{{ isChange ? '修改' : '新增' }}
</el-button>
</el-dialog>
</div>
</template>
<script setup>
import { ref, onBeforeMount } from 'vue';
import usePermission from '@/hooks/usePermission';
import { ElMessage } from 'element-plus';
import _ from 'lodash';
import {
getRoleList, updateRole, getRoleById, addRole,
} from '@/api/permission';
const { permisstionList, originList } = usePermission();
const dialogVisible = ref(false);
const roles = ref([]);
const loading = ref(false);
const dialogData = ref({});
const isChange = ref(true);
// * 树组件
const treeRef = ref();
async function getRoles() {
try {
roles.value = await getRoleList();
} catch (error) {
ElMessage.error(error.message);
} finally {
loading.value = false;
}
}
onBeforeMount(() => {
getRoles();
});
// * 重构node-key
const formatTree = (data) => {
const result = [];
originList.value.forEach((item) => {
if (data.includes(item.id)) {
result.push(item);
}
});
return result;
};
const openDialog = async (row) => {
if (row) {
isChange.value = true;
dialogData.value = _.cloneDeep(row);
dialogVisible.value = true;
// * 打开的时候,获取最新的该角色的权限列表
try {
loading.value = true;
// eslint-disable-next-line no-underscore-dangle
const { permission } = await getRoleById(row._id);
const treeNodes = formatTree(permission);
treeRef.value.setCheckedNodes(treeNodes, false);
} catch (error) {
ElMessage.error(error.message);
} finally {
loading.value = false;
}
} else {
isChange.value = false;
dialogData.value = {};
dialogVisible.value = true;
}
};
const change = async () => {
const permission = treeRef.value.getCheckedNodes(false, false);
try {
loading.value = true;
if (isChange.value) {
await updateRole({
name: dialogData.value.name,
permission: permission.map((item) => item.id),
// eslint-disable-next-line no-underscore-dangle
id: dialogData.value._id,
});
} else if (dialogData.value.name) {
await addRole({
name: dialogData.value.name,
permission: permission.map((item) => item.id),
// eslint-disable-next-line no-underscore-dangle
});
} else {
ElMessage.error('权限名不能为空');
}
dialogVisible.value = false;
ElMessage.success(isChange.value ? '修改成功' : '新增成功');
} catch (error) {
ElMessage.error(error.message);
} finally {
getRoles();
loading.value = false;
}
};
</script>
<style lang="scss" scoped>
</style>
|
import React, {useEffect, useState} from 'react';
import {AiFillCaretDown, AiFillCaretUp, AiOutlineInfoCircle} from 'react-icons/ai';
import {Col, OverlayTrigger, Popover, Row, Tooltip} from 'react-bootstrap';
function Racers({lapTimes}) {
const [racers, setRacers] = useState({
racerPositions: [],
mode: 'Racer', // can be "Racer" or "Alias"
sortByPos: '1',
sortByPosDir: 'desc',
sortByTotal: true
});
useEffect(() => {
// calc who has most LRs
const racerPositions = [];
const sanitizedLapTimes = lapTimes.initialTrackTimes.filter((tt) => tt.alias).map((lt) => {
if (lt.linkname === '#N/A') {
// console.log("mapping to " + lt.alias);
lt.linkname = lt.alias;
}
return lt;
});
const dedupedLapTimes = [];
for (const lt of sanitizedLapTimes) {
const foundI = dedupedLapTimes.findIndex((dlt) => dlt.track === lt.track && dlt.linkname === lt.linkname && dlt.class === lt.class);
if (foundI !== -1 && dedupedLapTimes[foundI].rank > lt.rank) {
dedupedLapTimes[foundI] = lt;
} else if (foundI === -1) {
dedupedLapTimes.push(lt);
}
}
for (const lrTime of dedupedLapTimes) {
// console.log(lrTime)
const lrFoundIndex = racerPositions.findIndex((lr) => lr.linkname === lrTime.linkname);
if (lrFoundIndex === -1) {
const newEntry = {
linkname: lrTime.linkname,
link: lrTime.link,
aliases: [lrTime.alias],
};
let totalAmount = 0;
for (let i = 1; i <= 10; i++) {
newEntry[`amount${i}`] = dedupedLapTimes.filter((lr) => lr.linkname === lrTime.linkname && lr.rank === i.toString()).length;
totalAmount += newEntry[`amount${i}`];
}
newEntry.totalAmount = totalAmount;
racerPositions.push(newEntry);
} else if (!racerPositions[lrFoundIndex].aliases.includes(lrTime.alias)) {
// lrTimes[lrFoundIndex].amount++;
racerPositions[lrFoundIndex].aliases.push(lrTime.alias);
}
}
let sortedPos;
if (!racers.sortByTotal) {
sortedPos = racerPositions.sort((a, b) => (racers.sortByPosDir === 'desc'
? b[`amount${racers.sortByPos}`] - a[`amount${racers.sortByPos}`]
: a[`amount${racers.sortByPos}`] - b[`amount${racers.sortByPos}`]));
} else {
sortedPos = racerPositions.sort((a, b) => (racers.sortByPosDir === 'desc' ? b.totalAmount - a.totalAmount : a.totalAmount - b.totalAmount));
}
setRacers({...racers, racerPositions: sortedPos});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [lapTimes.initialTrackTimes, racers.sortByPos, racers.sortByPosDir, racers.sortByTotal]);
function handleNumberSort(nr) {
setRacers((rcrs) => ({
...rcrs,
sortByPos: nr,
sortByPosDir: rcrs.sortByPosDir === 'asc' ? 'desc' : 'asc',
sortByTotal: false,
}));
}
function handleTotalSort() {
setRacers((rcrs) => ({
...rcrs,
sortByPosDir: rcrs.sortByPosDir === 'asc' ? 'desc' : 'asc',
sortByTotal: true,
}));
}
return (
<Col>
<Row>
<h2>
Racers Leaderboard Placements<span> </span>
<OverlayTrigger
key={'rTT'}
placement="bottom"
overlay={
<Popover id={`popover-positioned-1`}>
<Popover.Header as="h2">
Top10 Placements
</Popover.Header>
<Popover.Body>
<span>Amount of placements in the top10 per track.</span>
<br/><br/>
<span>If there is more than one alias recorded per track, the better time will be taken.</span>
<br/><br/>
<span>At the moment removed tracks will be taken into account.</span>
</Popover.Body>
</Popover>
}>
<span><AiOutlineInfoCircle/></span>
</OverlayTrigger>
</h2>
</Row>
<Row>
<table>
<thead>
<tr>
{/* <th>Rank</th> */}
<th>{racers.mode}</th>
{[...new Array(10)].map((el, i) => {
return (
<th
className={`racerTh ${racers.sortByPos === (i + 1).toString() && !racers.sortByTotal ? 'racerThActive' : ''}`}
onClick={() => handleNumberSort((i + 1).toString())}>
#
{i + 1}
{' '}
{racers.sortByPos === (i + 1).toString() && !racers.sortByTotal && (racers.sortByPosDir === 'desc' ? <AiFillCaretDown/> : <AiFillCaretUp/>)}
</th>
);
})}
<th
className={`racerTh ${racers.sortByTotal ? 'racerThActive' : ''}`}
onClick={() => handleTotalSort()}>
Total
{racers.sortByTotal && (racers.sortByPosDir === 'desc' ? <AiFillCaretDown/> : <AiFillCaretUp/>)}
</th>
</tr>
</thead>
<tbody>
{
racers.racerPositions.slice(0, 100).map((tt, i) => (
<tr key={i}>
{/* <td>{tt.track}</td> */}
{/* <td>{tt.class}</td> */}
{/* <td>{i + 1}</td> */}
{/* <td>{tt.linkname}</td> */}
<td>
{
tt.link
? <>
<OverlayTrigger
key={'leftTT' + i}
placement="left"
overlay={
<Tooltip id={`tooltip-leftTT${i}`}>
<span>Used Aliases:</span><br/>
{tt.aliases.map((al) => <><strong>{al}</strong><br/></>)}
</Tooltip>
}>
<span><AiOutlineInfoCircle/></span>
</OverlayTrigger>
<span> </span>
<a href={tt.link}>{tt.linkname}</a>
</>
: <span>{tt.linkname}</span>
}
</td>
{[...new Array(10)].map((el, index) => <td>{tt[`amount${index + 1}`]}</td>)}
<td>{tt.totalAmount}</td>
{/* <td>{tt.amount1}</td> */}
{/* <td>{tt.time}</td> */}
{/* <td>{tt.time.link ? <a href={tt.time.link}>{tt.time.linkname}</a> : <span>N/A</span>}</td> */}
</tr>
))
}
</tbody>
</table>
</Row>
</Col>
);
}
export default Racers;
|
import api from "@/utils/api";
import { useState, useEffect } from "react";
import { MovieDetails } from "../types/Movie";
interface MovieDetailsResult {
loading: boolean;
error: string | null;
data: MovieDetails | null;
}
const useMovieDetails = (id: string) => {
const [result, setResult] = useState<MovieDetailsResult>({
loading: false,
error: null,
data: null,
});
useEffect(() => {
const fetchMovieDetails = async () => {
setResult((prev) => ({ ...prev, loading: true }));
try {
const response = await api.get("/", {
params: {
i: id,
},
});
if (response.data.Response === "False") {
throw new Error("Movie not found");
}
setResult({
loading: false,
error: null,
data: response.data,
});
} catch (error) {
setResult({
loading: false,
// @ts-ignore
error: error.message,
data: null,
});
}
};
if (id) {
fetchMovieDetails();
}
}, [id]);
return result;
};
export default useMovieDetails;
|
import tkinter as tk
from tkinter import messagebox
from random import choice
from random import sample
import string
class GenereMdp:
"""
Affiche la fenetre de generation de mot de passe
@master: fenetre créée
@new_instance : instance de la classe interface
"""
def __init__(self, master, new_instance):
self.master = master
self.master.title("Générateur de mot de passe")
self.new_instance = new_instance
# Les cases à cocher
self.caseMinuscules_var = tk.BooleanVar()
self.caseMinuscules = tk.Checkbutton(self.master, text="Minuscules", variable=self.caseMinuscules_var)
self.caseMajuscules_var = tk.BooleanVar()
self.caseMajuscules = tk.Checkbutton(self.master, text="Majuscules", variable=self.caseMajuscules_var)
self.caseChiffres_var = tk.BooleanVar()
self.caseChiffres = tk.Checkbutton(self.master, text="Chiffres", variable=self.caseChiffres_var)
self.caseSymboles_var = tk.BooleanVar()
self.caseSymboles = tk.Checkbutton(self.master, text="Symboles", variable=self.caseSymboles_var)
self.caseMinuscules.select() # Pour cocher par défaut
self.caseMajuscules.select()
self.caseChiffres.select()
self.caseSymboles.select()
# Les boutons
self.boutonQuitter = tk.Button(self.master, text="Quitter", command=self.quitter)
self.boutonCopier = tk.Button(self.master, text="Copier", command=self.copier)
self.boutonGenerer = tk.Button(self.master, text="Générer", command=self.generer)
# Le champ de texte
self.champTexte = tk.Entry(self.master, width=30)
# La glissière
self.glissiereTaille = tk.Scale(self.master, from_=8, to=30, orient=tk.HORIZONTAL, label="Taille : 8", command=self.changerTailleMotDePasse)
# Positionnement des éléments
self.caseMajuscules.grid(row=0, column=0, pady=5)
self.glissiereTaille.grid(row=0, column=2, pady=5, columnspan=3)
self.caseMinuscules.grid(row=0, column=1, pady=5)
self.caseChiffres.grid(row=1, column=0, pady=5)
self.caseSymboles.grid(row=1, column=1, pady=5)
self.champTexte.grid(row=2, column=1, pady=10)
self.boutonQuitter.grid(row=3, column=2, pady=5)
self.boutonCopier.grid(row=3, column=0, pady=5)
self.boutonGenerer.grid(row=3, column=1, pady=5)
# Configuration de la fenêtre
self.master.protocol("WM_DELETE_WINDOW", self.quitter)
"""
Quitte la fenetre
"""
def quitter(self):
self.master.destroy()
"""
Copie le mot de passe généré dans le presse papier
et dans le champs mot de passe
"""
def copier(self):
mot_de_passe = self.champTexte.get()
if mot_de_passe:
self.master.clipboard_clear()
self.master.clipboard_append(mot_de_passe)
self.master.update()
self.new_instance.password_entry.delete(0, tk.END)
self.new_instance.password_entry.insert(0, mot_de_passe)
self.new_instance.password_entry_conf.delete(0, tk.END)
self.new_instance.password_entry_conf.insert(0, mot_de_passe)
else:
messagebox.showwarning("Mot de passe vide", "Le champ de mot de passe est vide.", parent=self.master)
return mot_de_passe
"""
Génère un mot de passe fort
@args: bool (true si option cochée, false sinon)
@return: mot de passe généré
"""
def genererMotDePasse(self, tailleMotDePasse=8, minuscules=True, majuscules=True, chiffres=True, symboles=True):
caracteres = ""
motDePasse = ""
if minuscules:
caracteres += string.ascii_lowercase
motDePasse += choice(string.ascii_lowercase)
if majuscules:
caracteres += string.ascii_uppercase
motDePasse += choice(string.ascii_uppercase)
if chiffres:
caracteres += string.digits
motDePasse += choice(string.digits)
if symboles:
caracteres += "&~#{([-|_\^@)=+$]}*%!/:.;?,"
motDePasse += choice("&~#{([-|_\^@)=+$]}*%!/:.;?,")
motDePasse += "".join(choice(caracteres) for _ in range(tailleMotDePasse - len(motDePasse)))
# Mélanger le mot de passe pour plus de sécurité
motDePasse = ''.join(sample(motDePasse, len(motDePasse)))
return motDePasse
"""
Prend en compte les choix de l'utilisateur et génère son mot de passe
"""
def generer(self):
taille_mot_de_passe = self.glissiereTaille.get()
minuscules = False
majuscules = False
chiffres = False
symboles = False
if self.caseMinuscules_var.get():
minuscules = True
if self.caseMajuscules_var.get():
majuscules = True
if self.caseChiffres_var.get():
chiffres = True
if self.caseSymboles_var.get():
symboles = True
if not majuscules and not minuscules and not chiffres and not symboles:
messagebox.showwarning("Impossible de générer", "Veuillez cocher les cases.", parent=self.master)
return
mot_de_passe = self.genererMotDePasse(taille_mot_de_passe, minuscules, majuscules, chiffres, symboles)
self.champTexte.delete(0, tk.END)
self.champTexte.insert(0, mot_de_passe)
"""
Met à jour l'affichage de la taille du mot de passe
@event (tk.Event): L'événement associé au changement de valeur de la glissière.
"""
def changerTailleMotDePasse(self, event):
taille = self.glissiereTaille.get()
self.glissiereTaille.configure(label=f"Taille : {taille}")
|
// .map()
const map = (arr, callback) => {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
newArr.push(callback(arr[i], i, arr));
}
return newArr;
}
// .reduce()
const reduce = (arr, callback, initialValue) => {
let acc = initialValue === undefined ? undefined : initialValue;
for (let i = 0; i < arr.length; i++) {
if (acc !== undefined) {
acc = callback(acc, arr[i], i, arr)
} else {
acc = arr[i]
}
}
return acc
}
// .filter()
const filter = (arr, callback) => {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i], i, arr)) {
newArr.push(arr[i]);
}
}
return newArr;
}
// Using custom functions
const mapFunc = (arr) => {
return arr.map(item => item * 2)
}
console.log(mapFunc([1, 2, 3, 4, 5]))
const foodItems = [
{
name: 'pizza',
amount: 5
},
{
name: 'burger',
amount: 10
},
{
name: 'sushi',
amount: 20
}
]
const reduceFunc = (arr) => {
return arr.reduce((acc, item) => acc + item.amount, 0)
}
console.log(reduceFunc(foodItems))
const filterFunc = (arr) => {
return arr.filter(arr => arr > 10)
}
console.log(filterFunc([1, 7, 8, 9, 10, 14, 19, 22]))
|
import PageLayout from '../shared/layout/PageLayout';
import Home from '../pages/home/Index';
import About from '../pages/about/Index';
import Blog from '../pages/blog/Index';
type RouteConfig = {
Component: React.JSX.Element;
state?: string;
label:string;
children?:[{label:string,subLabel:string,href:string}],
path:string
// outras propriedades do objeto, se houver
};
const routesConfig:Array<RouteConfig> = [
{
state:'home',
label:'Home',
path:'/',
Component:<PageLayout><Home/></PageLayout>
},{
state:'about',
label:'Sobre',
path:'/sobre',
Component:<PageLayout><About/></PageLayout>
},
{
state:'blog',
label:'Blog',
path:'/blog',
Component:<PageLayout><Blog/></PageLayout>,
children:[
{
label: 'Explore Design Work',
subLabel: 'Trending Design to inspire you',
href: '#',
}
]
}
];
export const getRoutesWithState = () => {
return routesConfig.filter(route => route.hasOwnProperty('state'));
}
export default routesConfig;
|
//
// ZoneView.swift
// Velcker_Correia-Mateus_SwiftMobile
//
// Created by Pain des bites on 23/03/2023.
//
import SwiftUI
struct ZoneView: View {
@EnvironmentObject var authentification: Authentification
@Environment(\.dismiss) private var dismiss
@ObservedObject var zone: ZoneViewModel
var intentZone: ZoneIntent
@State var nom: String
@State var nb_benevole : Int
@State var nb_benevole_present : Int
init(zone: ZoneViewModel) {
self.zone = zone
self.intentZone = ZoneIntent(zoneVM: zone)
self._nom = State(initialValue: zone.nom)
self._nb_benevole = State(initialValue: zone.nb_benevole)
self._nb_benevole_present = State(initialValue: 0)
}
var body: some View {
VStack(alignment: .leading) {
TextField("", text: $nom)
Picker("Benevole", selection: $nb_benevole) {
ForEach((1...10).reversed(), id: \.self) {
Text(verbatim: "\($0)").tag($0)
}
}
if(zone.nb_benevole_present >= zone.nb_benevole){
Text("Il y a assez de bénévole dans cette zone")
}else{
Text("Il n'y a pas assez de bénévole pour cette zone !")
}
}.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
NavBackButton(dismiss: self.dismiss, texte: "Retour")
}
}
.onAppear{
Task{
intentZone.getNbrBenevolePresent(token: authentification.token)
}
}
}
}
|
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Edit Contact</title>
@vite('resources/css/app.css')
</head>
<body>
<div class="flex flex-col items-center justify-center min-h-screen bg-gray-100">
<div class="px-32 py-32 mt-4 text-left bg-white shadow-lg">
<h3 class="text-2xl font-bold text-center">Edit a contact</h3>
<form action="{{ route('editContact', ['id' => $contact_id]) }}" method="post">
@csrf
@method('put')
<div class="mt-8">
<div class="mt-2">
<label class="block" for="contact_name">Contact Name<label>
<input type="text" placeholder="Contact Name" autocomplete="off" name="contact_name"
class="w-full px-4 py-2 mt-2 border rounded-md focus:outline-none focus:ring-1 focus:ring-blue-600" value ="{{Session::get('editContact')->contact_name}}"/>
@error('contact_name')
<div class="text-sm text-red-500">{{ $message }}</div>
@enderror
</div>
<div class="mt-2">
<label class="block" for="contact_company">Company<label>
<input type="text" placeholder="Contact Company" autocomplete="off" name="contact_company" value ="{{Session::get('editContact')->contact_company}}"
class="w-full px-4 py-2 mt-2 border rounded-md focus:outline-none focus:ring-1 focus:ring-blue-600">
@error('contact_company')
<div class="text-sm text-red-500">{{ $message }}</div>
@enderror
</div>
<div class="mt-2">
<label class="block" for="phone">Phone<label>
<input type="text" placeholder="Phone" autocomplete="off" name="contact_phone" value="{{Session::get('editContact')->contact_phone}}"
class="w-full px-4 py-2 mt-2 border rounded-md focus:outline-none focus:ring-1 focus:ring-blue-600">
@error('contact_phone')
<div class="text-sm text-red-500">{{ $message }}</div>
@enderror
</div>
<div class="mt-2">
<label class="block" for="contact_email">Contact Email<label>
<input type="text" placeholder="Contact Email" autocomplete="off" name="contact_email" value = "{{Session::get('editContact')->contact_email}}"
class="w-full px-4 py-2 mt-2 border rounded-md focus:outline-none focus:ring-1 focus:ring-blue-600">
@error('contact_email')
<div class="text-sm text-red-500">{{ $message }}</div>
@enderror
</div>
<input value="{{session('id');}}" name="user_id" hidden/>
<input value="{{Session::get('editContact')->id}}" name="id" hidden/>
<div class="flex items-baseline justify-between mt-4">
<a href="/home">
<span class="px-6 py-2 mt-4 text-white bg-gray-600 rounded-lg hover:bg-gray-900">Back</span>
</a>
<button type="submit" class="px-6 py-2 mt-4 text-white bg-yellow-600 rounded-lg hover:bg-yellow-900">Edit Contact</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
|
import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as actionCreators from '../../../actions/authActionCreators'
import css from './CharitySignup.scss'
class CharitySignup extends React.Component {
formSubmit(e) {
e.preventDefault()
const newCharityDetails = {
first_name: this.refs.first_name.value,
last_name: this.refs.last_name.value,
email: this.refs.email.value,
password: this.refs.password.value,
password_confirmation: this.refs.password_confirmation.value
}
this.props.charitySignup(newCharityDetails)
}
render() {
return (
<div className="charity-signup">
<form ref="signup-form" action="/" method="post" onSubmit={this.formSubmit.bind(this)}>
<div className="form-header">
<h2>Sign up</h2>
</div>
<div className="email-field-wrapper form-field">
<label htmlFor="email">Email</label>
<input ref="email" id="email" name="email" type="email" />
</div>
<div className="name-field-wrapper form-field">
<div>
<label htmlFor="first_name">First name</label>
<input ref="first_name" id="first_name" name="first_name" type="text" />
</div>
<div>
<label htmlFor="last_name">Last name</label>
<input ref="last_name" id="last_name" name="last_name" type="text" />
</div>
</div>
<div className="password-field-wrapper form-field">
<label htmlFor="password">Password</label>
<input ref="password" id="password" name="password" type="password" />
</div>
<div className="password-confirmation-field-wrapper form-field">
<label htmlFor="password_confirmation">Password confirmation</label>
<input ref="password_confirmation" id="password_confirmation" name="password_confirmation" type="password" />
</div>
<input type="submit" value="Sign up" />
<div className="extra-info">
Already have an account?
</div>
</form>
</div>
)
}
}
function mapStateToProps(state, router) {
return Object.assign({}, state.auth)
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(actionCreators, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(CharitySignup)
|
import { useState } from "react";
export default function Header() {
const [theme, setTheme] = useState("light");
function toggleTheme() {
const newTheme = theme === "light" ? "dark" : "light";
setTheme(newTheme);
const root = document.querySelector(":root");
const style = root.style;
if (newTheme === "light") {
style.setProperty("--element-background-color", "hsl(0, 0%, 100%)");
style.setProperty("--primary-background-color", "hsl(0, 0%, 95%)");
style.setProperty("--text-color", "hsl(200, 15%, 8%)");
} else {
style.setProperty("--element-background-color", "hsl(209, 23%, 22%)");
style.setProperty("--primary-background-color", "hsl(207, 26%, 17%)");
style.setProperty("--text-color", "hsl(0, 0%, 100%)");
}
}
return (
<header>
<nav>
<h2>Where in the world?</h2>
<div>
<i
className={theme === "light" ? "far fa-moon" : "far fa-sun"}
onClick={toggleTheme}
></i>
{theme === "light" ? <p>Dark Mode</p> : <p>Light Mode</p>}
</div>
</nav>
</header>
);
}
|
import { ExceptionMessage, HttpCode } from '~/common/enums/enums';
import { User as UserModel } from '~/data/models/models';
import { HttpError } from '~/exceptions/exceptions';
type Constructor = {
userCollection: UserModel[];
};
class User {
#userCollection: UserModel[];
constructor({ userCollection }: Constructor) {
this.#userCollection = userCollection;
}
async getById(id: string): Promise<UserModel> {
return this.getOne({ id });
}
async getOne(search: Partial<UserModel>): Promise<UserModel> {
const user = await this.findOne(search);
if (!user) {
throw new HttpError({
status: HttpCode.NOT_FOUND,
message: ExceptionMessage.USER_NOT_FOUND,
});
}
return user;
}
async findOne(search: Partial<UserModel>): Promise<UserModel | null> {
const user = this.#userCollection.find((user) => {
return Object.entries(search).every(
([key, value]) => user[key as keyof UserModel] === value,
);
});
return user ?? null;
}
async create(user: UserModel): Promise<UserModel> {
const { email } = user;
const lastUser = await this.findOne({
email,
});
if (lastUser) {
throw new HttpError({
status: HttpCode.BAD_REQUEST,
message: ExceptionMessage.USER_ALREADY_EXISTS,
});
}
this.#userCollection.push(user);
return user;
}
}
export { User };
|
import type { Driver } from "../driver";
export abstract class GenericDOMDriver<E extends Element> implements Driver<E, Text, E, Event> {
abstract createElement(type: string): E;
abstract createTextNode(text: string): Text;
placeEnd(parent: E) {
const $this = this;
return {
addText(text: string) {
const node = $this.createTextNode(text);
parent.appendChild(node);
return node;
},
addElement(type: string) {
const node = $this.createElement(type);
parent.appendChild(node);
return node;
},
ossify() {
return this;
},
};
}
placeBefore(element: E | Text) {
const $this = this;
const parent = element.parentElement;
if (!parent) {
throw new Error("Element has no parent");
}
return {
addText(text: string) {
const node = $this.createTextNode(text);
parent.insertBefore(node, element);
return node;
},
addElement(type: string) {
const node = $this.createElement(type);
parent.insertBefore(node, element);
return node;
},
ossify() {
const dummyNode = $this.createTextNode("");
parent.insertBefore(dummyNode, element);
return {
addText(text: string) {
const node = $this.createTextNode(text);
parent.insertBefore(node, dummyNode);
return node;
},
addElement(type: string) {
const node = $this.createElement(type);
parent.insertBefore(node, dummyNode);
return node;
},
ossify() {
return this;
},
};
},
};
}
remove(node: Text | E) {
node.remove();
}
updateText(text: Text, newText: string) {
text.data = newText;
}
abstract updateStyles(element: E, styles: Record<string, string>): void;
updateClasses(element: E, added: string[], removed: string[]) {
for (const className of added) {
element.classList.add(className);
}
for (const className of removed) {
element.classList.remove(className);
}
}
setAttribute(element: E, attr: string, value: string) {
element.setAttribute(attr, value);
}
removeAttribute(element: E, attr: string) {
element.removeAttribute(attr);
}
addListener(element: E, event: string, listener: (event: Event) => void) {
element.addEventListener(event, listener);
}
removeListener(element: E, event: string, listener: (event: Event) => void) {
element.removeEventListener(event, listener);
}
getNativeHandle(element: E) {
return element;
}
isText(node: Text | E): node is Text {
return node instanceof Text;
}
}
export class HTMLDOMDriver extends GenericDOMDriver<HTMLElement> {
createElement(type: string) {
return document.createElement(type);
}
createTextNode(text: string) {
return document.createTextNode(text);
}
updateStyles(element: HTMLElement, styles: Record<string, string>) {
for (const [key, value] of Object.entries(styles)) {
element.style.setProperty(key, value);
}
}
}
|
import os
import random
from pyfiglet import Figlet
from termcolor import colored
from ppieces.utils.validation import validate_project_name, validate_projects_folder_path
SCRIPTS_DIR = "scripts"
TEMPLATES_DIR = "templates"
PROJECTS_DIR = "/Users/dvitto/projects"
def welcome():
os.system("clear")
# isometric1, chunky, poison, cybermedium
font = random.choice(["lean", "cyberlarge", "alligator", "larry3d", "trek"])
fig = Figlet(font=font)
print()
print(colored(fig.renderText(" ppieces"), "cyan"))
welcome_text = colored(
("\nWelcome to ppieces, a python project initializer!\n"),
"red",
attrs=["bold"],
)
print(welcome_text)
print("-" * len(welcome_text))
def bye():
msg: str = colored("\nAll set! Happy coding!\n", "green", attrs=["bold"])
print(msg)
def ask_user(question):
valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
prompt = " [Y/n] "
default = "yes"
while True:
print(colored(f"{question}{prompt}", "cyan", attrs=["bold"]), end="")
choice = input().lower()
if choice == "":
return valid[default]
elif choice in valid:
return valid[choice]
else:
msg = colored(
("Please respond with 'yes' or 'no' (or 'y' or 'n')."),
"red",
attrs=["bold"],
)
print(msg)
def get_project_path():
default_projects_folder_path = os.path.join(os.getenv("HOME"), "projects")
projects_folder_path = input(
colored(
"Enter the absolute path of your projects folder (default: "
f"{default_projects_folder_path}): ",
"cyan",
attrs=["bold"],
)
)
if not projects_folder_path:
projects_folder_path = default_projects_folder_path
validate_projects_folder_path(projects_folder_path)
project_name = input(
colored("Enter the name of your new project: ", "cyan", attrs=["bold"])
)
validate_project_name(project_name)
return os.path.join(projects_folder_path, project_name)
|
#include <math.h>
class Motor {
public:
float x, y, z;
int pin;
float multiplier;
Motor(float x, float y, float z, float multiplier, int pin) {
this->x = x;
this->y = y;
this->z = z;
this->pin = pin;
this->multiplier = multiplier;
}
float calcDistance(float posx, float posy, float posz) {
float distance = sqrt(pow(posx - x, 2) + pow(posy - y, 2) + pow(posz - z, 2));
return distance;
}
void setIntensity(float posx, float posy, float posz, float nextmotorX, float nextmotorY, float nextmotorZ) {
float distance = calcDistance(posx, posy, posz);
float d = calcDistance(nextmotorX, nextmotorY, nextmotorZ);
int intensity = (255 / d) * (d - distance) * (this->multiplier);
analogWrite(pin, intensity);
delay(10);
}
};
Motor motor1(0.0, 0.0, 0.0, 1.0, 3);
Motor motor2(0.0, 0.0, 1.0, 1.0, 5);
Motor motor3(0.0, 0.0, 2.0, 1.0, 6);
Motor motor4(0.0, 0.0, 3.0, 1.0, 9);
Motor motor5(0.0, 0.0, 4.0, 1.0, 10);
Motor motor6(0.0, 0.0, 5.0, 1.0, 11); // The new Motor object
void setup() {
Serial.begin(230400);
}
void loop() {
if (Serial.available() > 0) {
String inputString = Serial.readStringUntil('\n');
float dist = inputString.toFloat();
float disttmp = 0.0;
if (dist > 0 && dist < 1) {
disttmp = 0;
motor1.setIntensity(0.0, 0.0, dist - disttmp, 0.0, 0.0, 1.0);
motor2.setIntensity(0.0, 0.0, dist - disttmp, 0.0, 0.0, 2.0);
analogWrite(motor3.pin, 0);
analogWrite(motor4.pin, 0);
analogWrite(motor5.pin, 0);
analogWrite(motor6.pin, 0); // added for motor6
}
else if (dist > 1 && dist < 2) {
disttmp = 0;
analogWrite(motor1.pin, 0);
motor2.setIntensity(0.0, 0.0, dist - disttmp, 0.0, 0.0, 2.0);
motor3.setIntensity(0.0, 0.0, dist - disttmp, 0.0, 0.0, 3.0);
analogWrite(motor4.pin, 0);
analogWrite(motor5.pin, 0);
analogWrite(motor6.pin, 0); // added for motor6
}
else if (dist > 2 && dist < 3) {
disttmp = 0;
analogWrite(motor1.pin, 0);
analogWrite(motor2.pin, 0);
motor3.setIntensity(0.0, 0.0, dist - disttmp, 0.0, 0.0, 3.0);
motor4.setIntensity(0.0, 0.0, dist - disttmp, 0.0, 0.0, 4.0);
analogWrite(motor5.pin, 0);
analogWrite(motor6.pin, 0); // added for motor6
}
else if (dist > 3 && dist < 4) {
disttmp = 0;
analogWrite(motor1.pin, 0);
analogWrite(motor2.pin, 0);
analogWrite(motor3.pin, 0);
motor4.setIntensity(0.0, 0.0, dist - disttmp, 0.0, 0.0, 4.0);
motor5.setIntensity(0.0, 0.0, dist - disttmp, 0.0, 0.0, 5.0); // Change to 5.0 from 3.0
analogWrite(motor6.pin, 0); // added for motor6
}
else if (dist > 4 && dist < 5) { // added a new condition for motor6
disttmp = 0;
analogWrite(motor1.pin, 0);
analogWrite(motor2.pin, 0);
analogWrite(motor3.pin, 0);
analogWrite(motor4.pin, 0);
motor5.setIntensity(0.0, 0.0, dist - disttmp, 0.0, 0.0, 5.0);
motor6.setIntensity(0.0, 0.0, dist - disttmp, 0.0, 0.0, 6.0); // Added for motor6
}
else if (dist == 0 || dist == 1 || dist == 2 || dist == 3 || dist == 4 || dist == 5) {
analogWrite(motor1.pin, (dist == 0)*255);
analogWrite(motor2.pin, (dist == 1)*255);
analogWrite(motor3.pin, (dist == 2)*255);
analogWrite(motor4.pin, (dist == 3)*255);
analogWrite(motor5.pin, (dist == 4)*255);
analogWrite(motor6.pin, (dist == 5)*255); // added for motor6
}
else {
analogWrite(motor1.pin, 0);
analogWrite(motor2.pin, 0);
analogWrite(motor3.pin, 0);
analogWrite(motor4.pin, 0);
analogWrite(motor5.pin, 0);
analogWrite(motor6.pin, 0); // added for motor6
}
}
Serial.flush();
}
|
import { TeamStatusValue } from "./Interfaces";
export default class TeamStatus {
private status: TeamStatusValue = 'NEW';
constructor(rawApiStatus?: string) {
rawApiStatus = rawApiStatus !== undefined ? rawApiStatus : 'New';
const statusLookup = {
'New': 'NEW', // Newly created, not yet submitted. Full edit capability
'Active': 'ACTIVE', // Ready to Play. Shouldn't be able to do things that affect CTV or on-pitch effects. Should still allow reordering of the players and things like icons / genders of players.
'Waiting for Opponent': 'WAITING_FOR_OPPONENT', // Tournament state, there is a tournament match coming up. Should work much like Active
'Skill Rolls Pending': 'SKILL_ROLLS_PENDING', // A state for teams where skill selection must be made. For 2016, this is just reaching the threshold. For 2020, it's reaching the stat SPP.
'Post Match Sequence': 'POST_MATCH_SEQUENCE', // Post-match. Should allow buying new players (assuming treasury is available)
'Re-Drafting': 'REDRAFTING', // Re-drafting state, editing as per redrafting rules.
'Retired': 'RETIRED', // Retired team, no changes allowed (except for staff who can unretire, rename etc)
'Pending Approval': 'PENDING_APPROVAL', // This is a state for teams that have been reported for violating the naming rules. Should be essentially locked until staff has reviewed (except for staff, who need access to the team)
'Blocked': 'BLOCKED', // I don't remember fully what this does
};
this.status = statusLookup[rawApiStatus];
}
public getStatus() {
return this.status;
}
public isNew(): boolean {
return this.status === 'NEW';
}
public isActive(): boolean {
return ['ACTIVE', 'WAITING_FOR_OPPONENT'].includes(this.status);
}
public isRetired(): boolean {
return this.status === 'RETIRED';
}
public isPostMatch(): boolean {
return this.status === 'POST_MATCH_SEQUENCE';
}
}
|
package com.lpoo.snake.Model;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class SingleplayerLevel implements Level {
private Element apple;
private BigApple bigApple;
private Snake snake;
private Obstacle obstacle;
private final int snakeSize = 6;
private int wallSize;
private List<Element> elements;
private List<Wall> walls;
private List<Obstacle> obstacles;
private int width;
private int height;
public SingleplayerLevel(int width, int height, int wallSize) {
this.width = width;
this.height = height;
this.wallSize = wallSize;
elements = new ArrayList<>();
obstacles = new ArrayList<>();
buildElements();
}
public Snake getSnake() {
return snake;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public List<Wall> getWalls() {
return walls;
}
public BigApple getBigApple() {
return bigApple;
}
public Element getApple() {
return apple;
}
private void buildElements() {
snake = ElementFactory.getSnakeRandom(width, height, snakeSize, wallSize);
elements.add(snake);
apple = ElementFactory.getElementRandom("Element", wallSize, width, height);
elements.add(apple);
bigApple = (BigApple) ElementFactory.getElement("BigApple", new Position(15, 15));
elements.add(bigApple);
walls = ElementFactory.getWalls(width, height, wallSize);
elements.addAll(walls);
obstacle = (Obstacle) ElementFactory.getElementRandom("Obstacle", wallSize, width, height);
obstacles.add(obstacle);
}
public boolean checkCollision() throws IOException {
// Snake head colission with self or bounds
if (snake.hasEatenSelf() || snake.outOfBounds(width, height, wallSize))
return true;
// Snake collision with apple
if (Element.collision(snake, apple)) {
snake.grow(20);
apple.setPosition(Position.getRandomPosition(wallSize, width, height));
}
// Snake collision with big apple
if (Element.collision(snake, bigApple) && bigApple.getTimeForEnd() > 0) {
bigApple.setActive(false);
bigApple.setTimeForEnd(-1);
snake.grow(40);
}
// Snake collision with obstacles
for (Obstacle obstacle : obstacles) {
/* test if snake collide with any part of the snake */
if (obstacle.isActive()
&& (Element.collision(snake, obstacle) || Element.collision(obstacle, snake.tail()))) {
return true;
}
}
return false;
}
public void update() {
snake.update();
}
public void addObstacle() {
obstacles.add((Obstacle) ElementFactory.getElementRandom("Obstacle", wallSize, width, height));
}
public void spawnBigApple() {
bigApple.setActive(true);
bigApple.setPosition(Position.getRandomPosition(wallSize, width, height));
bigApple.setTimeForEnd(20);
}
public List<Obstacle> getObstacles() {
return obstacles;
}
public Obstacle getLast() {
return obstacles.get(obstacles.size() - 1);
}
}
|
//=== MLModelRunner/C/ONNXModelRunner.cpp - C API for ONNXModelRunner -----===//
//
// Part of the MLCompilerBridge Project, under the Apache License v2.0 with LLVM
// Exceptions. See the LICENSE file for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file defines the C APIs for ONNXModelRunner.
///
//===----------------------------------------------------------------------===//
#include "MLModelRunner/C/ONNXModelRunner.h"
#include "MLModelRunner/ONNXModelRunner/agent.h"
#include "MLModelRunner/ONNXModelRunner/utils.h"
#include "MLModelRunner/Utils/Debug.h"
#include "llvm/ADT/SmallVector.h"
#include <cassert>
#include <iostream>
#include <map>
#include <stdarg.h>
#include <vector>
using namespace MLBridge;
struct ONNXModelRunner {
Environment *env;
Agent *agent;
std::map<std::string, Agent *> agents;
ONNXModelRunner(Environment *env, std::map<std::string, Agent *> &&agents)
: env(env), agents(agents) {}
ONNXModelRunner(Agent *agent) : agent(agent) {}
};
struct Environment {
private:
// Function pointer to the step and reset functions
float *(*stepFunc)(Action action);
float *(*resetFunc)();
int numFeatures;
std::string nextAgent;
bool done;
public:
Environment() : stepFunc(nullptr), resetFunc(nullptr) {}
// EnvironmentImpl(float *(*stepFunc)(Action action), float *(*resetFunc)())
// : stepFunc(stepFunc), resetFunc(resetFunc) {}
void setNumFeatures(int numFeatures) { this->numFeatures = numFeatures; }
void setStepFunc(float *(*stepFunc)(Action action)) {
this->stepFunc = stepFunc;
}
void setResetFunc(float *(*resetFunc)()) { this->resetFunc = resetFunc; }
void setNextAgent(char *agentName) { nextAgent = agentName; }
std::string getNextAgent() { return nextAgent; }
Observation step(Action action) {
assert(stepFunc != nullptr &&
"Step function is null! Define step function on env");
float *stepRes = stepFunc(action);
return llvm::SmallVector<float, 100>(stepRes, stepRes + numFeatures);
}
Observation reset() {
assert(resetFunc != nullptr &&
"Reset function is null! Define reset function on env");
float *resetRes = resetFunc();
return llvm::SmallVector<float, 100>(resetRes, resetRes + numFeatures);
}
bool checkDone() { return done; }
void setDone() { done = true; }
void resetDone() { done = false; }
};
Environment *createEnvironment() { return new Environment(); }
void env_setDone(Environment *env) { env->setDone(); }
void env_resetDone(Environment *env) { env->resetDone(); }
bool env_checkDone(Environment *env) { return env->checkDone(); }
void env_setNumFeatures(Environment *env, int numFeatures) {
env->setNumFeatures(numFeatures);
}
void env_setStepFunc(Environment *env, float *(*stepFunc)(Action action)) {
env->setStepFunc(stepFunc);
}
void env_setResetFunc(Environment *env, float *(*resetFunc)()) {
env->setResetFunc(resetFunc);
}
void env_setNextAgent(Environment *env, char *agentName) {
env->setNextAgent(agentName);
}
ONNXModelRunner *createONNXModelRunner(Environment *env, int numAgents, ...) {
assert(env != nullptr && "Environment is null!");
va_list args;
va_start(args, numAgents);
std::map<std::string, Agent *> agents;
for (int i = 0; i < numAgents; i += 2) {
char *agentName = va_arg(args, char *);
char *agentPath = va_arg(args, char *);
agents[agentName] = new Agent(agentPath);
}
va_end(args);
ONNXModelRunner *obj = new ONNXModelRunner(env, std::move(agents));
return obj;
}
ONNXModelRunner *createSingleAgentOMR(char *agent_path) {
Agent *agent = new Agent(agent_path);
ONNXModelRunner *obj = new ONNXModelRunner(agent);
return obj;
}
void evaluate(ONNXModelRunner *omr) {
auto x = omr->env->reset();
while (true) {
Action action;
// current agent
// auto current_agent = omr->agents[omr->env->getNextAgent()];
Agent *current_agent = omr->agent;
action = current_agent->computeAction(x);
MLBRIDGE_DEBUG(std::cout << "Action: " << action << "\n");
x = omr->env->step(action);
if (omr->env->checkDone()) {
MLBRIDGE_DEBUG(std::cout << "Done🎉\n");
break;
}
}
}
int singleAgentEvaluate(ONNXModelRunner *obj, float *inp, int inp_size) {
Observation obs(inp, inp + inp_size);
Action action = obj->agent->computeAction(obs);
MLBRIDGE_DEBUG(std::cout << "action :: " << action << "\n");
return action;
}
void destroyEnvironment(Environment *env) { delete env; }
void destroyONNXModelRunner(ONNXModelRunner *omr) { delete omr; }
|
import numpy as np
def rand_fixed_sum(tasks_per_task_set: int, utilization_level: float, number_of_task_sets: int):
"""
Copyright 2010 Paul Emberson, Roger Stafford, Robert Davis.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Paul Emberson, Roger Stafford or
Robert Davis.
Includes Python implementation of Roger Stafford's randfixedsum implementation
http://www.mathworks.com/matlabcentral/fileexchange/9700
Adapted specifically for the purpose of taskset generation with fixed
total utilisation value
Please contact paule@rapitasystems.com or robdavis@cs.york.ac.uk if you have
any questions regarding this software.
"""
n = tasks_per_task_set
u = utilization_level
nsets = number_of_task_sets
if n < u:
return None
# deal with n=1 case
if n == 1:
return np.tile(np.array([u]), [nsets, 1])
k = min(int(u), n - 1)
s = u
s1 = s - np.arange(k, k - n, -1.)
s2 = np.arange(k + n, k, -1.) - s
tiny = np.finfo(float).tiny
huge = np.finfo(float).max
w = np.zeros((n, n + 1))
w[0, 1] = huge
t = np.zeros((n - 1, n))
for i in np.arange(2, n + 1):
tmp1 = w[i - 2, np.arange(1, i + 1)] * s1[np.arange(0, i)] / float(i)
tmp2 = w[i - 2, np.arange(0, i)] * s2[np.arange(n - i, n)] / float(i)
w[i - 1, np.arange(1, i + 1)] = tmp1 + tmp2
tmp3 = w[i - 1, np.arange(1, i + 1)] + tiny
tmp4 = s2[np.arange(n - i, n)] > s1[np.arange(0, i)]
t[i - 2, np.arange(0, i)] = (tmp2 / tmp3) * tmp4 + \
(1 - tmp1 / tmp3) * (np.logical_not(tmp4))
x = np.zeros((n, nsets))
rt = np.random.uniform(size=(n - 1, nsets)) # rand simplex type
rs = np.random.uniform(size=(n - 1, nsets)) # rand position in simplex
s = np.repeat(s, nsets)
j = np.repeat(k + 1, nsets)
sm = np.repeat(0, nsets)
pr = np.repeat(1, nsets)
for i in np.arange(n - 1, 0, -1): # iterate through dimensions
# decide which direction to move in this dimension (1 or 0):
e = rt[(n - i) - 1, ...] <= t[i - 1, j - 1]
sx = rs[(n - i) - 1, ...] ** (1.0 / i) # next simplex coord
sm = sm + (1.0 - sx) * pr * s / (i + 1)
pr = sx * pr
x[(n - i) - 1, ...] = sm + pr * e
s = s - e
j = j - e # change transition table column if required
x[n - 1, ...] = sm + pr * s
# iterated in fixed dimension order but needs to be randomised
# permute x row order within each column
for i in range(0, nsets):
x[..., i] = x[np.random.permutation(n), i]
return x.T.tolist()
|
import { PrismaClient, User } from '@prisma/client'
interface Payload {
email: string,
firstName: string,
lastName: string,
}
export default async function upsertUserById(id: number, payload: Payload) {
return new Promise<User>(async (resolve, reject) => {
try {
const prisma: PrismaClient = new PrismaClient();
const upsertedUser: User = await prisma.user.upsert({
where: {
id
},
// *-- En caso de que no exista.
create: {
email: payload.email,
firstName: payload.firstName,
lastName: payload.lastName
},
// *-- En caso de que exista.
update: {
...payload
}
})
console.info(`[🦐] Usuario actualizado o creado correctamente...`)
console.info(upsertedUser);
console.info(`---------`)
return resolve(upsertedUser);
} catch (err) {
return reject();
}
})
}
|
---
layout: bootstrap
title: "Assignment 7: 2D Scalar Field Visualization"
---
# Assignment 7
- Posting date: Nov 1st
- Due date: Nov 8th
- GitHub [classroom link](https://classroom.github.com/a/v8Oi8l-s)
# Description
In this assignment, you will implement **Marching Squares**, one
algorithm for generating contours of a 2D scalar field. We will use
the same data as in [assignment 4](../assignment_4/), the dataset
with temperature and pressure measurements for a simulation of
Hurricane Isabel. As usual, you will build on skeleton code we
provide.
# Data
The data is provided in two arrays: `temperatureCells` and
`pressureCells`. Each array contains objects that look like this:
{
NW: value-at-nw-corner,
NE: value-at-ne-corner,
SW: value-at-sw-corner,
SE: value-at-se-corner,
Row: i,
Col: j
}
## Part 1: Implement the computation of outlines contours (50 points)
Implement the computation of **outline contours** using marching squares
by filling out the skeleton code, specifically the function
`generateOutlineContour`. As in assignment 4, each square is 10x10
pixels.
The solution will look like this:

## Part 2: Implement the computation of filled contours (50 points)
Implement the computation of **filled contours** using marching
squares by filling out the skeleton code, specifically the functions
`generateFilledContour` and `includesFilledContour`. As in assignment
4, each square is 10x10 pixels.
The solution will look somewhat like this:

# Files
- [main.js](files/main.js) is the skeleton you will build on
(implement the functions commented with "write this"),
- [index.html](files/index.html) has the HTML you'll need, and
- [data.js](files/data.js) has the data you will use. **Note
that this is a different file from assignment 4, because
the data is structured differently**.
|
<?php
namespace RT\Newsfit\Custom;
use RT\Newsfit\Helpers\Fns;
use RT\Newsfit\Options\Opt;
use RT\Newsfit\Traits\SingletonTraits;
class DynamicStyles {
use SingletonTraits;
protected $meta_data;
public function __construct() {
add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_scripts' ], 20 );
}
public function enqueue_scripts() {
$this->meta_data = get_post_meta( get_the_ID(), 'rt_layout_meta_data', true );
$dynamic_css = $this->inline_style();
wp_register_style( 'newsfit-dynamic', false, 'newsfit-main' );
wp_enqueue_style( 'newsfit-dynamic' );
wp_add_inline_style( 'newsfit-dynamic', $this->minify_css( $dynamic_css ) );
}
function minify_css( $css ) {
$css = preg_replace( '/\/\*[^*]*\*+([^\/][^*]*\*+)*\//', '', $css ); // Remove comments
$css = preg_replace( '/\s+/', ' ', $css ); // Remove multiple spaces
$css = preg_replace( '/\s*([\{\};])\s*/', '$1', $css ); // Remove spaces around { } ; : ,
return $css;
}
private function inline_style() {
$primary_color = newsfit_option( 'rt_primary_color', '#007BFF' );
$primary_dark_color = newsfit_option( 'rt_primary_dark_color', '#0273EC' );
$primary_light_color = newsfit_option( 'rt_primary_light_color', '#479DFA' );
$secondary_color = newsfit_option( 'rt_secondary_color', '#131619' );
$body_color = newsfit_option( 'rt_body_color', '#3D3E41' );
$title_color = newsfit_option( 'rt_title_color', '#161D25' );
$meta_color = newsfit_option( 'rt_meta_color', '#808993' );
$meta_light = newsfit_option( 'rt_meta_light', '#F2F8FF' );
$gray20 = newsfit_option( 'rt_gray20_color', '#E6E6E6' );
$gray40 = newsfit_option( 'rt_gray40_color', '#D0D0D0' );
$rt_container_width = newsfit_option( 'rt_container_width', '1240' );
ob_start(); ?>
:root {
--rt-primary-color: <?php echo esc_attr( $primary_color ); ?>;
--rt-primary-dark: <?php echo esc_attr( $primary_dark_color ); ?>;
--rt-primary-light: <?php echo esc_attr( $primary_light_color ); ?>;
--rt-secondary-color: <?php echo esc_attr( $secondary_color ); ?>;
--rt-body-color: <?php echo esc_attr( $body_color ); ?>;
--rt-title-color: <?php echo esc_attr( $title_color ); ?>;
--rt-meta-color: <?php echo esc_attr( $meta_color ); ?>;
--rt-meta-light: <?php echo esc_attr( $meta_light ); ?>;
--rt-gray20: <?php echo esc_attr( $gray20 ); ?>;
--rt-gray40: <?php echo esc_attr( $gray40 ); ?>;
--rt-body-rgb: <?php echo esc_attr( Fns::hex2rgb( $body_color ) ); ?>;
--rt-title-rgb: <?php echo esc_attr( Fns::hex2rgb( $title_color ) ); ?>;
--rt-primary-rgb: <?php echo esc_attr( Fns::hex2rgb( $primary_color ) ); ?>;
--rt-secondary-rgb: <?php echo esc_attr( Fns::hex2rgb( $secondary_color ) ); ?>;
--rt-container-width: <?php echo esc_attr( $rt_container_width . 'px' ); ?>;
}
body {
color: <?php echo esc_attr( $body_color ); ?>;
}
<?php
$this->site_fonts();
$this->topbar_css();
$this->header_css();
$this->breadcrumb_css();
$this->content_padding_css();
$this->footer_css();
return ob_get_clean();
}
/**
* Topbar Settings
*
* @return void
*/
protected function topbar_css() {
$_topbar_active_color = newsfit_option( 'rt_topbar_active_color' );
echo self::css( 'body .site-header .newsfit-topbar .topbar-container *:not(.dropdown-menu *)', 'color', 'rt_topbar_color' );
echo self::css( 'body .site-header .newsfit-topbar .topbar-container svg:not(.dropdown-menu svg)', 'fill', 'rt_topbar_color', ' !important' );
if ( ! empty( $_topbar_active_color ) ) :
?>
body .site-header .newsfit-topbar .topbar-container a:hover:not(.dropdown-menu a:hover),
body .newsfit-topbar #topbar-menu ul ul li.current_page_item > a,
body .newsfit-topbar #topbar-menu ul ul li.current-menu-ancestor > a,
body .newsfit-topbar #topbar-menu ul.newsfit-topbar-menu > li.current-menu-item > a,
body .newsfit-topbar #topbar-menu ul.newsfit-topbar-menu > li.current-menu-ancestor > a {
color: <?php echo esc_attr( $_topbar_active_color ); ?> !important;
}
body .site-header .newsfit-topbar .topbar-container a:hover:not(.dropdown-menu a:hover svg) svg,
body .newsfit-topbar #topbar-menu ul ul li.current-menu-ancestor > a svg,
body .newsfit-topbar #topbar-menu ul.newsfit-topbar-menu > li.current-menu-item > a svg,
body .newsfit-topbar #topbar-menu ul.newsfit-topbar-menu > li.current-menu-ancestor > a svg {
fill: <?php echo esc_attr( $_topbar_active_color ); ?> !important;
}
<?php endif; ?>
<?php
echo self::css( 'body .newsfit-topbar', 'background-color', 'rt_topbar_bg_color' );
}
/**
* Menu Color Settings
*
* @return void
*/
protected function header_css() {
// Logo CSS
$logo_width = '';
$logo_dimension = newsfit_option( 'rt_logo_width_height' );
$menu_border_bottom = newsfit_option( 'rt_menu_border_color' );
if ( strpos( $logo_dimension, ',' ) ) {
$logo_width = explode( ',', $logo_dimension );
}
// Default Menu
$_menu_color = newsfit_option( 'rt_menu_color' );
$_menu_active_color = newsfit_option( 'rt_menu_active_color' );
$_menu_bg_color = newsfit_option( 'rt_menu_bg_color' );
// Transparent Menu
$_tr_menu_color = newsfit_option( 'rt_tr_menu_color' );
$_tr_menu_active_color = newsfit_option( 'rt_tr_menu_active_color' );
$_topbar_border = newsfit_option( 'rt_topbar_border' );
$_header_border = newsfit_option( 'rt_header_border' );
$_breadcrumb_border = newsfit_option( 'rt_breadcrumb_border' );
?>
<?php // Header Logo CSS ?>
<?php
if ( 'full-width' == Opt::$header_width ) :
$header_width = newsfit_option( 'rt_header_max_width' );
$h_width = $header_width > 992 ? $header_width . 'px' : '100%';
?>
.header-container, .topbar-container {width: <?php echo esc_attr( $h_width ); ?>;max-width: 100%;}
<?php endif; ?>
<?php if ( ! empty( $logo_width ) ) : ?>
.site-header .site-branding img {
width: <?php echo esc_attr( $logo_width[0] ?? '100%' ); ?>;
height: <?php echo esc_attr( $logo_width[1] ?? 'auto' ); ?>;
object-fit: contain;
}
<?php endif; ?>
<?php // Default Header ?>
<?php if ( ! empty( $_menu_color ) ) : ?>
body .main-header-section .newsfit-navigation ul li a {color: <?php echo esc_attr( $_menu_color ); ?>;}
body .main-header-section svg {fill: <?php echo esc_attr( $_menu_color ); ?>;}
body .main-header-section .menu-icon-wrapper .menu-bar span,
body .menu-icon-wrapper .has-separator li:not(:last-child):after {background-color: <?php echo esc_attr( $_menu_color ); ?>;}
<?php endif; ?>
<?php if ( ! empty( $_menu_active_color ) ) : ?>
body .main-header-section .newsfit-navigation ul li a:hover,
body .main-header-section .newsfit-navigation ul li.current-menu-item > a,
body .main-header-section .newsfit-navigation ul li.current-menu-ancestor > a {color: <?php echo esc_attr( $_menu_active_color ); ?>;}
body .main-header-section .newsfit-navigation ul li.current-menu-item > a svg,body .main-header-section .newsfit-navigation ul li.current-menu-ancestor > a svg {fill: <?php echo esc_attr( $_menu_active_color ); ?>;}
body .main-header-section .menu-icon-wrapper .menu-bar:hover span {background-color: <?php echo esc_attr( $_menu_active_color ); ?>;}
body .main-header-section a:hover [class*=rticon] svg {fill: <?php echo esc_attr( $_menu_active_color ); ?>;}
<?php endif; ?>
<?php if ( ! empty( $_menu_bg_color ) ) : ?>
body .main-header-section {background-color: <?php echo esc_attr( $_menu_bg_color ); ?>;}
<?php endif; ?>
<?php // Transparent Header ?>
<?php if ( ! empty( $_tr_menu_color ) ) : ?>
body.has-trheader .site-header .site-branding h1 a,
body.has-trheader .site-header .newsfit-navigation *,
body.has-trheader .site-header .newsfit-navigation ul li a {
color: <?php echo esc_attr( $_tr_menu_color ); ?>;
}
body.has-trheader .site-header .menu-bar span,
body.has-trheader .menu-icon-wrapper .has-separator li:not(:last-child):after {
background-color: <?php echo esc_attr( $_tr_menu_color ); ?> !important;
}
body.has-trheader .site-header .menu-icon-wrapper svg,
body.has-trheader .site-header .newsfit-topbar .caret svg,
body.has-trheader .site-header .main-header-section .caret svg {
fill: <?php echo esc_attr( $_tr_menu_color ); ?>
}
<?php endif; ?>
<?php if ( ! empty( $_tr_menu_active_color ) ) : ?>
body.has-trheader .site-header .newsfit-navigation ul li a:hover,
body.has-trheader .site-header .newsfit-navigation ul li.current-menu-item > a,
body.has-trheader .site-header .newsfit-navigation ul li.current-menu-ancestor > a {
color: <?php echo esc_attr( $_tr_menu_active_color ); ?>
}
body.has-trheader .main-header-section .menu-icon-wrapper .menu-bar:hover span {
background-color: <?php echo esc_attr( $_tr_menu_active_color ); ?> !important;
}
body.has-trheader .main-header-section a:hover [class*=rticon] svg,
body.has-trheader .site-header .newsfit-navigation ul li.current-menu-ancestor > a svg,
body.has-trheader .site-header .newsfit-navigation ul li.current-menu-item > a svg {
fill: <?php echo esc_attr( $_tr_menu_active_color ); ?>
}
<?php endif; ?>
<?php if ( ! empty( $menu_border_bottom ) ) : ?>
body .newsfit-topbar,
body .main-header-section,
body .newsfit-breadcrumb-wrapper {
border-bottom-color: <?php echo esc_attr( $menu_border_bottom ); ?>;
}
<?php endif; ?>
<?php if ( ! $_topbar_border ) : ?>
body .newsfit-topbar {border-bottom: none;}
<?php endif; ?>
<?php if ( ! $_header_border ) : ?>
body .main-header-section {border-bottom: none;}
<?php endif; ?>
<?php if ( ! $_breadcrumb_border ) : ?>
body .newsfit-breadcrumb-wrapper {border-bottom: none;}
<?php endif; ?>
<?php
}
/**
* Breadcrumb Settings
*
* @return void
*/
protected function breadcrumb_css() {
$banner_bg = newsfit_option( 'rt_banner_bg' );
$banner_overlay = newsfit_option( 'rt_banner_overlay' );
$breadcrumb_color = newsfit_option( 'rt_breadcrumb_color' );
$breadcrumb_active = newsfit_option( 'rt_breadcrumb_active' );
?>
<?php if ( ! empty( $banner_bg ) ) : ?>
body .newsfit-breadcrumb-wrapper {background-color: <?php echo esc_attr( $banner_bg ); ?>;}
<?php endif ?>
<?php if ( ! empty( $banner_overlay ) ) : ?>
body .newsfit-breadcrumb-wrapper.has-bg::before {background-color: <?php echo esc_attr( $banner_overlay ); ?>;}
<?php endif; ?>
<?php if ( ! empty( $breadcrumb_color ) ) : ?>
body .newsfit-breadcrumb-wrapper .breadcrumb a {color: <?php echo esc_attr( $breadcrumb_color ); ?>;}
body .newsfit-breadcrumb-wrapper .breadcrumb li::after {border-color: <?php echo esc_attr( $breadcrumb_color ); ?>;}
<?php endif; ?>
<?php if ( ! empty( $breadcrumb_active ) ) : ?>
body .newsfit-breadcrumb-wrapper .breadcrumb li.active {color: <?php echo esc_attr( $breadcrumb_active ); ?>;}
<?php
endif;
}
/**
* Content Padding
*
* @return void
*/
protected function content_padding_css() {
$content_padding_top = $this->meta_data['rt_padding_top'] ?? '';
$content_padding_bottom = $this->meta_data['rt_padding_bottom'] ?? '';
if ( ! ( $content_padding_top || $content_padding_bottom ) ) {
return;
}
$class = 'body .site-content';
if ( Opt::$has_banner ) {
$class = 'body.has-banner .site-content .newsfit-breadcrumb-wrapper + div';
}
?>
<?php echo esc_attr( $class ); ?> {
<?php if ( $content_padding_top ) : ?>
padding-top: <?php echo esc_attr( $content_padding_top ); ?>px;
<?php endif; ?>
<?php if ( $content_padding_bottom ) : ?>
padding-bottom: <?php echo esc_attr( $content_padding_bottom ); ?>px;
<?php endif; ?>
}
<?php
}
/**
* Footer CSS
*
* @return void
*/
protected function footer_css() {
if ( newsfit_option( 'rt_footer_width' ) && newsfit_option( 'rt_footer_max_width' ) > 1400 ) {
echo self::css( '.site-footer .footer-container', 'width', 'rt_footer_max_width', 'px;max-width: 100%' );
}
echo self::css( 'body .site-footer *:not(a)', 'color', 'rt_footer_text_color' );
echo self::css( 'body .site-footer a', 'color', 'rt_footer_link_color' );
echo self::css( 'body .site-footer a:hover', 'color', 'rt_footer_link_hover_color' );
echo self::css( 'body .site-footer, body .site-footer select option', 'background-color', 'rt_footer_bg' );
echo self::css( '.site-footer .widget :is(td, th, select, .search-box)', 'border-color', 'rt_footer_input_border_color' );
echo self::css( 'body .site-footer .widget-title', 'color', 'rt_footer_widget_title_color' );
echo self::css( 'body .site-footer .footer-copyright-wrapper', 'color', 'rt_copyright_text_color' );
echo self::css( 'body .site-footer .footer-copyright-wrapper a', 'color', 'rt_copyright_link_color' );
echo self::css( 'body .site-footer .footer-copyright-wrapper a:hover', 'color', 'rt_copyright_link_hover_color' );
echo self::css( 'body .site-footer .footer-copyright-wrapper', 'background-color', 'rt_copyright_bg' );
}
/**
* Load site fonts
*
* @return void
*/
protected function site_fonts() {
$typo_body = json_decode( newsfit_option( 'rt_body_typo' ), true );
$typo_menu = json_decode( newsfit_option( 'rt_menu_typo' ), true );
$typo_heading = json_decode( newsfit_option( 'rt_all_heading_typo' ), true );
$body_font_family = $typo_body['font'] ?? 'IBM Plex Sans';
$heading_font_family = $typo_heading['font'] ?? $body_font_family;
?>
:root{
--rt-body-font: '<?php echo esc_html( $typo_body['font'] ); ?>', sans-serif;;
--rt-heading-font: '<?php echo esc_html( $heading_font_family ); ?>', sans-serif;
--rt-menu-font: '<?php echo esc_html( $typo_body['font'] ); ?>', sans-serif;
}
<?php
echo self::font_css( 'body', $typo_body );
echo self::font_css( '.site-header', [ 'font' => $typo_menu['font'] ] );
echo self::font_css(
'.main-header-section .newsfit-navigation ul li a',
[
'lineheight' => $typo_menu['lineheight'],
'regularweight' => $typo_menu['regularweight'],
]
);
echo self::font_css(
'.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6',
[
'font' => $typo_heading['font'],
'regularweight' => $typo_heading['regularweight'],
]
);
$heading_fonts = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ];
foreach ( $heading_fonts as $heading ) {
$font = json_decode( newsfit_option( "rt_heading_{$heading}_typo" ), true );
if ( ! empty( $font['font'] ) ) {
$selector = "$heading, .$heading";
echo self::font_css( $selector, $font );
}
}
}
/**
* Generate CSS
*
* @param $selector
* @param $property
* @param $theme_mod
*
* @return string|void
*/
public static function css( $selector, $property, $theme_mod, $after_css = '' ) {
$theme_mod = newsfit_option( $theme_mod );
if ( ! empty( $theme_mod ) ) {
return sprintf( '%s { %s:%s%s; }', $selector, $property, $theme_mod, $after_css );
}
}
/**
* Font CSS
*
* @param $selector
* @param $property
* @param $theme_mod
* @param $after_css
*
* @return string
*/
public static function font_css( $selector, $font ) {
$css = '';
$css .= $selector . '{'; // Start CSS
$css .= ! empty( $font['font'] ) ? "font-family: '" . $font['font'] . "', sans-serif;" : '';
$css .= ! empty( $font['size'] ) ? "font-size: {$font['size']}px;" : '';
$css .= ! empty( $font['lineheight'] ) ? "line-height: {$font['lineheight']}px;" : '';
$css .= ! empty( $font['regularweight'] ) ? "font-weight: {$font['regularweight']};" : '';
$css .= '}'; // End CSS
return $css;
}
}
|
<?php
namespace App\Http\Controllers;
use App\Models\City;
use App\Models\Operator;
use App\Models\Package;
use App\Models\PackageStatus;
use App\Models\Status;
use App\Models\User;
use Auth;
use DB;
use Hash;
use Illuminate\Http\Request;
class OperatorController extends Controller
{
public function showClients()
{
$clients = User::all();
$message = session("message");
return view("operator.show-clients", compact('clients', 'message'));
}
public function showPackages()
{
$userId = Auth::user()->id;
$operator = Operator::where('user_id', $userId)->first();
$packages = Package::where('city_id', $operator->city_id)
->where('street_id', $operator->street_id)
->with(['city', 'user']) // Eager load the 'city' and 'user' relationships
->get();
return view("operator.show-all-packages", compact("packages"));
}
public function createClient()
{
return view("operator.create-client");
}
public function showPackage($packageId)
{
$package = Package::where("id", $packageId)->first();
$packageHistory = PackageStatus::where("package_id", $packageId)
->with(['status'])
->get();
// dd($packageHistory);
$nextStatus = null;
$packageStatusId = $package->status_id;
if ($packageStatusId < 4) {
$nextStatus = Status::where('id', $packageStatusId + 1)->first();
// dd($nextStatus);
}
return view("operator.show-package", compact("package", "packageHistory", "nextStatus"));
}
public function updateStatus()
{
// dd($_POST);
$packageId = request()->input('packageId');
$statusId = request()->input('statusId');
$isFinished = $statusId == 4 ? true : false;
DB::beginTransaction();
try {
// $package = Package::find($packageId);
Package::where('id', $packageId)->update([
'status_id' => $statusId,
'is_finished' => $isFinished
]);
} catch (\Exception $e) {
DB::rollBack();
return back()->withErrors(['status' => 'nepavyko pakeisti statuso']);
}
try {
// dd($statusId);
// dd($packageId + $statusId);
PackageStatus::create(['package_id' => $packageId, 'status_id' => $statusId]);
// dd('insert to status failed ');
DB::commit();
return redirect(route('operator.show-package', [$packageId]));
// return response('status update to ' . $statusId);
} catch (\Exception $e) {
// dd('insert to status failed ');
dd($e);
DB::rollBack();
return response('Netinkama statusas: ' . $statusId);
}
}
public function viewStatus($id)
{
$packages = Package::with('city, user')
->where('id', $id);
}
public function storeUser(Request $request)
{
$data = $request->validate(
[
'name' => 'required',
'email' => 'required|email',
'password' => [
'required',
'min:6',
'regex:/^(?=.*[A-Z])(?=.*[!@#$%^&*])/', // Requires at least one uppercase letter and one symbol
],
],
[
'password.required' => 'Slaptažodis yra būtinas',
'password.min' => 'Slaptažodis privalo būti bent 6 simbolių ilgio',
'password.regex' => 'Slaptažodį privalo sudaryti bent viena didžioji raidė ir specalus simbolis'
]
);
$data['password'] = Hash::make($data['password']); // Hash the password
$data['user_role'] = '1';
try {
$user = User::create($data);
} catch (\Exception $e) {
// dd($e);
return back()->withInput()->with('message', "Naudotojoas su šiuo el. paštu jau užregistruotas");
}
return redirect()->route('operator.show-clients')->with("message", "Klientas sukurtas sėkmingai");
}
}
|
/*****************************************************************************
*
* Copyright (c) 2018-2019, Oleg `Kanedias` Chernovskiy
*
* This file is part of MARC-FS.
*
* MARC-FS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MARC-FS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MARC-FS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
class ThreadPool {
public:
ThreadPool(size_t);
~ThreadPool();
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>;
private:
// need to keep track of threads so we can join them
std::vector<std::thread> workers;
// the task queue
std::queue<std::function<void()> > tasks;
// synchronization
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
: stop(false) {
for (size_t i = 0; i < threads; ++i) {
workers.emplace_back([this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock, [this]{ return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
}
// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared<std::packaged_task<return_type()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if (stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task](){ (*task)(); });
}
condition.notify_one();
return res;
}
// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker: workers)
worker.join();
}
#endif // THREAD_POOL_H
|
YARN-5411. Create a proxy chain for ApplicationClientProtocol in the Router. (Giovanni Matteo Fumarola via Subru).
(cherry picked from commit 4846069061b6baa06da3b524b9e36567dd368388)
+import java.io.IOException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.service.CompositeService;
+import org.apache.hadoop.util.ShutdownHookManager;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.yarn.YarnUncaughtExceptionHandler;
+import org.apache.hadoop.yarn.conf.YarnConfiguration;
+import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
+import org.apache.hadoop.yarn.server.router.clientrm.RouterClientRMService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
-public class Router{
+public class Router extends CompositeService {
+ private static final Logger LOG = LoggerFactory.getLogger(Router.class);
+ private static CompositeServiceShutdownHook routerShutdownHook;
+ private Configuration conf;
+ private AtomicBoolean isStopping = new AtomicBoolean(false);
+ private RouterClientRMService clientRMProxyService;
+
+ /**
+ * Priority of the Router shutdown hook.
+ */
+ public static final int SHUTDOWN_HOOK_PRIORITY = 30;
+
+ public Router() {
+ super(Router.class.getName());
+ }
+
+ protected void doSecureLogin() throws IOException {
+ // TODO YARN-6539 Create SecureLogin inside Router
+ }
+
+ @Override
+ protected void serviceInit(Configuration config) throws Exception {
+ this.conf = config;
+ clientRMProxyService = createClientRMProxyService();
+ addService(clientRMProxyService);
+ super.serviceInit(conf);
+ }
+
+ @Override
+ protected void serviceStart() throws Exception {
+ try {
+ doSecureLogin();
+ } catch (IOException e) {
+ throw new YarnRuntimeException("Failed Router login", e);
+ }
+ super.serviceStart();
+ }
+
+ @Override
+ protected void serviceStop() throws Exception {
+ if (isStopping.getAndSet(true)) {
+ return;
+ }
+ super.serviceStop();
+ }
+
+ protected void shutDown() {
+ new Thread() {
+ @Override
+ public void run() {
+ Router.this.stop();
+ }
+ }.start();
+ }
+
+ protected RouterClientRMService createClientRMProxyService() {
+ return new RouterClientRMService();
+ }
+
+ public static void main(String[] argv) {
+ Configuration conf = new YarnConfiguration();
+ Thread
+ .setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler());
+ StringUtils.startupShutdownMessage(Router.class, argv, LOG);
+ Router router = new Router();
+ try {
+
+ // Remove the old hook if we are rebooting.
+ if (null != routerShutdownHook) {
+ ShutdownHookManager.get().removeShutdownHook(routerShutdownHook);
+ }
+
+ routerShutdownHook = new CompositeServiceShutdownHook(router);
+ ShutdownHookManager.get().addShutdownHook(routerShutdownHook,
+ SHUTDOWN_HOOK_PRIORITY);
+
+ router.init(conf);
+ router.start();
+ } catch (Throwable t) {
+ LOG.error("Error starting Router", t);
+ System.exit(-1);
+ }
+ }
|
** SGI_COPYRIGHT_TAG
** Author : Roger Chickering (MMM yyyy)
** Modified by : Gavin Bell (MMM yyyy)
** VSG_COPYRIGHT_TAG
** Modified by : VSG (MMM YYYY)
#ifndef _SO_OVERRIDE_ELEMENT
#define _SO_OVERRIDE_ELEMENT
#include <Inventor/elements/SoSubElement.h>
//
// Macro to implement get*Override inline methods. There are a lot of
// these methods, each of which has an identical implementation and
// which needs to be inline to keep traversal fast.
#define SO_GET_OVERRIDE(flag) \
const SoOverrideElement *elt; \
elt = SoElement::getConstElement<SoOverrideElement>(state); \
return (elt->flags & flag)!=0;
//
// Implement set*Override methods.
//
#define SO_SET_OVERRIDE(flag) \
SoOverrideElement *elt; \
elt = SoElement::getElement<SoOverrideElement>(state); \
if (override) \
elt->flags |= flag; \
else \
elt->flags &= ~flag;
/**
* Stores a flag for each type of element which can be
* overridden.
*
* @ingroup elements
*
* @DESCRIPTION
* This element stores a flag for each type of element which can be
* overridden. Nodes implement override by setting the appropriate
* bit if their override flag is on, and ignoring overridden elements
* if the corresponding bit in the state's SoOverrideElement is set.
*
* @SEE_ALSO
*/
SoEXTENDER_Documented class INVENTOR_API SoOverrideElement : public SoElement {
SO_ELEMENT_HEADER(SoOverrideElement);
enum {
AMBIENT_COLOR = 0x1,
COLOR_INDEX = 0x2,
COMPLEXITY = 0x4,
COMPLEXITY_TYPE = 0x8,
CREASE_ANGLE = 0x10,
DIFFUSE_COLOR = 0x20,
/**
* TRANSPARENCY is same as diffuse color: overriding one will override both.
*/
TRANSPARENCY = 0x20,
DRAW_STYLE = 0x40,
EMISSIVE_COLOR = 0x80,
FONT_NAME = 0x100,
FONT_SIZE = 0x200,
LIGHT_MODEL = 0x400,
LINE_PATTERN = 0x800,
LINE_WIDTH = 0x1000,
MATERIAL_BINDING = 0x2000,
POINT_SIZE = 0x4000,
PICK_STYLE = 0x8000,
SHAPE_HINTS = 0x10000,
SHININESS = 0x20000,
SPECULAR_COLOR = 0x40000,
POLYGON_OFFSET = 0x80000,
PATTERN_OFFSET = 0x100000,
FONT_RENDERSTYLE = 0x200000,
FULL_SCENE_ANTIALIASING = 0x400000,
TRANSPARENCY_TYPE = 0x800000,
ENVIRONMENT = 0x1000000,
DEPTH_BUFFER_RANGE = 0x2000000,
DEPTH_BUFFER_FUNCTION = 0x4000000,
BBOX_TYPE = 0x8000000,
NEIGHBOR_TOLERANCE = 0x10000000
};
public:
/**
* Comparison based on value of int32_ts.
*/
virtual SbBool matches(const SoElement *elt) const;
/**
* Overrides push() method to copy values from next instance in
* the stack, and set up cache dependencies correctly.
*/
virtual void push(SoState *state);
//
// "get" methods for each element which can be overridden.
//
/**
* Returns TRUE if SoAmbientColorElement is overridden.
*/
static SbBool getAmbientColorOverride(SoState *state)
{ SO_GET_OVERRIDE(AMBIENT_COLOR); }
/**
* Returns TRUE if SoColorIndexElement is overridden.
*/
static SbBool getColorIndexOverride(SoState *state)
{ SO_GET_OVERRIDE(COLOR_INDEX); }
/**
* Returns TRUE if SoComplexityElement is overridden.
*/
static SbBool getComplexityOverride(SoState *state)
{ SO_GET_OVERRIDE(COMPLEXITY); }
/**
* Returns TRUE if SoComplexityTypeElement is overridden.
*/
static SbBool getComplexityTypeOverride(SoState *state)
{ SO_GET_OVERRIDE(COMPLEXITY_TYPE); }
/**
* Returns TRUE if SoCreaseAngleElement is overridden.
*/
static SbBool getCreaseAngleOverride(SoState *state)
{ SO_GET_OVERRIDE(CREASE_ANGLE); }
/**
* Returns TRUE if SoNeighborToleranceElement is overridden.
*/
static SbBool getNeighborToleranceOverride(SoState *state)
{ SO_GET_OVERRIDE(NEIGHBOR_TOLERANCE); }
/**
* Returns TRUE if SoDiffuseColorElement is overridden.
*/
static SbBool getDiffuseColorOverride(SoState *state)
{ SO_GET_OVERRIDE(DIFFUSE_COLOR); }
/**
* Returns TRUE if SoDrawStyleElement is overridden.
*/
static SbBool getDrawStyleOverride(SoState *state)
{ SO_GET_OVERRIDE(DRAW_STYLE); }
/**
* Returns TRUE if SoEmissiveColorElement is overridden.
*/
static SbBool getEmissiveColorOverride(SoState *state)
{ SO_GET_OVERRIDE(EMISSIVE_COLOR); }
/**
* Returns TRUE if SoFontNameElement is overridden.
*/
static SbBool getFontNameOverride(SoState *state)
{ SO_GET_OVERRIDE(FONT_NAME); }
/**
* Returns TRUE if SoFontSizeElement is overridden.
*/
static SbBool getFontSizeOverride(SoState *state)
{ SO_GET_OVERRIDE(FONT_SIZE); }
/**
* Returns TRUE if SoFontRenderStyleElement is overridden.
*/
static SbBool getFontRenderStyleOverride(SoState *state)
{ SO_GET_OVERRIDE(FONT_RENDERSTYLE); }
/**
* Returns TRUE if SoLightModelElement is overridden.
*/
static SbBool getLightModelOverride(SoState *state)
{ SO_GET_OVERRIDE(LIGHT_MODEL); }
/**
* Returns TRUE if SoLinePatternElement is overridden.
*/
static SbBool getLinePatternOverride(SoState *state)
{ SO_GET_OVERRIDE(LINE_PATTERN); }
/**
* Returns TRUE if SoLineWidthElement is overridden.
*/
static SbBool getLineWidthOverride(SoState *state)
{ SO_GET_OVERRIDE(LINE_WIDTH); }
/**
* Returns TRUE if SoMaterialBindingElement is overridden.
*/
static SbBool getMaterialBindingOverride(SoState *state)
{ SO_GET_OVERRIDE(MATERIAL_BINDING); }
/**
* Returns TRUE if SoPointSizeElement is overridden.
*/
static SbBool getPointSizeOverride(SoState *state)
{ SO_GET_OVERRIDE(POINT_SIZE); }
/**
* Returns TRUE if SoPickStyleElement is overridden.
*/
static SbBool getPickStyleOverride(SoState *state)
{ SO_GET_OVERRIDE(PICK_STYLE); }
/**
* Returns TRUE if SoShapeHintsElement is overridden.
*/
static SbBool getShapeHintsOverride(SoState *state)
{ SO_GET_OVERRIDE(SHAPE_HINTS); }
/**
* Returns TRUE if SoShininessElement is overridden.
*/
static SbBool getShininessOverride(SoState *state)
{ SO_GET_OVERRIDE(SHININESS); }
/**
* Returns TRUE if SoSpecularColorElement is overridden.
*/
static SbBool getSpecularColorOverride(SoState *state)
{ SO_GET_OVERRIDE(SPECULAR_COLOR); }
/**
* Returns TRUE if SoTransparencyElement is overridden.
*/
static SbBool getTransparencyOverride(SoState *state)
{ SO_GET_OVERRIDE(TRANSPARENCY); }
/**
* Returns TRUE if SoTransparencyTypeElement is overridden.
*/
static SbBool getTransparencyTypeOverride(SoState *state)
{ SO_GET_OVERRIDE(TRANSPARENCY_TYPE); }
/**
* Returns TRUE if SoEnvironmentElement is overridden.
*/
static SbBool getEnvironmentOverride(SoState *state)
{ SO_GET_OVERRIDE(ENVIRONMENT); }
/**
* Returns TRUE if SoPolygonOffsetElement is overridden.
*/
static SbBool getPolygonOffsetOverride(SoState *state)
{ SO_GET_OVERRIDE(POLYGON_OFFSET); }
/**
* Returns TRUE if SoPatternElement is overriden.
*/
static SbBool getPatternOverride(SoState* state)
{ SO_GET_OVERRIDE(PATTERN_OFFSET); }
/**
* Returns TRUE if SoFullSceneAntialiasingElement is overridden.
*/
static SbBool getFullSceneAntialiasingOverride(SoState *state)
{ SO_GET_OVERRIDE(FULL_SCENE_ANTIALIASING); }
/**
* Returns TRUE if SoDepthBuffer::range is overridden.
*/
static SbBool getDepthBufferRangeOverride(SoState *state)
{ SO_GET_OVERRIDE(DEPTH_BUFFER_RANGE); }
/**
* Returns TRUE if SoDepthBuffer::function is overridden.
*/
static SbBool getDepthBufferFunctionOverride(SoState *state)
{ SO_GET_OVERRIDE(DEPTH_BUFFER_FUNCTION); }
/**
* Returns TRUE if SoComplexityType::bboxType is overridden.
*/
static SbBool getBBoxTypeOverride(SoState *state)
{ SO_GET_OVERRIDE(BBOX_TYPE); }
//
// "set" methods for each element which can be overridden.
//
/**
* Set override flag for SoAmbientColorElement.
*/
static void setAmbientColorOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(AMBIENT_COLOR); }
/**
* Set override flag for SoColorIndexElement.
*/
static void setColorIndexOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(COLOR_INDEX); }
/**
* Set override flag for SoComplexityElement.
*/
static void setComplexityOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(COMPLEXITY); }
/**
* Set override flag for SoComplexityTypeElement.
*/
static void setComplexityTypeOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(COMPLEXITY_TYPE); }
/**
* Set override flag for SoCreaseAngleElement.
*/
static void setCreaseAngleOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(CREASE_ANGLE); }
/**
* Set override flag for SoNeighborToleranceElement.
*/
static void setNeighborToleranceOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(NEIGHBOR_TOLERANCE); }
/**
* Set override flag for SoDiffuseColorElement.
*/
static void setDiffuseColorOverride(SoState *state, SoNode *, SbBool override);
/**
* Set override flag for SoDrawStyleElement.
*/
static void setDrawStyleOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(DRAW_STYLE); }
/**
* Set override flag for SoEmissiveColorElement.
*/
static void setEmissiveColorOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(EMISSIVE_COLOR); }
/**
* Set override flag for SoFontNameElement.
*/
static void setFontNameOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(FONT_NAME); }
/**
* Set override flag for SoFontSizeElement.
*/
static void setFontSizeOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(FONT_SIZE); }
/**
* Set override flag for SoFontRenderStyleElement.
*/
static void setFontRenderStyleOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(FONT_RENDERSTYLE); }
/**
* Set override flag for SoLightModelElement.
*/
static void setLightModelOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(LIGHT_MODEL); }
/**
* Set override flag for SoLinePatternElement.
*/
static void setLinePatternOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(LINE_PATTERN); }
/**
* Set override flag for SoLineWidthElement.
*/
static void setLineWidthOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(LINE_WIDTH); }
/**
* Set override flag for SoMaterialBindingElement.
*/
static void setMaterialBindingOverride(SoState *state, SoNode *, SbBool override);
/**
* Set override flag for SoPickStyleElement.
*/
static void setPickStyleOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(PICK_STYLE); }
/**
* Set override flag for SoPointSizeElement.
*/
static void setPointSizeOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(POINT_SIZE); }
/**
* Set override flag for SoShapeHintsElement.
*/
static void setShapeHintsOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(SHAPE_HINTS); }
/**
* Set override flag for SoShininessElement.
*/
static void setShininessOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(SHININESS); }
/**
* Set override flag for SoSpecularColorElement.
*/
static void setSpecularColorOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(SPECULAR_COLOR); }
/**
* Set override flag for SoTransparencyElement.
*/
static void setTransparencyOverride(SoState *state, SoNode *, SbBool override);
/**
* Set override flag for SoTransparencyTypeElement.
*/
static void setTransparencyTypeOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(TRANSPARENCY_TYPE); }
/**
* Set override flag for SoEnvironmentElement.
*/
static void setEnvironmentOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(ENVIRONMENT); }
/**
* Set override flag for SoPolygonOffsetElement.
*/
static void setPolygonOffsetOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(POLYGON_OFFSET); }
/**
* Set override flag for SoPatternElement.
*/
static void setPatternOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(PATTERN_OFFSET); }
/**
* Set override flag for SoFullSceneAntialiasingElement.
*/
static void setFullSceneAntialiasingOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(FULL_SCENE_ANTIALIASING); }
/**
* Set override flag for SoDepthBuffer::range.
*/
static void setDepthBufferRangeOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(DEPTH_BUFFER_RANGE); }
/**
* Set override flag for SoDepthBuffer::function.
*/
static void setDepthBufferFunctionOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(DEPTH_BUFFER_FUNCTION); }
/**
* Set override flag for SoComplexity::bboxType.
*/
static void setBBoxTypeOverride(SoState *state, SoNode *, SbBool override)
{ SO_SET_OVERRIDE(BBOX_TYPE); }
/**
* Prints element (for debugging).
*/
virtual void print(FILE *fp) const;
SoINTERNAL public:
// Initializes the SoOverrideElement class
static void initClass();
static void exitClass();
// Initializes element
virtual void init(SoState *state);
// Copy method, copies flags
virtual SoElement *copyMatchInfo() const;
private:
// Used by ::print method
void pFlag(FILE *, const char *, int) const;
uint32_t flags;
};
#endif /* _SO_OVERRIDE_ELEMENT */
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class SettingsManager : MonoBehaviour
{
// Default values
[SerializeField]
private float defaultMusicVolume = 0.2f;
[SerializeField]
private float defaultSFXVolume = 0.7f;
[SerializeField]
private float defaultUIVolume = 0.5f;
[SerializeField]
private bool defaultInvertEarthRot = false;
// Public access to default values
public float DefaultMusicVolume { get { return defaultMusicVolume; } }
public float DefaultSFXVolume { get { return defaultSFXVolume; } }
public float DefaultUIVolume { get { return defaultUIVolume; } }
public bool DefaultInvertEarthRot { get { return defaultInvertEarthRot; } }
// Customized values
private bool invertEarthRot;
// Public access to customized values
public bool InvertEarthRot { get { return invertEarthRot; } }
// Reference to self
public static SettingsManager SM;
private void Awake()
{
// Checks if a GameManager instance exists and destroys it
// Singleton pattern to ensure the first GameManager loaded is the one that persists
if (SM == null)
{
SM = this; // sets current GameManager object as instance if no other exists
}
else
{
Destroy(gameObject); // destroys self if there already exists another instance; breaks loop
return;
}
// Makes the GameManager game object persistent through multiple scenes
DontDestroyOnLoad(gameObject);
}
private void Start()
{
// Set default sound volume
AudioManager.AM.ChangeVolume("Music", DefaultMusicVolume);
AudioManager.AM.ChangeVolume("SFX", DefaultSFXVolume);
AudioManager.AM.ChangeVolume("UI", DefaultUIVolume);
}
/// <summary>
/// Changes the current volume of sounds throughout the game.
/// </summary>
/// <param name="slider">Volume slider object from options menu.</param>
public void VolumeChanged(Slider slider)
{
if (GameObject.Find("MainMenu Canvas") != null)
{
if (GameObject.Find("MainMenu Canvas").GetComponent<MainMenu>().CurrentScene == "Options")
{
switch (slider.name)
{
// Change music volume
case ("MusicSlider"):
AudioManager.AM.ChangeVolume("Music", slider.value);
break;
// Changed sound effects volume
case ("SFXSlider"):
AudioManager.AM.ChangeVolume("SFX", slider.value);
AudioManager.AM.Play("Virus Click");
break;
// Change volume of UI elements
case ("UISlider"):
AudioManager.AM.ChangeVolume("UI", slider.value);
AudioManager.AM.Play("Button Hover");
break;
// Slider doesn't exist or hasn't been implemented above
default:
Debug.Log(slider.name + " does not exist!");
break;
}
}
}
}
public void InvertEarthRotation(Toggle toggle)
{
invertEarthRot = toggle.isOn;
Debug.Log("invertEarthRot (SettingsManager): " + invertEarthRot);
}
}
|
import { Avatar, ListItemDecorator, Option, Select, SelectOption } from "@mui/joy";
import { useAtom } from "jotai";
import type { SyntheticEvent } from "react";
import { languageAtom } from "@/docs/atoms";
import FlagCn from "@/docs/components/flags/cn";
import FlagCz from "@/docs/components/flags/cz";
import FlagDe from "@/docs/components/flags/de";
import FlagEs from "@/docs/components/flags/es";
import FlagFr from "@/docs/components/flags/fr";
import FlagIt from "@/docs/components/flags/it";
import FlagJp from "@/docs/components/flags/jp";
import FlagNl from "@/docs/components/flags/nl";
import FlagPirate from "@/docs/components/flags/pirate";
import FlagPl from "@/docs/components/flags/pl";
import FlagPt from "@/docs/components/flags/pt";
import FlagUs from "@/docs/components/flags/us";
import { SxProps, Theme } from "@mui/material/styles";
const options = [
{ id: "en-US", value: "english", flag: <FlagUs />, label: "English" },
{ id: "de-DE", value: "german", flag: <FlagDe />, label: "Deutsch" },
{ id: "es-ES", value: "spanish", flag: <FlagEs />, label: "Español" },
{ id: "pt-PT", value: "portugese", flag: <FlagPt />, label: "Português" },
{ id: "it-IT", value: "italian", flag: <FlagIt />, label: "Italiano" },
{ id: "fr-FR", value: "french", flag: <FlagFr />, label: "Français" },
{ id: "nl-NL", value: "dutch", flag: <FlagNl />, label: "Nederlands" },
{ id: "pl-PL", value: "polish", flag: <FlagPl />, label: "Polski" },
{ id: "cs-CZ", value: "czech", flag: <FlagCz />, label: "Čeština" },
{ id: "zh-CN", value: "chinese", flag: <FlagCn />, label: "中文" },
{ id: "ja-JP", value: "japanese", flag: <FlagJp />, label: "日本語" },
{ id: "en-pirate", value: "pirate", flag: <FlagPirate />, label: "Pirate" },
];
type LanguageSelectProps = {
sx?: SxProps<Theme>;
};
export function LanguageSelect({ sx = [] }: LanguageSelectProps) {
const [language, setLanguage] = useAtom(languageAtom);
function renderValue(option: SelectOption<string> | null) {
if (!option) {
return null;
}
return (
<>
<ListItemDecorator>
<Avatar variant="outlined" size="sm" sx={{ "--Avatar-size": "20px" }}>
{options.find(o => o.value === option.value)?.flag}
</Avatar>
</ListItemDecorator>
</>
);
}
return (
<Select
sx={[...(Array.isArray(sx) ? sx : [sx])]}
name="language"
aria-label="Select a language"
value={language}
slotProps={{ listbox: { sx: { zIndex: 4000 } } }}
renderValue={renderValue}
onChange={(event: SyntheticEvent, value) => {
setLanguage(value);
}}
>
{options.map(option => (
<Option key={option.id} value={option.value}>
<ListItemDecorator>
<Avatar variant="outlined" size="sm" sx={{ "--Avatar-size": "20px" }}>
{option.flag}
</Avatar>
</ListItemDecorator>
{option.label}
</Option>
))}
</Select>
);
}
|
import { Menu } from ".";
import { Tragamonedas } from "./Tragamonedas";
import { Jugar } from "./interface";
import colors from "colors"
import * as readlineSync from 'readline-sync'
export class Frutas extends Tragamonedas implements Jugar { //inicio de la sub clase frutas
private pozoAcumulado:number;
public constructor (psalaNro:number,pozoAcumulado:number,pdineroDisponible:number, pdineroApuesta?:number) { //se agrega parametros del padre
super (psalaNro,pdineroDisponible, pdineroApuesta)//y del padre del padre, y en la super clase tambien
this.pozoAcumulado=pozoAcumulado;
} // fin constructor
public setPozoAcumulado (pozoAcumulado:number):void {
this.pozoAcumulado = pozoAcumulado;
}
public getPozoAcumulado ():number {
return this.pozoAcumulado;
}
//método que implementa la interfaz
//le da comienzo a los distintos juegos
public inicioJuego():void {
console.log(colors.bgGreen(`Pozo acumulado ${this.pozoAcumulado} $`));
console.log(` Dinero disponible: ${this.dineroDisponible}$` );
console.log(colors.bgMagenta(`Inicia el juego. Mucha suerte!`));
this.apostar();
console.log(`Procesando...***tulin tulin---tulin tulin---***`);
let lineas1 = ["manzana","banana","naranja","pera"]
let aleatorio = lineas1[Math.floor(Math.random()*lineas1.length)]
let lineas2 = ["manzana","banana","naranja","pera"]
let aleatorio2 = lineas2[Math.floor(Math.random()*lineas2.length)]
let lineas3 = ["manzana","banana","naranja","pera"]
let aleatorio3 = lineas3[Math.floor(Math.random()*lineas3.length)]
let lineas4 = ["manzana","banana","naranja","pera"]
let aleatorio4 = lineas4[Math.floor(Math.random()*lineas4.length)]
console.log(colors.bgMagenta(`Su juego Lineas --> ${aleatorio} ----${aleatorio2} ----- ${aleatorio3}----${aleatorio4}`));
if((aleatorio === aleatorio3 && aleatorio !== aleatorio2 && aleatorio !== aleatorio4) ||
(aleatorio === aleatorio4 && aleatorio !== aleatorio2 && aleatorio !== aleatorio3) ||
(aleatorio2 === aleatorio3 && aleatorio2 !== aleatorio && aleatorio2 !== aleatorio4) ||
(aleatorio2 === aleatorio4 && aleatorio2 !== aleatorio && aleatorio2 !== aleatorio3) ||
(aleatorio3 === aleatorio4 && aleatorio3 !== aleatorio && aleatorio3 !== aleatorio2)||
(aleatorio === aleatorio2 && aleatorio !== aleatorio3 && aleatorio !== aleatorio4 )){
console.log(colors.yellow(
` Acierto de 2 lineas. Usted gana $ ${this.dineroApuesta + 2000}`),
colors.red(`TOTAL ACUMULADO ${this.dineroDisponible = this.dineroDisponible + this.dineroApuesta + 2000}`));
} else if((aleatorio === aleatorio2 && aleatorio === aleatorio3 && aleatorio !== aleatorio4) ||
(aleatorio === aleatorio4 && aleatorio===aleatorio2 && aleatorio !== aleatorio3)||
(aleatorio === aleatorio3 && aleatorio === aleatorio4 && aleatorio !== aleatorio2)||
(aleatorio3 === aleatorio && aleatorio3 === aleatorio2 && aleatorio3 !== aleatorio4)||
(aleatorio3 === aleatorio2 && aleatorio3 === aleatorio4 && aleatorio3 !== aleatorio)){
console.log(colors.bgBlue(
`Acierto de 3 lineas. Usted gana $ ${this.dineroApuesta + 5000}`),
colors.red(`TOTAL ACUMULADO ${this.dineroDisponible = this.dineroDisponible + this.dineroApuesta + 5000}`));
console.log(`Dinero disponible ${this.dineroDisponible}`);
} else if(aleatorio === aleatorio2 && aleatorio === aleatorio3 && aleatorio === aleatorio4){
console.log(colors.bgCyan(
`HA ACERTADO LAS 4 LINEAS!!!!! USTED GANA ${this.dineroDisponible = this.pozoAcumulado + this.dineroApuesta} `));
} else{
console.log(colors.bgRed(
`Sin aciertos!! Usted pierde ${this.dineroApuesta} Desea apostar nuavemente?`));
}
let seguirAbandonar: string;
seguirAbandonar = readlineSync.question(colors.blue(
`Recuerde que jugar en exceso es signo de posible adiccion
_________________________
¿ DESEA SEGUIR APOSTANDO ?
Responda S/N : ` ));
if (seguirAbandonar == "S") {
this.dineroDisponible = this.dineroDisponible;
this.inicioJuego();
} else if (seguirAbandonar === "N") {
let menu=new Menu();
menu.getElegirJuego();
console.log(`Gracias por jugar con nosotros`);
}
}
//método que implementa la interfaz
//ESTE METODO DEVUELVE CUAL ES LA PROBABILIDAD DE GANAR APOSTANDO N cant de líneas.
public probabilidadDeGanar():void{
let cantLineas;
cantLineas = readlineSync.questionInt(
colors.bgGreen("Antes de empezar el juego, vea cuales son sus probabilidades de acertar 2,3 o 4 lineas. Ingrese una opción: "
));
let probabilidad: number = Math.floor(Math.random() * 4)+1;
console.log(colors.red(`La probabilidad de acertar ${cantLineas} lineas es de`),
colors.red(`*****${probabilidad} en ${Math.floor(Math.random() * 16)+1} *****`));
this.inicioJuego();
}
//método que implementa la interfaz
//interactúa con la apuesta ingresada y el saldo disponible
// con el ciclo do - while primero se evalúa la sentencia y luego la condición.
public apostar(): void {
let apuestaLocal: number;
do { //hacer
apuestaLocal = readlineSync.questionInt(colors.bgBlue("Ingrese su apuesta: "));
if (apuestaLocal > 0) {//condicion que evalua el monto ingresado sea mayor a 0
this.dineroDisponible = this.dineroDisponible - apuestaLocal;
this.dineroApuesta = apuestaLocal;
} else if (apuestaLocal === 0){
console.log(colors.red("Saldo insuficiente. Por favor, ingrese un monto válido"));
}
console.log(colors.red(`SE LE RESTAN ${this.dineroApuesta}`));
console.log(colors.green(`SALDO DISPONIBLE: ${this.dineroDisponible}`));
} while (apuestaLocal < 0); //mientras que//si la apuesta ingresada en menor o igual a cero, el ciclo se vuelve a ejecutar
}
} // fin de la sub clase
|
Feature: Cadastrar noticia
Background:
Given login noticia
And clicar em Noticia no menu
When abrir a tela de cadastro de Noticia
@web @noticia @registrarNotSuc
Scenario Outline: Registrar noticia com sucesso
And preencher campo com titulo "<titulo>"
And preencher campo com data da publicacao "<dataPubli>"
And preencher campo com imagem "<imagem>"
And preencher campo com texto da noticia "<texto>"
And clicar no botao Cadastrar noticia
Then retorna a mensagem "<mensagem>" para noticia
Examples:
| titulo | dataPubli | imagem | texto | mensagem |
| noticia1 | 06062023 | D:\testenoticia.jpg | aaaaaaaaaaaaaaaaaaa | Cadastrado com sucesso! |
| noticia2 | 07092022 | D:\testenoticia.jpg | aaaaaaaaaaaaaaaaaaa | Cadastrado com sucesso! |
| noticia3 | 25112023 | D:\testenoticia.jpg | aaaaaaaaaaaaaaaaaaa | Cadastrado com sucesso! |
| noticia4 | 01012000 | D:\testenoticia.jpg | aaaaaaaaaaaaaaaaaaa | Cadastrado com sucesso! |
@web @noticia @registrarNotErro
Scenario Outline: Registrar noticia com campos em branco
And preencher tiulo "<tiulo>" da noticia
And preencher data da publicacao "<dataPubli>" da noticia
And preencher imagem "<imagem>" da noticia
And preencher texto da noticia "<texto>" noticia
Then retorna a mensagem "<mensagem>" na tela de noticia
Examples:
| tiulo | dataPubli | imagem | texto | mensagem |
| | 26062023 | D:\\testenoticia.jpg | aaaaaaaaaaaaaaaaaa | O campo Título é obrigatório |
| TesteRC | | D:\\testenoticia.jpg | bbbbbbbbbbbbbbbbbb | O campo Data de publicação é obrigatório |
| TesteRC | 27072024 | D:\\testenoticia.jpg | | O campo Texto é obrigatório |
@web @noticia @consultarNot
Scenario Outline: Consultar noticia cadastrado
When rolar pagina de noticia
When buscar o noticia pelo "<titulo>"
Then o retorna o titulo da noticia "<titulo>"
Then o retorna a data de cadastro da noticia "<dataCad>"
Then o retorna a data de publicacao da noticia "<datapubli>"
Examples:
| titulo | dataCad | datapubli |
| noticia1 | 06/07/2023 | 06/06/2023 |
| noticia2 | 06/07/2023 | 07/09/2022 |
| noticia3 | 06/07/2023 | 25/11/2023 |
| noticia4 | 06/07/2023 | 01/01/2000 |
@web @noticia @alterarNot
Scenario Outline: Alterar noticia cadastrada
When role pagina de noticia
When inserir "<titulo>" para buscar noticia
When o registro do noticia com "<titulo>" retorna
When clicar no icone de edicao de noticia
When os dados do noticia serao apresentados
Then altere o nome do noticia "<titulo2>"
Then clique em Alterar noticia
Then mensagem de alteracao do cadastro da noticia "<mensagem>"
Examples:
| titulo | titulo2 | mensagem |
| noticia1 | Noticia1 | Alterado com sucesso! |
| noticia2 | Noticia2 | Alterado com sucesso! |
| noticia3 | Noticia3 | Alterado com sucesso! |
| noticia4 | Noticia4 | Alterado com sucesso! |
@web @noticia @excluirNot
Scenario Outline: Deletar noticia cadastrado
When role pagina de noticia para baixo
When insera "<titulo>" no campo de busca de noticia
When o registro do noticia do "<titulo>" retornar
When clicar no icone de exclusão do noticia
When clicar em SIM para deletar noticia
Then mensagem "<mensagem>" de deletado noticia
Examples:
| titulo | mensagem |
| Noticia1 | Deletado com sucesso! |
| Noticia2 | Deletado com sucesso! |
| Noticia3 | Deletado com sucesso! |
| Noticia4 | Deletado com sucesso! |
|
# Цикл связанных списков
# Определите, есть ли в связанном списке цикл.
from typing import List, Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def getList(self, maxLength: int or None = None):
stack = []
if maxLength != None: i = 0
node = self
while node:
stack.append(node.val)
node = node.next
if maxLength != None: i += 1
if maxLength != None and i > maxLength: break
return stack
def hasCycle(self) -> bool:
seen = set()
node = self
while node:
if node in seen:
return True
seen.add(node)
node = node.next
return False
def reverseList(self):
prev = None
current = self
while current:
current.next, prev, current = prev, current, current.next
return prev
def createList(array: List):
temp_list = ListNode(array[0])
result = temp_list
for value in array[slice(1, len(array))]:
temp_list.next = ListNode(value)
temp_list = temp_list.next
return result
values = [1,2,3,4,5]
temp_list_node = createList(values)
list_node = temp_list_node
print('ListNode is Cycle', list_node.hasCycle(), list_node.getList())
list_node = list_node.reverseList()
print('ListNode is reversed', list_node.getList())
list_node.next.next.next.next.next = list_node
print('ListNode is Cycle', list_node.hasCycle(), list_node.getList(len(values)))
print((6 & 1))
|
require("httr")
require("jsonlite")
dateTimeStr = function(){
dt = Sys.time()
d = format(dt, format="%Y-%m-%d")
t = format(dt, format="%H:%M:%S")
t = gsub(":", "%3A", t)
str = paste(d, t, sep = "T", collapse = NULL)
return(str)
}
# the only exposed function
getWeatherForecast <- function(){
url_base = "https://api.data.gov.sg/v1/environment/2-hour-weather-forecast?date_time="
weather_url = paste(url_base, dateTimeStr(), sep = "", collapse = NULL)
response = GET(weather_url)
responseStr = content(response, "text", encoding = "UTF-8")
responseJson = fromJSON(responseStr, flatten = TRUE)
forecasts = as.data.frame(responseJson$items$forecasts)
metadata = as.data.frame(responseJson$area_metadata)
merged = merge(forecasts, metadata)
names(merged) = c("area","forecast","name","lat","lng")
merged = relocate(merged, where(is.numeric), .before = where(is.character))
merged = relocate(merged, lng)
return(merged)
}
#usage:
#weather = getWeatherForecast()
|
import fs from "fs";
import util from "util";
// readFileメソッドを同期的に処理する関数を定義
// 処理の結果をPromiseオブジェクトで受け取る
const promisifyReadfile = util.promisify(fs.readFile);
async function main() {
const readFilePromise = promisifyReadfile("package.json");
let fileContent: string = "Not loaded";
// then:Promiseで解決済みを確認してからcallbackが実行される
readFilePromise.then((data) => {
fileContent = data.toString();
console.log(fileContent);
});
// await:async関数内ではawait部分は解決済みを確認してから次の処理へ
const data = await promisifyReadfile("package.json");
fileContent = data.toString();
console.log(fileContent);
}
main();
|
# Simple calculator app
This project is part of Meta's "React Basics" course. They gave us a template to create a simple calculator app — and it's very, very simple. Baby, even. The functionality of the calculator isn't entirely there. For example, the steps to print the result for `1 + 15` are:
1. Type `1`.
2. Click `Add`. Your result updates to `1`.
3. Type `15`.
4. Click `Add` again. Your result updates to `16`.
If you press enter, though, the result resets back to `0`.
This is confusing. Let's look at what happens when we use the `multiply` and `divide` functionality. If I want to multiply `15 * 2`, the steps I would take are:
1. Input the number `15`.
2. Click `add`. This prints the result `15`.
3. Input the number `2`
4. Click `multiply``.
5. Result prints.
Given how simple this calculator is, it seems like the logic works like this:
* Result always defaults to 0.
* To complete a new operation, you have to add the value to the default 0, hence always needing to click `add` after your first input.
* If you want to multiply `15 * 2`, then the actual operation under the hood is `0 + 15 * 2`.
Obviously, you wouldn't want to use this app to do something financially urgent.
## Stylizing the app
I'm not a developer, but I do like making things cute. I spent more time stylizing the app itself than I did optimizing the actual app — I know, I know. But I figured since I completed the assignment, I could do something fun for me. You can look at my code comments to see how I grouped the different buttons and why I chose the formatting I did. There are some things I wanted to do that I wasn't able to.
* I wanted to make this a Sailor Mercury-themed calculator, hence the color palette.
* I had an image that I wanted to anchor behind the app component at the lower-right of the webpage. It was cute! It would've been cute!
* Since this app uses the `create-react-app`, which isn't supported afaik, I lacked ~things~ to make this happen. This might answer your question why I have so many packages installed. `0:-)`
* I tried different kinds of functions and CSS magic and yadda yadda, but the image only ever loaded in a broken way... if it didn't break the app altogether.
* Eventually, I accepted that if I want to make a cute webpage, then I should probably start my own project and move on from this one.
## The easy and the difficult
I'll admit that I initially struggled a bit with reading the template code. I use React at work so am familiar with different React ~things, but I have pretty limited JavaScript. I can edit existing JavaScript code, but a concrete understanding of what does what and why isn't entirely there. I grokked it, though. After I read through the template a few times, it clicked and realized I had overcomplicated the project too much, lol. Typical. The easiest part was then just filling in the blanks that Meta left for us to do. I also thought stylizing the calculator was pretty straight forward, too... I have a lot more HTML/CSS experience than I do anything else, though.
The other hard part for me was figuring out packages. Obviously `create-react-app` isn't the best to use. I also use VS Code and GitHub at work fairly often and wanted this work reflected in a repo. Breaking apart all the packages I needed and getting the preview to build was a huge headache. In any case, by the second or third try I figured it out and am pretty confident I know exactly what steps to take to start a new project in the future.
## Conclusion
Anyway, cheers: https://github.com/akristen/simple-calculator/blob/main/public/screenshot.png
|
<template>
<div class="tab-control">
<div v-for="(item,index) in titles" class="tab-control-item"
:class="{active: index === currentIndex}" @click="itemClick(index)">
<span>{{item}}</span>
</div>
</div>
</template>
<script>
export default {
name: "TabControl",
data() {
return {
currentIndex:0
}
},
props: {
titles: {
type: Array,
default() {
return []
}
}
},
methods: {
itemClick(item) {
this.currentIndex = item;
this.$emit('tabClick',item)
}
}
}
</script>
<style scoped>
.tab-control {
display: flex;
text-align: center;
height: 40px;
line-height: 40px;
font-size: 15px;
background-color: #fff;
z-index: 9;
}
.tab-control-item {
flex: 1;
}
.active span{
color: var(--color-high-text);
padding: 5px;
border-bottom: 2px solid var(--color-high-text);
}
</style>
|
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
public class SuperTable{
public static void main(String[] args) throws IOException {
// Instantiate Configuration class
Configuration config = HBaseConfiguration.create();
// Instaniate HBaseAdmin class
HBaseAdmin admin = new HBaseAdmin(config);
// Instantiate table descriptor class
HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf("powers"));
// Add column families to table descriptor
tableDescriptor.addFamily(new HColumnDescriptor("personal"));
tableDescriptor.addFamily(new HColumnDescriptor("professional"));
// Execute the table through admin
admin.createTable(tableDescriptor);
// Instantiating HTable class
HTable hTable = new HTable(config, "powers");
// Repeat these steps as many times as necessary
// Instantiating Put class
// Hint: Accepts a row name
// Add values using add() method
// Hints: Accepts column family name, qualifier/row name ,value
// Save the table
Put p1 = new Put(Bytes.toBytes("row1"));
p1.add(Bytes.toBytes("personal"), Bytes.toBytes("hero"), Bytes.toBytes("superman"));
p1.add(Bytes.toBytes("personal"), Bytes.toBytes("power"), Bytes.toBytes("strength"));
p1.add(Bytes.toBytes("professional"), Bytes.toBytes("name"), Bytes.toBytes("clark"));
p1.add(Bytes.toBytes("professional"), Bytes.toBytes("xp"), Bytes.toBytes("100"));
hTable.put(p1);
Put p2 = new Put(Bytes.toBytes("row2"));
p2.add(Bytes.toBytes("personal"), Bytes.toBytes("hero"), Bytes.toBytes("batman"));
p2.add(Bytes.toBytes("personal"), Bytes.toBytes("power"), Bytes.toBytes("money"));
p2.add(Bytes.toBytes("professional"), Bytes.toBytes("name"), Bytes.toBytes("bruce"));
p2.add(Bytes.toBytes("professional"), Bytes.toBytes("xp"), Bytes.toBytes("50"));
hTable.put(p2);
Put p3 = new Put(Bytes.toBytes("row3"));
p3.add(Bytes.toBytes("personal"), Bytes.toBytes("hero"), Bytes.toBytes("wolverine"));
p3.add(Bytes.toBytes("personal"), Bytes.toBytes("power"), Bytes.toBytes("healing"));
p3.add(Bytes.toBytes("professional"), Bytes.toBytes("name"), Bytes.toBytes("logan"));
p3.add(Bytes.toBytes("professional"), Bytes.toBytes("xp"), Bytes.toBytes("75"));
hTable.put(p3);
// Instantiate the Scan class
Scan scan = new Scan();
// Scan the required columns
scan.addColumn(Bytes.toBytes("personal"), Bytes.toBytes("hero"));
// Get the scan result
ResultScanner scanner = hTable.getScanner(scan);
// Read values from scan result
for (Result result = scanner.next(); result != null; result = scanner.next()) {
// Print scan result
System.out.println(result);
}
// Close the scanner
scanner.close();
// Close table
hTable.close();
}
}
|
/*
DDB is a wide column NoSQL database service that supports key-value and document data structures.
Public service - public internet, vpc with either an internet gateway or a gateway VPC endpoint.
DDB is a managed service, so you don't have to manage the underlying infrastructure unlike RDS or Aurora or Aurora Serverless.
Manual/Automatic provisioned performance IN/OUT or On-Demand. More Capacity means more speed. On-Demand charges per operation, Or manually provition writes and reads (WCU = 1KB/S) and (RCU = 4KB/S)
High Resilient - Across AZs or globally - default replications, backups, point in time recovery, encryption at rest.
Backups are similar to RDS manual Snapshots - Kept until deleted. Can use to restore(with or without indexes, anc can change encryption settings), or migrate.
Point-in-Time Recovery needs to be enabled on every table. Gives a 35 day continues replay to any point in time down to 1sec.
Event-Driven integration...do things when data changes
Tables are the base intitiy within the DB product, all items within a table have the same primary key, its like a one row relational table with infinite items. Tables can have secondary indexes called a composite key, or (sort key) So every item in the table needs to use the same primary key and have a unique value. If the primary is also a composite key, then the combination of the PK and SK need to be unique in that table.
Every Item can have additional data called attributes.
attributes can be the same. DDB is schemaless, so you can add attributes to an item at any time.
Items have to be less than 400KB
Access via CLI or API or Console UI
You can get a cheaper rate for long term storage commitments.
DynamoDB is eventually consistent by default.
You can use transactions to make multiple changes to multiple items in a single operation.
You can use conditional writes to make sure that an item has not been modified since you last read it.
You can use strong consistency to read the latest version of an item, but this incurs a performance penalty.
EG Operations:
- GetItem
- PutItem
- UpdateItem
- DeleteItem
- Query - a common way to retrieve data. only for pk or pk+sk. takes a single partition key, and optional SK or range. Capacity consumed is the size of all returned items.
- Scan - a more flexible least efficient operation, moves through a table consuming the capacity of every ITEM, but you can specity any attributes you want to match in the items, it scans the entire table for you to grab any little data.
When setting a table up it has two capacity modes:
- On-Demand - is simple but the cost can be 5times higher per r or w unit. Every operation consumes at least 1 r or w
- Provisioned - you set the capacity units per table, and you pay for what you use. You can scale up or down as needed.
- Every table has a burst pool of 300 seconds for r and w ops
Consistency refers to the process of how when data is updated and then imediately read, is that the updated data?
Can use two different consistency modes for read operations:
- Eventual Consistency - default, easier to implement returns the most recent data, eventually consistent after a short time. Scales better. half the cost of consumtion
- Strong (imediate) Consistency - returns a consistent copy of the data, but incurs a performance penalty and is more costly scales less well. Mandates reads from the leader node.
Data is replicated in 3 AZs default, each called a storage node. One is the leader.
Writes are always directed to the leader node.
Reads can be directed to any node, but the leader node is the only one that can return strong consistency.
If a operation consumes 2.5K average per item, it will round up to three WCU or RCU. Multiply that by operation per second to get requirements.
EG: 10 2.k items/Sec = 10 RCU/sec strong and 5 RCU at eventual consistency requirement.
Indexes are a way to improve data retrievel operations.
Query is most efficient but only works on one partition key at a time or a range of SK values. Indexes are alternative views on table data which allow the query operation to work in ways in otherwise couldnt.
DDB has two types of indexes:
Local Secondary Indexes (LSI) and Global Secondary Indexes (GSI)
LSI - can only be created at table creation time with 5 maximum per table, and can only be created on a table with a composite key (SK).
LSI allow for alternative SK's and shared capacity with the table
whereas with GSIs you can use alternative PK and SK.
For both, when creating them you have the ability to choose which attributes from the base table are projected into them - this can massively impact efficiency. You can choose all, keys_only, or include (specify explicitly)
In LSI The indexes let us easily limit the data that we retrieve while using the query operation. LSI Indexes are known as sparse indexes - meaning only items from the base table which have a value for the attribute that we define as the new sort key are present in the index.
GSI - can be created at any time, and can be created on a table with a single key. Limit of 20 per base table. They have their own RCU and WCU capacity values if you use provisioned capacity. Same choices of attributes to project as LSIs. GSIs are also sparse so only items which have values in the new PK and optional SK are added. GSIs are always eventually consistent because data is replicated from the base table to the index asynchronously.
Queries on attributes NOT projected are expensive.
AWS recomment GSIs as default and LSIs when only strong constistency is required. remember the term alternative access patterns
DynamoDB Streams are a 24 hour rolling window of time ordered change logs to ITEMS in a DynamoDB table
Streams have to be enabled on a per table basis, and have 4 view types
KEYS_ONLY - only records PK and optionally SK (we dont see what exactly was changed in that item)
NEW_IMAGE - stores the entire Item after the change(does not show what changed still)
OLD_IMAGE - can use to compare difference to current item in the table now
NEW_AND_OLD_IMAGES - provides before and after change image independent of actual data table. can calculate difference without consulting the actual DB
Streams can be used to trigger Lambda functions, or to send data to Kinesis Firehose or Kinesis Data Streams. DB Changes generate an event which contains the view type data.
Lambda can be integrated to provide trigger functionality - invoking when new entries are added on the stream.
- Also useful for reporting and analytics, aggregations, messaging, or notifications. Cost effective serverless architecture.
DAX is a fully managed, highly available, in-memory cache for DynamoDB. It should be your default choice for any DynamoDB caching related questions. Makes it easy to integrate data caching to your app.
DAX is not a public space service
Operates from within a VPC and is designed to be deployed into multiple AZs in that VPC to ensure HA. There is a primary cluster node with read/write and the others are read replicas.
Item Cache holds results of (Batch)GetItem. The query cache holds data based on query/scan params.
Dax is accessed much like RDS, every DAX cluster has an endpoint which is used to loadbalance accross the cluster
Write-Through is supported. write to DDB then DAX, all with single APIs
DAX delivers faster reads and reduced costs. Scales up or out (bigger instanc or more instances)
Not ideal for apps that require strongly consistent reads
DynamoDB Global Tables provides multi-master global replication of DynamoDB tables which can be used for performance, HA or DR/BC reasons. No single table is viewed as the master.
Create tables in various regions then unify them in a global table.
IF there's a data conflict the last writer wins.
Gererally sub-second replication between regions
Strongly consistent reads are only available in the region it is written to.
Amazon DynamoDB Time to Live (TTL) allows you to define a per-item timestamp to determine when an item is no longer needed. Shortly after the date and time of the specified timestamp, DynamoDB deletes the item from your table without consuming any write throughput. TTL is provided at no extra cost as a means to reduce stored data volumes by retaining only the items that remain current for your workload’s needs
Enabled per table basis. One process compates times and moves to expired. Another process later deletes expired items, for free.
You can configure a stream on the TTL processes to generate events with a 24 hour window
Elasticache is a managed in-memory cache which provides a managed implementation of the redis or memcached engines.
its useful for read heavy workloads, scaling reads in a cost effective way and allowing for externally hosted user session state (useful for serverless apps). storing external session data allows the app to be built in a stateless way which is beyond HA and now faulttolerant.
Elasticache is a managed service, so you dont have to worry about patching, backups, or scaling.
Elasticache is a shared cache, so you can have multiple clients accessing the same cache.
Elasticache is a distributed cache, so you can have multiple nodes in a cluster, and the cache is distributed across all nodes.
Implementation requires changes to your application code.
Redis supports more advanced types of data than memcached, such as lists, sets, sorted sets, hashes, bit arrays and more. Redis also supports multi-AZ replication which improves read scales and resiliency. memcache does sharding to multiple nodes but not quite the same.
Redis also supports back-up and restore, memcache dont.
Memcached is multithreaded so it can take better advantage of multi core CPUs whereas redis is transaction based, better consistency requirements.
Instance types and sizes are available in elasticache.
*/
|
<?php
namespace Tests\Functional\Domain\Record\Tackle\Command;
use App\Domain\Record\Tackle\Command\TackleBrand\DeleteTackleBrandCommand;
use Doctrine\Common\DataFixtures\ReferenceRepository;
use Tests\DataFixtures\ORM\Record\LoadTackles;
use Tests\Functional\ValidationTestCase;
/**
* @group tackle
* @group tackle-brand
*/
class DeleteTackleBrandCommandValidationTest extends ValidationTestCase
{
/** @var ReferenceRepository */
private $referenceRepository;
protected function setUp(): void
{
parent::setUp();
$this->referenceRepository = $this->loadFixtures([
LoadTackles::class,
])->getReferenceRepository();
}
protected function tearDown(): void
{
unset($this->referenceRepository);
parent::tearDown();
}
public function testNotEmptyTackles(): void
{
$tackle = $this->referenceRepository->getReference(LoadTackles::getRandReferenceName());
$command = new DeleteTackleBrandCommand($tackle->getBrand());
$this->getValidator()->validate($command);
$this->assertFieldInvalid('emptyTackles', 'Нельзя удалить бренд, для которого существует снасть.');
}
}
|
import { useState, useEffect } from "react";
function Counter() {
const [count, setCount] = useState(0); // step 1 --> initialize state variables
useEffect(()=>{
console.log('count', count)
}, [count])
return (
// step 2 --> render what is inside the return statement
<div className="Counter">
<h2>Counter</h2>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count - 1)}> - </button>
<button onClick={() => setCount(count + 1)}> + </button>
</div>
);
}
export default Counter;
|
<% provide(:title, 'Log-in')%>
<section class="sign_in_up">
<div class="auth_form_wrapper">
<div class="cover_deco_auth">
<%= image_tag(asset_path("default.jpg")) %>
</div>
<div class="form_header">
<h1>LOG-IN</h1>
</div>
<div class="auth_form">
<div class="form_container">
<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
</div>
<div class="field">
<%= f.label :password %><br />
<%= f.password_field :password, autocomplete: "current-password" %>
</div>
<% if devise_mapping.rememberable? %>
<div class="field">
<%= f.label :remember_me %>
<%= f.check_box :remember_me %>
</div>
<% end %>
<div class="actions">
<%= f.submit "Log in" %>
</div>
<% end %>
<div class="links">
<p><%= render "users/shared/links" %></p>
</div>
</div>
</div>
</div>
</section>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iivari Rantala</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="mediaqueries.css">
</head>
<body>
<nav id="desktop-nav">
<div class="logo">Iivari Rantala</div>
<h1 id="current-time"></h1>
<div>
<ul class="nav-links">
<li><a href="#about">About</a></li>
<li><a href="#experience">Experience</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</nav>
<nav id="hamburger-nav">
<div class="logo">Iivari Rantala</div>
<div class="hamburger-menu">
<div class="hamburger-icon" onclick="toggleMenu()">
<span></span>
<span></span>
<span></span>
</div>
<div class="menu-links">
<li><a href="#about" onclick="toggleMenu()">About</a></li>
<li><a href="#experience" onclick="toggleMenu()">Experience</a></li>
<li><a href="#projects" onclick="toggleMenu()">Projects</a></li>
<li><a href="#contact" onclick="toggleMenu()">Contact</a></li>
</div>
</div>
</nav>
<!--<section id="weather-clock">
<div class="time-container">
</div>-->
</section>
<section id="profile">
<div class="section__pic-container">
<img src="./assets/profiilikuva.png" alt="Iivari Rantala profile picture">
</div>
<div class="section__text">
<p class="section__text__p1">Hello I'm</p>
<h1 class="title">Iivari Rantala</h1>
<p class="section__text__p2">Software Engineering Student</p>
<div class="btn-container">
<button class="btn btn-color-2" onclick="window.open('./assets/CV-Iivari-Rantala.pdf')">Download CV</button>
<button class="btn btn-color-1" onclick="location.href='./#contact'">Contact Info</button>
</div>
<div id="socials-container">
<img src="./assets/linkedin.png" alt="My LinkedIn Profile" class="icon" onclick="location.href='https://www.linkedin.com/in/iivari-rantala-8a6273260/?locale=es_ES'">
<img src="./assets/git.png" alt="My Github Profile" class="icon" onclick="location.href='https://github.com/iivarirantala'">
<img src="./assets/insta.png" alt="My Instagram Profile" class="icon" onclick="location.href='https://www.instagram.com/iivarirantala/'">
</div>
</div>
</section>
<section id="about">
<p class="section__text__p1">Get To Know More</p>
<h1 class="title">About Me</h1>
<div class="section-container">
<div class="section__pic-container">
<img src="./assets/about-pic.png" alt="Profile picture" class="about-pic">
</div>
<div class="about-details-container">
<div class="about-containers">
<div class="details-container">
<img src="./assets/experience.png" alt="Experience icon" class="icon">
<h3>Experience</h3>
<p>4+ years <br />Job Experience In Different Fields</p>
</div>
<div class="details-container">
<img src="./assets/education.png" alt="Education icon" class="icon">
<h3>Education</h3>
<p>High School Diploma <br />2nd Year Student In Software Engineering</p>
</div>
</div>
<div class="text-container">
<p>Hey there! I'm Iivari, a 21-year-old with a variety of interests that keep life interesting. I'm a big fan of video games, they're my go-to when I want to unwind and have some fun. You can often find me at the gym, working on my physique and staying active.
I also have a deep love for music and play the piano. It's a great way for me to express myself and unwind after a long day. Videography is another one of my passions, and I love capturing the world's moments through the lens of a camera.
And of course, I'm a car enthusiast. There's just something about the power and design of cars that fascinates me. Whether it's tinkering with them or just admiring them, cars have a special place in my heart.
</p>
</div>
</div>
</div>
<img src="./assets/arrow.png" alt="Arrow icon" class="icon arrow" onclick="location.href='./#experience'"/>
</section>
<section id="experience">
<p class="section__text__p1">Explore My</p>
<h1 class="title">Experience</h1>
<div class="experience-details-container">
<div class="about-containers">
<div class="details-container">
<h2 class="experience-sub-title">Frontend Development</h2>
<div class="article-container">
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon"/>
<div>
<h3>HTML</h3>
<p>Intermediate</p>
</div>
</article>
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon"/>
<div>
<h3>CSS</h3>
<p>Intermediate</p>
</div>
</article>
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon"/>
<div>
<h3>JavaScript</h3>
<p>Basic</p>
</div>
</article>
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon"/>
<div>
<h3>TypeScript</h3>
<p>Basic</p>
</div>
</article>
</div>
</div>
<div class="details-container">
<h2 class="experience-sub-title">Backend Development</h2>
<div class="article-container">
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon"/>
<div>
<h3>C++</h3>
<p>Intermediate</p>
</div>
</article>
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon"/>
<div>
<h3>SQL</h3>
<p>Intermediate</p>
</div>
</article>
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon"/>
<div>
<h3>Java</h3>
<p>Intermediate</p>
</div>
</article>
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon"/>
<div>
<h3>Git</h3>
<p>Intermediate</p>
</div>
</article>
</div>
</div>
</div>
</div>
<img src="./assets/arrow.png" alt="Arrow icon" class="icon arrow" onclick="location.href='./#projects'"/>
</section>
<section id="projects">
<p class="section__text__p1">Browse My Recent</p>
<h1 class="title">Projects</h1>
<div class="experience-details-container">
<div class="about-containers">
<div class="details-container color-container">
<div class="article-container">
<img src="./assets/sc2.jpg" alt="Project 1" id="img" class="project-img" onmouseover="increase()" onmouseout="decrease()"/>
</div>
<h2 class="experience-sub-title project-title">Project One</h2>
<div class="btn-container">
<button class="btn btn-color-2 project-btn" onclick="location.href='https://github.com/banksimul-2023-22spo/group_8/tree/main'">
Github
</button>
</div>
</div>
<div class="details-container color-container">
<div class="article-container">
<img src="./assets/sc3.png" alt="Project 2" class="project-img"/>
</div>
<h2 class="experience-sub-title project-title">Project Two</h2>
<div class="btn-container">
<button class="btn btn-color-2 project-btn" onclick="location.href='https://github.com/iivarirantala/Web-Page'">
Github
</button>
</div>
</div>
</div>
</div>
<img src="./assets/arrow.png" alt="Arrow icon" class="icon arrow" onclick="location.href='./#contact'"/>
</section>
<section id="contact">
<p class="section__text__p1">Get in Touch</p>
<h1 class="title">Contact Me</h1>
<div class="contact-info-upper-container">
<div class="contact-info-container">
<img src="./assets/email.png" alt="Email icon" class="icon contact-icon email-icon"/>
<p><a href="mailto:rantalaiivari@gmail.com">rantalaiivari@gmail.com</a></p>
</div>
<div class="contact-info-container">
<img src="./assets/linkedin.png" alt="LinkedIn icon" class="icon contact-icon"/>
<p><a href="https://www.linkedin.com/in/iivari-rantala-8a6273260/?locale=es_ES">LinkedIn</a></p>
</div>
</div>
</section>
<footer>
<nav>
<div class="nav-links-container">
<ul class="nav-links">
<li><a href="#about">About</a></li>
<li><a href="#experience">Experience</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</nav>
<p>Copyright © 2023 Iivari Rantala. All Rights Reserved.</p>
</footer>
<script src="script.js"></script>
</body>
</html>
|
<template>
<section>
<h1>Välkommen!</h1>
<form action="">
<h2>Vad är ditt kön?</h2>
<input type="radio" id="g0" value="male" v-model="gender" />
<label for="g0">{{ genders[0] }}</label><br />
<input type="radio" id="g1" value="female" v-model="gender" />
<label for="g1">{{ genders[1] }}</label><br />
<input type="radio" id="g2" value="other" v-model="gender" />
<label for="g2">{{ genders[2] }}</label><br />
</form>
<form action="">
<h2>Hur gammal är du?</h2>
<input type="radio" id="a0" value="14-" v-model="age" />
<label for="a0">{{ ages[0] }}</label><br />
<input type="radio" id="a1" value="15-17" v-model="age" />
<label for="a1">{{ ages[1] }}</label><br />
<input type="radio" id="a2" value="18-20" v-model="age" />
<label for="a2">{{ ages[2] }}</label><br />
<input type="radio" id="a3" value="21-25" v-model="age" />
<label for="a3">{{ ages[3] }}</label><br />
<input type="radio" id="a4" value="26-35" v-model="age" />
<label for="a4">{{ ages[4] }}</label><br />
<input type="radio" id="a5" value="36+" v-model="age" />
<label for="a5">{{ ages[5] }}</label><br />
<input type="radio" id="a6" value="other" v-model="age" />
<label for="a6">{{ ages[6] }}</label><br />
</form>
<!-- <p class="debug">{{ gender }}, {{ age }}</p>
<p class="debug">userId: {{ userId }}</p>
<button @click="clear()" class="debug">clear localStorage</button> -->
<a href="#/intro">
<button @click="send()">Nästa</button>
</a>
</section>
</template>
<script>
import shared from "../main.js";
export default {
name: "Main",
data() {
return {
genders: ["Man", "Kvinna", "Annat/Svara ej"],
ages: [
"Yngre än 14",
"15-17",
"18-20",
"21-25",
"26-35",
"Äldre än 36",
"Svara ej",
],
gender: "other",
age: "other",
userId: localStorage.getItem('userId'),
};
},
methods: {
async send() {
if (localStorage.getItem('userId') === null) {
localStorage.setItem('userId', makeid(8));
}
await shared.setDoc(shared.doc(shared.db, 'users', localStorage.getItem('userId')), {
gender: this.gender,
age: this.age,
},
{ merge: true });
this.gender = "other";
this.age = "other";
this.userId = localStorage.getItem('userId');
},
clear() {
localStorage.clear();
this.userId = localStorage.getItem('userId');
},
},
};
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
</script>
|
import { useLoaderData } from "react-router-dom";
import Swal from 'sweetalert2'
const UpdateCraft = () => {
const updatedata = useLoaderData();
const handelUpdate = (e) => {
e.preventDefault();
const form = e.target;
const name = form.name.value;
const image = form.image.value;
const subcategory_Name = form.subcategory_Name.value;
const price = form.price.value;
const rating = form.rating.value;
const customization = form.customization.value;
const times = form.times.value;
const stock_status = form.stock_status.value;
const description = form.description.value;
const infos = {
name,
image,
subcategory_Name,
price,
rating,
customization,
times,
stock_status,
description
};
fetch(`https://ruhit-server.vercel.app/update/${updatedata._id}`, {
method : "PATCH",
headers : {
"content-type" : "application/json"
},
body : JSON.stringify(infos)
})
.then((res)=> res.json())
.then((data)=> {
if(data.modifiedCount === 1){
Swal.fire({
title: 'Success!',
text: 'Update Successfull',
icon: 'success',
confirmButtonText: 'Ok'
})
}
})
};
return (
<div>
<div className="container mx-auto px-[20px] my-[100px]">
<div className="lg:w-[70%] mx-auto bg-blue-300 p-[20px]">
<h2 className="text-3xl text-center font-[600] mb-[20px]">
Update Product
</h2>
<form onSubmit={handelUpdate}>
<div className="">
<div className="lg:flex gap-[25px] mb-[10px]">
<div className="flex-1">
<label htmlFor=""> Name</label>
<input
defaultValue={updatedata.name}
className="w-full p-[10px]"
name="name"
type="text"
placeholder="Name"
/>
</div>
<div className="flex-1">
<label htmlFor=""> Image Url</label>
<input
defaultValue={updatedata.image}
className="w-full p-[10px]"
name="image"
type="text"
placeholder="Image Url"
/>
</div>
</div>
<div className="lg:flex gap-[25px]">
<div className="flex-1">
<label>Subcategory Name</label>
<select
className="w-full p-[10px]"
defaultValue={updatedata.subcategory_Name}
name="subcategory_Name"
>
<option>--Select--</option>
<option value="card_Making">Card Making</option>
<option value="scrapbooking">Scrapbooking</option>
<option value="paper_Quilling">
{" "}
Paper Quilling & origami
</option>
<option value="glass_Painting"> Glass Painting</option>
<option value="lampworking">Lampworking</option>
<option value="glass_Dying">Glass Dying & Staining</option>
</select>
</div>
<div className="flex-1">
<label htmlFor=""> Price</label>
<input
defaultValue={updatedata.price}
className="w-full p-[10px]"
name="price"
type="text"
placeholder="Price"
/>
</div>
</div>
<div className="lg:flex gap-[25px] mb-[10px]">
<div className="flex-1">
<label htmlFor=""> Rating</label>
<input
defaultValue={updatedata.rating}
className="w-full p-[10px]"
name="rating"
type="text"
placeholder="Rating"
/>
</div>
<div className="flex-1">
<label>Customization:</label>
<select
className="w-full p-[10px]"
defaultValue={updatedata.customization}
name="customization"
>
<option>--Select--</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</div>
<div className="lg:flex gap-[25px] mb-[10px]">
<div className="flex-1">
<label htmlFor="">Processing Time</label>
<input
defaultValue={updatedata.times}
className="w-full p-[10px]"
name="times"
type="text"
placeholder="Processing Time"
/>
</div>
<div className="flex-1">
<label>Stock Status</label>
<select
className="w-full p-[10px]"
defaultValue={updatedata.stock_status}
name="stock_status"
>
<option>--Select--</option>
<option value="In stock">In stock</option>
<option value="Made to Order">Made to Order</option>
</select>
</div>
</div>
<div>
<label htmlFor="">Description</label>
<textarea
defaultValue={updatedata.description}
className="w-full p-[10px]"
placeholder="Description"
name="description"
id=""
cols="30"
rows="5"
></textarea>
</div>
<div className="mt-[10px]">
<button className="w-full py-[10px] bg-blue-900 text-white">
Update
</button>
</div>
</div>
</form>
</div>
</div>
</div>
);
};
export default UpdateCraft;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha384-... (laissé à titre indicatif) ..." crossorigin="anonymous">
<title>Site web code warriors</title>
<!-- Bootstrap core CSS -->
<link href="{{asset('vendor/bootstrap/css/bootstrap.min.css')}}" rel="stylesheet">
<!-- Additional CSS Files -->
<link rel="stylesheet" href="{{asset('assets/css/fontawesome.css')}}">
<link rel="stylesheet" href="{{asset('assets/css/templatemo-digimedia-v1.css')}}">
<link rel="stylesheet" href="{{asset('assets/css/animated.css')}}">
<link rel="stylesheet" href="{{asset('assets/css/owl.css')}}">
<style>
.ff {
display: flex;
justify-content: center;
}
input[type="email"] {
background-color: #f7f7f7;
border: 1px solid #ccc;
font-size: 16px;
margin-right: 20px;
width: 552px;
height: 42px;
top: 29px;
left: 370px;
padding: 11px 404px 11px 25px;
border-radius: 50px;
}
button[type="submit"] {
background-color: #9747FF;
color: #fff;
border: none;
font-size: 16px;
cursor: pointer;
min-width: 132px;
min-height: 42px;
top: 29px;
left: 972px;
padding: 11px 45px 11px 46px;
border-radius: 49px;
}
section {
margin-top: 50px;
background-color: #9747FF;
color: #fff;
padding: 20px 0;
font-family: 'Poppins', sans-serif;
}
.conteneur {
max-width: 1200px;
margin: 0 auto;
display: flex;
height:350px;
justify-content: space-between;
background-color: #9747FF;
margin-top:80px;
margin-left: 70px;
}
.conteneur img {
width: 253px;
height: 150px;
margin-top: 60px;
margin-left: -50px;
margin-right: 60px;
}
.categories,
.ressources,
.contact {
width: 33.33%;
margin-left: 30px;
}
#h22 {
margin-bottom: 10px;
color: black;
font-size: 24px;
font-weight: 700;
line-height: 30px;
letter-spacing: 0em;
text-align: left;
}
ul {
list-style: none;
padding: 0;
margin-top: 50px;
}
li {
margin-bottom: 15px;
font-size: 16px;
font-weight: 600;
}
a {
color: black;
text-decoration: none;
}
.copyright p{
font-size: 12px;
font-weight: 600;
line-height: 22px;
letter-spacing: 0.07038461416959763px;
text-align: center;
color: white;
}
@media (max-width: 768px) {
.conteneur {
flex-direction: column;
}
.categories,
.ressources,
.contact {
width: 100%;
}
}
button:hover {
background-color: purple;
}
</style>
</head>
<body>
<!-- ***** Preloader Start ***** -->
<div id="js-preloader" class="js-preloader">
<div class="preloader-inner">
<span class="dot"></span>
<div class="dots">
<span></span>
<span></span>
<span></span>
</div>
</div>
</div>
<!-- ***** Preloader End ***** -->
<!-- Pre-header Starts -->
<!-- Pre-header End -->
<!-- ***** Header Area Start ***** -->
<header class="header-area header-sticky wow slideInDown" data-wow-duration="0.75s" data-wow-delay="0s">
<div class="container">
<div class="row">
<div class="col-12">
<nav class="main-nav">
<!-- ***** Logo Start ***** -->
<a href="index.html" class="logo">
<img style="padding: 22px;" src="{{asset('assets/images/logo.png')}}" alt="">
</a>
<!-- ***** Logo End ***** -->
<!-- ***** Menu Start ***** -->
<ul class="nav">
<li><a href="/" >Home</a></li>
<li style="margin-top: -8px;" class="nav-item dropdown">
<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
Categories
</a>
<div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
@foreach( app("App\Http\Controllers\categoryController")->categories() as $category)
<a class="dropdown-item" href="{{ route('blog.categories', $category) }}">{{ $category->nom}}</a>
@endforeach
</div>
</li>
<li><a href="{{ route('blog.articls') }}">Articles</a></li>
<li><a href="/Blog/tips">Tips</a></li>
<li style="margin-top: -8px;" class="nav-item dropdown">
<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
Questions
</a>
<div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{{ route('allQuestions') }}" >
All Questions
</a>
@auth
<a class="dropdown-item" href="{{ route('gotoaddQuestion', ['id' => Auth::user()->id]) }}" >
Ask Question
</a>
<a class="dropdown-item" href="{{ route('FilterMyQuestions', ['id' => Auth::user()->id]) }}" >
My Questions
</a>
@endauth
</div>
</li>
<li><a href="{{ route('getfaqs') }}">FAQ</a></li>
<li><a href="{{ route('showAllpolicies') }}">Policies</a></li>
<li>
<div class="border-first-button">
@guest
@if (Route::has('login'))
<div class="sm:fixed sm:top-0 sm:right-0 p-6 text-right z-10">
@auth
<a href="{{ url('.') }}" class="font-semibold text-gray-600 dark:text-gray-400 focus:outline focus:outline-2 focus:rounded-sm focus:outline-red-500">Home</a>
@else
<a href="{{ route('login') }}" class="border-first-button-SignIn">Sign In</a>
@if (Route::has('register'))
<a href="{{ route('register') }}" class="border-first-button-SignUp">Sign Up</a>
@endif
@endauth
</div>
@endif
@else
@if(Auth::user()->is_admin == 0)
<li class="nav-item dropdown">
<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
<img src="{{ asset('storage/' . Auth::user()->photo) }}" alt="profile" class="me-2" style="width: 30px; height: 30px; border-radius: 50%;">
{{ Auth::user()->name }}
</a>
<div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="/editprofile">{{ __('Edit profile') }}</a>
<a class="dropdown-item" href="{{ route('user.profile', ['user_id' => Auth()->user()->id]) }}">{{ __('View profile') }}</a>
<a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
{{ __('Logout') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none ff">
@csrf
</form>
</div>
</li>
@else
<script>window.location = "{{ route('admin.homeadmin') }}";</script>
@endif
@endguest
</div>
</li>
</ul>
<!-- <a class='menu-trigger'>
<span>Menu</span>
</a>
***** Menu End ***** -->
</nav>
</div>
</div>
</div>
</header>
<!-- ***** Header Area End ***** -->
@yield('content')
<section>
<div class="conteneur">
<div>
<img src="{{asset('assets/images/logo1.png')}}" alt="">
</div>
<div class="categories">
<h2 id="h22">Categories</h2>
<ul>
@foreach( app("App\Http\Controllers\categoryController")->categories() as $category)
<li><a href="{{ route('blog.categories', $category) }}">{{ $category->nom}}</a></li>
@endforeach
</ul>
</div>
<div class="ressources">
<h2 id="h22">Ressources</h2>
<ul>
<li><a href="https://stackoverflow.com/">Stackoverflow</a></li>
<li><a href="https://www.udemy.com/fr/">Udemy</a></li>
<li><a href="https://www.coursera.org/">Coursera</a></li>
</ul>
</div>
<div class="contact">
<h2 id="h22">Contact</h2>
<ul>
<ul>
@foreach(app("App\Http\Controllers\SocialNetworkController")->getAllSocial() as $socialwork)
<li>
<a style="margin-left: 10px;" href="{{ $socialwork->link }}">
{!! $socialwork->icon !!} {{ $socialwork->link }}
</a>
</li>
@endforeach
</ul>
<ul style="display: flex; ">
@foreach(app("App\Http\Controllers\SocialNetworkController")->getAllSocial() as $socialwork)
<li>
<a style="margin-left: 10px;" href="{{ $socialwork->link }}">
{!! $socialwork->icon !!}
</a>
</li>
@endforeach
</ul>
</ul>
</div>
</div>
<div class="copyright">
<p>© Copy Rights ENET Com Junior Entreprise</p>
</div>
</section>
<script src="{{asset('vendor/jquery/jquery.min.js')}}"></script>
<script src="{{asset('vendor/bootstrap/js/bootstrap.bundle.min.js')}}"></script>
<script src="{{asset('assets/js/owl-carousel.js')}}"></script>
<script src="{{asset('assets/js/animation.js')}}"></script>
<script src="{{asset('assets/js/imagesloaded.js')}}"></script>
<script src="{{asset('assets/js/custom.js')}}"></script>
</body>
</html>
|
#[allow(unused_imports)]
use std::io::{BufWriter, stdin, stdout, Write};
#[derive(Default)]
struct Scanner {
buffer: Vec<String>
}
impl Scanner {
fn next<T: std::str::FromStr>(&mut self) -> T {
loop {
if let Some(token) = self.buffer.pop() {
return token.parse().ok().expect("Failed parse");
}
let mut input = String::new();
stdin().read_line(&mut input).expect("Failed read");
self.buffer = input.split_whitespace().rev().map(String::from).collect();
}
}
}
fn main() {
let mut scan = Scanner::default();
let out = &mut BufWriter::new(stdout());
// Write code here
let w: i32 = scan.next();
if w % 2 == 0 && w > 2 {
writeln!(out, "YES").ok();
} else {
writeln!(out, "NO").ok();
}
}
|
import LineChart from '@/components/Charts/LineChart'
import React,{useState,useEffect} from 'react'
import PieChart from '@/components/Charts/PieChart'
function Stats({users}) {
const [catStat, setCatStat] = useState(null)
const [userData, setUserData] = useState()
const userStat = async (user) =>{
const response = await fetch(`/api/users/user/${user}`)
const datas = await response.json()
//console.log(datas)
setUserData({
labels: datas[0].map((data)=>data.Year+':'+ data.Month),
datasets: [{
label: "Posts",
data: datas[0].map((data) => data.PostCount),
backgroundColor: "purple",
borderColor: "purple",
borderWidth: 1,
},{
label: "Likes",
data: datas[1].map((data) => data.LikeCount),
backgroundColor: "blue",
borderColor: "blue",
borderWidth: 1,
},{
label: "Views",
data: datas[2].map((data) => data.ViewCount),
backgroundColor: "red",
borderColor: "red",
borderWidth: 1,
}]
})
}
const catSubStat = async (user) =>{
const response = await fetch(`/api/users/cat/${user}`)
const resp = await response.json()
const datas = resp[1]
if(resp[0][0].SubCount !== 0){
setCatStat({
labels: datas.map((data)=>data.Category),
datasets: [{
label: "Categories",
data: datas.map((data) => data.SubscriberCount),
backgroundColor: ["purple","red","gray","green","blue"],
borderColor: ["purple","red","gray","green","blue"],
borderWidth: 1,
}]
})
}
}
useEffect(() => {
if(users){
catSubStat(users.ID)
userStat(users.ID)
}
}, [users])
return (
<>
<div className="stat flex flex-wrap space-y-2 mt-5 md:flex-row md:justify-between md:h-[350px] bg-white rounded-3xl">
{userData && (<LineChart chartData={userData} />) }
{catStat && (<PieChart chartData={catStat} />)}
</div>
</>
)
}
export default Stats
|
#include <iostream>
#include <cmath>
#include <chrono>
#include "NewtonCotesFormulas.h"
#include "NewtonCotesFactory.h"
//#include "func.cpp"
using namespace std;
// timer
unsigned int stopwatch()
{
static auto start_time = chrono::steady_clock::now();
auto end_time = chrono::steady_clock::now();
auto delta = chrono::duration_cast<chrono::microseconds>(end_time - start_time);
start_time = end_time;
return delta.count();
}
//struct funcToIntegrate;
//struct funcToIntegrate {
// double operator()(double x) {
// return sqrt(x) + exp(-x);
// }
//};
double func(double x) {
return sqrt(x) * exp(-x);
//return pow(x, 2.5) / (1 + x * x);
}
int main()
{
cout << "Choose method:\n"
<< "Midpoint numeric quadrature -----> (1)\n"
<< "Trapezoidal numeric quadrature --> (2)\n"
<< "Simpson's numeric quadrature ----> (3)\n" << endl;
// int choice;
// cin >> choice;
// while (choice < 1 || choice > 3) {
// cout << "Pick again a number from 1 to 3\n";
// cin >> choice;
// }
stopwatch();
NewtonCotesFactory creator;
for (int choice : {1,2,3}) {
NewtonCotesFormulas* rule = creator.createQuadrature(choice, 1, 3, 0.000001);
//NewtonCotesFormulas* rule = creator.createQuadrature(choice, 0, 1, 0.00000000001);
double result = rule->printConvergenceValues(4, &func);
cout << "Final result within tolerance: " << result << endl << endl;
delete rule;
}
cout << "Performance time: " << stopwatch() << " microseconds.\n\n";
return 0;
}
|
"use client"
import React, { useState } from 'react'
import DropDown from 'react-dropdown';
import { CommitteeMember } from "@/constants/types"
import MMNContainer from '@/components/MMNContainer';
import MMNTitle from '@/components/MMNTItle';
import TopNav from '@/components/TopNav';
import LinesEllipsis from 'react-lines-ellipsis'
import Image from "next/image";
import { Urls } from '@/constants';
const NavData = [
{ title: "Home", link: "/home" },
{ title: "About us", link: "/aboutus" },
{ title: "Committee Members", link: "#" },
];
const yearList = [
{ value: '2020', label: "2020-2022" },
{ value: '2018', label: "2018-2020" },
];
const data = {
executive: [
{ name: "Member name , Member name, Member name, Member name,Member name, Member name, Member name", imageurl: "/image/members/executive/member1.jpg" },
{ name: "Member name", imageurl: "/image/members/executive/member2.jpg" },
{ name: "Member name", imageurl: "" },
{ name: "Member name", imageurl: "" },
{ name: "Member name", imageurl: "" },
{ name: "Member name", imageurl: "" },
{ name: "Member name", imageurl: "" },
{ name: "Member name", imageurl: "" },
{ name: "Member name", imageurl: "" },
],
working: [
{ name: "Member name 1", imageurl: "", period: { begin: 2018, end: 2020 } },
{ name: "Member name 2", imageurl: "", period: { begin: 2019, end: 2021 } },
{ name: "Member name 6", imageurl: "", period: { begin: 2018, end: 2019 } },
{ name: "Member name 4", imageurl: "", period: { begin: 2018, end: 0 } },
{ name: "Member name 8", imageurl: "", period: { begin: 2021, end: 0 } },
{ name: "Member name 7", imageurl: "", period: { begin: 2021, end: 2022 } },
{ name: "Member name 3", imageurl: "", period: { begin: 2018, end: 0 } },
]
}
const memberCard = (member: CommitteeMember) => {
let title = member.name;
if (member.period) {
// title += `\n(${member.period.begin} - ${member.period.end <= 0 ? 'Now' : member.period.end})`
}
return (
<div className='flex flex-col gap-[10px] cursor-pointer'>
<div className='w-[211px] h-[211px] bg-[#F0F0F0] rounded-[10px] flex justify-center items-center p-[25px]'>
<Image
src={member.imageurl || Urls.DefaultMemberImage}
alt={title}
width={0}
height={0}
sizes="100vw"
className="z-[1] h-full w-auto p-[5px]"
/>
</div>
<div className='text-center line-height-mmn-large font-poppins font-medium max-w-[211px] whitespace-break-spaces'>
<LinesEllipsis
text={title}
maxLine='2'
ellipsis='...'
trimRight={true}
basedOn='letters'
/>
</div>
</div>
)
}
const memberList = (members: CommitteeMember[]) => {
return (
<div className='flex gap-[30px] flex-wrap justify-center sm:justify-start'>
{
members.map((member, index) => {
return (
<div className='flex gap-[30px]' key={`committee-${index}`} title={member.name}>
{memberCard(member)}
</div>
)
})
}
</div>
)
}
const CommitteeMemberPage = () => {
const [beginYear, setBeginYear] = useState(2020);
const currentWorkingMembers = data.working.filter((member) => {
if (!member.period || isNaN(beginYear)) return false;
const mbeginyear = member.period.begin, mendyear = member.period.end;
const endyear = beginYear + 2;
if (mbeginyear > mendyear && mendyear > 0) return false;
return (mbeginyear < endyear) && (mendyear <= 0 || mendyear >= beginYear);
});
const exeMemberList = memberList(data.executive);
const workingMemberList = memberList(currentWorkingMembers);
return (
<div className='max-w-[1440px] m-auto'>
<TopNav itemList={NavData} />
<div className="flex flex-col sm:px-[90px] px-5 gap-[30px] pb-[40px] text-size-mmn-medium">
<MMNTitle title={"Executive committee members"} className={""} color='purple' />
{exeMemberList}
</div>
<div className="flex flex-col sm:px-[90px] px-5 gap-[30px] pb-[40px] text-size-mmn-medium">
<div className='flex gap-[20px] flex-wrap'>
<MMNTitle title={"Working committee members"} className={""} color='purple' />
<DropDown options={yearList}
className='w-fit'
controlClassName="text-size-mmn-medium font-semibold line-height-mmn-medium text-color-mmn-yellow !rounded-[6px] !pl-[12px] !pr-[32px] bg-[#FFEDEA] !border-none cursor-pointer"
menuClassName='text-size-mmn-medium font-semibold line-height-mmn-medium border-none '
arrowClassName='top-[18px] right-[10px]'
value={`${beginYear}`}
onChange={(e) => { setBeginYear(Number(e.value)) }}
placeholder={"Select Year"} />
</div>
{workingMemberList}
</div>
</div>
)
}
export default CommitteeMemberPage
|
#include "MyVector2.hpp"
using namespace MyPhysics;
using namespace std;
//* ╔═══════════════════════════════╗
//* ║ Constructors & Deconstructors ║
//* ╚═══════════════════════════════╝
MyVector2::MyVector2() : x(0), y(0){};
MyVector2::MyVector2(double xy) : x(xy), y(xy){};
MyVector2::MyVector2(double x, double y) : x(x), y(y){};
MyVector2::MyVector2(glm::vec2 xy) : x(xy.x), y(xy.y) {}
//* ╔═════════╗
//* ║ Methods ║
//* ╚═════════╝
void MyVector2::DisplayValuesIndividually(std::string message, int precision) {
cout << fixed << setprecision(precision) << message << " -> " << "X: " << this->x << ", Y: " << this->y
<< endl;
}
void MyVector2::DisplayValues(int precision) {
cout << fixed << setprecision(precision) << "(" << this->x << ", " << this->y << ")";
}
//? Vector Operations
MyVector2 MyVector2::operator+(const MyVector2 addend) {
return MyVector2(this->x + addend.x, this->y + addend.y);
}
void MyVector2::operator+=(const MyVector2 addend) {
this->x += addend.x;
this->y += addend.y;
}
MyVector2 MyVector2::operator-(const MyVector2 subtrahend) {
return MyVector2(this->x - subtrahend.x, this->y - subtrahend.y);
}
void MyVector2::operator-=(const MyVector2 subtrahend) {
this->x -= subtrahend.x;
this->y -= subtrahend.y;
}
MyVector2 MyVector2::operator*(const double multiplicand) {
return MyVector2(this->x * multiplicand, this->y * multiplicand);
}
void MyVector2::operator*=(const double multiplicand) {
this->x *= multiplicand;
this->y *= multiplicand;
}
MyVector2 MyVector2::operator*(const MyVector2 multiplicand) {
return MyVector2(this->x * multiplicand.x, this->y * multiplicand.y);
}
void MyVector2::operator*=(const MyVector2 multiplicand) {
this->x *= multiplicand.x;
this->y *= multiplicand.y;
}
double MyVector2::DotMultiplication(MyVector2 multiplicand) {
return (this->x * multiplicand.x) + (this->y * multiplicand.y);
}
MyVector2 MyVector2::operator/(const double dividend) {
if (dividend != 0) {
return MyVector2(this->x / dividend, this->y / dividend);
} else {
if (DEBUG_MODE_MATH) std::cout << "- - - - - ERROR: DIVIDING BY 0! - - - - -" << std::endl;
return MyVector2();
}
}
void MyVector2::operator/=(const double dividend) {
if (dividend != 0) {
this->x /= dividend;
this->y /= dividend;
} else {
if (DEBUG_MODE_MATH) std::cout << "- - - - - ERROR: DIVIDING BY 0! - - - - -" << std::endl;
}
}
MyVector2 MyVector2::operator/(const MyVector2 dividend) {
if (dividend.x != 0 && dividend.y != 0) {
return MyVector2(this->x / dividend.x, this->y / dividend.y);
} else {
if (DEBUG_MODE_MATH) std::cout << "- - - - - ERROR: DIVIDING BY 0! - - - - -" << std::endl;
return MyVector2();
}
}
void MyVector2::operator/=(const MyVector2 dividend) {
if (dividend.x != 0 && dividend.y != 0) {
this->x /= dividend.x;
this->y /= dividend.y;
} else {
if (DEBUG_MODE_MATH) std::cout << "- - - - - ERROR: DIVIDING BY 0! - - - - -" << std::endl;
}
}
double MyVector2::getMagnitude() { return sqrt(pow(this->x, 2) + pow(this->y, 2)); }
MyVector2 MyVector2::getNormalized() {
return MyVector2(this->x / this->getMagnitude(), this->y / this->getMagnitude());
}
//* ╔═══════════════════╗
//* ║ Getters & Setters ║
//* ╚═══════════════════╝
double MyVector2::getX() { return this->x; }
void MyVector2::setX(double x) { this->x = x; }
double MyVector2::getY() { return this->y; }
void MyVector2::setY(double y) { this->y = y; }
|
package com.stefanos.order.MenuCategoryFromTableActivity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import com.stefanos.order.MenuItemFromTableActivity.MenuItemsAccessFromTableActivity;
import com.stefanos.order.R;
import com.stefanos.order.TablesActivity.Table;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
public class MenuCategoryAccessFromTableActivity extends AppCompatActivity {
private static Object mContext;
private FirebaseFirestore db=FirebaseFirestore.getInstance();
private MenuCategoryAccessFromTableAdapter menuCategoryAccessFromTableAdapter;
private RecyclerView recyclerView;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_category_access_from_individual_table);
mContext = this;
}
private void setUpRecyclerView() {
recyclerView=findViewById(R.id.menuRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
String storeName=readPreferences();
CollectionReference tablesRef=db.collection("store").document(storeName).
collection("menuCategory");
Query query=tablesRef.orderBy("priority");
FirestoreRecyclerOptions<Table> options=new FirestoreRecyclerOptions.Builder<Table>().
setQuery(query, Table.class).build();
menuCategoryAccessFromTableAdapter =new MenuCategoryAccessFromTableAdapter(options);
recyclerView.setAdapter(menuCategoryAccessFromTableAdapter);
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
menuCategoryAccessFromTableAdapter.notifyDataSetChanged();
}
}
});
}
@Override
protected void onStart() {
super.onStart();
setUpRecyclerView();
menuCategoryAccessFromTableAdapter.startListening();
toolbar=findViewById(R.id.toolbarMenuCategoryAccessFromTable);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.menu_category_access_from_table_greek);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
protected void onStop() {
super.onStop();
if(menuCategoryAccessFromTableAdapter !=null){
menuCategoryAccessFromTableAdapter.stopListening();
}
}
public static void showMenuCategoryDetails(DocumentSnapshot documentSnapshot, int position){
if(documentSnapshot.exists()){
Intent intent=new Intent((Context)mContext, MenuItemsAccessFromTableActivity.class);
intent.putExtra("menuCategory",documentSnapshot.getString("table"));
((Activity)mContext).startActivity(intent);}
}
private String readPreferences(){
SharedPreferences prefs = getSharedPreferences("myStoreName", MODE_PRIVATE);
String storeName=prefs.getString("name",null);
return storeName;
}
}
|
extends CharacterBody2D
@export var move_speed : float = 100
@export var starting_direction : Vector2 = Vector2(0, 1)
@onready var animation_tree = $AnimationTree
@onready var state_machine = animation_tree.get("parameters/playback")
func _ready():
update_animation_parameter(starting_direction)
func _physics_process(_delta):
#get input direction
var input_direction = Vector2(
Input.get_action_strength("right") - Input.get_action_strength("left"),
Input.get_action_strength("down") - Input.get_action_strength("up")
)
update_animation_parameter(input_direction)
#update velocity
velocity = input_direction.normalized() * move_speed
#move and slide function uses velocity of char body to move char on the map
move_and_slide()
pick_new_state()
func update_animation_parameter(move_input : Vector2):
#don't change animation parameter is there's no input
if (move_input != Vector2.ZERO):
animation_tree.set("parameters/walk/blend_position", move_input)
animation_tree.set("parameters/idle/blend_position", move_input)
func pick_new_state():
if (velocity != Vector2.ZERO):
state_machine.travel("walk")
else:
state_machine.travel("idle")
|
import 'package:twg/core/dtos/auth/account_dto.dart';
import 'package:json_annotation/json_annotation.dart';
part 'message_dto.g.dart';
@JsonSerializable(explicitToJson: true)
class MessageDto {
String? chatRoomId;
AccountDto? userId;
String? message;
String? type;
String? createdAt;
String? updatedAt;
String? id;
MessageDto(
{this.chatRoomId,
this.userId,
this.message,
this.type,
this.createdAt,
this.updatedAt,
this.id});
factory MessageDto.fromJson(Map<String, dynamic> json) =>
_$MessageDtoFromJson(json);
Map<String, dynamic> toJson() => _$MessageDtoToJson(this);
}
|
package io.github.hansanto.kault.util
object KubernetesUtil {
val host: String = getKubernetesHost()
val token: String = getKubernetesToken()
val caCert: String = getKubernetesCaCert()
}
/**
* Environment variable name to retrieve IP of local kubernetes.
*/
private val KUBERNETES_IP_ENV = EnvValue("KUBERNETES_IP") { "192.168.49.2" }
/**
* Environment variable name to retrieve port of local kubernetes.
* For the default port value, check [documentation](https://minikube.sigs.k8s.io/docs/commands/start/).
*/
private val KUBERNETES_PORT_ENV = EnvValue("KUBERNETES_PORT") { "8443" }
/**
* Environment variable name to retrieve token of local kubernetes.
*/
private val KUBERNETES_TOKEN_ENV = EnvValue("KUBERNETES_TOKEN") {
// The token file is defined by the setup script in configuration/kubernetes
ResourceValue("configuration/kubernetes/token.tmp").value
}
/**
* File variable to retrieve CA certificate of local kubernetes.
*/
private val KUBERNETES_CA_CERT_FILE = SystemFileValue(".minikube/ca.crt")
/**
* Get the kubernetes host URL.
* @return URL of kubernetes host.
*/
private fun getKubernetesHost(): String {
return "https://${getKubernetesIp()}:${getKubernetesPort()}"
}
/**
* Get the IP of kubernetes from the environment variable.
* @return IP of kubernetes.
*/
private fun getKubernetesIp(): String = KUBERNETES_IP_ENV.value
/**
* Get the kubernetes port from the environment variable.
* @return Port of kubernetes.
*/
private fun getKubernetesPort(): String = KUBERNETES_PORT_ENV.value
/**
* Get the token of kubernetes from the environment variable [KUBERNETES_TOKEN_ENV].
* @return Token of kubernetes.
*/
private fun getKubernetesToken(): String = KUBERNETES_TOKEN_ENV.value
/**
* Get the CA certificate of kubernetes.
* @return CA certificate of kubernetes in string format.
*/
private fun getKubernetesCaCert(): String = KUBERNETES_CA_CERT_FILE.value
|
from quarto import Quarto
class Reserva:
# Reservas: (A)tiva, (C)ancelada, check-(I)n, check-(o)ut
# (A) = reserva funcionando, não pode reservar aqui
# (C) = pode reservar aqui
# (I) = tem alguém já com quarto e com dia
# (O) = quarto e dia vago, pode reservar aqui
def __init__(self, dia_inicio:int, dia_fim:int, cliente:str, quarto:Quarto, status:str) -> None:
# o parâmetro 'quarto' é mesmo do tipo Quarto (classe)?
self.__dia_inicio = dia_inicio
self.__dia_fim = dia_fim
self.__cliente = cliente
self.__quarto = quarto
self.__status = status
@property
def dia_inicio(self) -> int:
return self.__dia_inicio
@dia_inicio.setter
def dia_inicio(self, dia_inicio:int) -> int:
self.__dia_inicio = dia_inicio
@property
def dia_fim(self) -> int:
return self.__dia_fim
@dia_fim.setter
def dia_fim(self, dia_fim:int) -> int:
self.__dia_fim = dia_fim
@property
def cliente(self) -> str:
return self.__cliente
@cliente.setter
def cliente(self, cliente:str) -> str:
self.__cliente = cliente
@property
def quarto(self) -> Quarto:
return self.__quarto
@quarto.setter
def quarto(self, quarto:Quarto) -> Quarto:
self.__quarto = quarto
@property
def status(self) -> str:
return self.__status
@status.setter
def status(self, status:str) -> str:
self.__status = status
|
<a name="readme-top"></a>
<!-- TABLE OF CONTENTS -->
# 📗 Table of Contents
- [📖 About the Project](#about-project)
- [🛠 Built With](#built-with)
- [Tech Stack](#tech-stack)
- [Key Features](#key-features)
- [🚀 Live Demo](#live-demo)
- [💻 Getting Started](#getting-started)
- [Setup](#setup)
- [Prerequisites](#prerequisites)
- [Install](#install)
- [Usage](#usage)
- [Run tests](#run-tests)
- [Deployment](#triangular_flag_on_post-deployment)
- [👥 Authors](#authors)
- [🔭 Future Features](#future-features)
- [🤝 Contributing](#contributing)
- [⭐️ Show your support](#support)
- [🙏 Acknowledgements](#acknowledgements)
- [📝 License](#license)
<!-- PROJECT DESCRIPTION -->
# 📖 Enumerable <a name="about-project"></a>
In this project we learn how to use a module inside your class. For this we create a class MyList and a module MyEnumerable. Module MyEnumerable is implemented a subset of the functionality of Enumerable.
## 🛠 Built With <a name="built-with"></a>
### Tech Stack <a name="tech-stack"></a>
<details>
<summary>Client</summary>
<ul>
<li><a href="https://reactjs.org/">React.js</a></li>
</ul>
</details>
<details>
<summary>Server</summary>
<ul>
<li><a href="https://expressjs.com/">Express.js</a></li>
</ul>
</details>
<details>
<summary>Database</summary>
<ul>
<li><a href="https://www.postgresql.org/">PostgreSQL</a></li>
</ul>
</details>
<!-- Features -->
### Key Features <a name="key-features"></a>
- **Method add?**
- **Method any?**
- **Method filter**
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- LIVE DEMO -->
## 🚀 Live Demo <a name="live-demo"></a>
- [Live Demo Link](https://www.onlinegdb.com/)
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- GETTING STARTED -->
## 💻 Getting Started <a name="getting-started"></a>
To get a local copy up and running, follow these steps.
### Prerequisites
In order to run this project you need:
```sh
gem install rails
```
### Setup
Clone this repository to your desired folder:
```sh
cd my-folder
git clone git@github.com:myaccount/my-project.git
```
### Install
Install this project with:
```sh
cd my-project
gem install
```
### Usage
To run the project, execute the following command:
```sh
rails server
```
### Run tests
To run tests, run the following command:
```sh
bin/rails test test/models/article_test.rb
```
### Deployment
You can deploy this project using:
```sh
```
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- AUTHORS -->
## 👥 Authors <a name="authors"></a>
👤 **Kibrewossen Yitbarek**
- GitHub: [akos](https://github.com/akos29)
- Twitter: [kbson49](https://twitter.com/Kbson49)
- LinkedIn: [Kibrewossen](https://www.linkedin.com/in/kibrewossen-yitbarek-bb587a18/)
👤 **Sergiy Shkolnik**
- GitHub: [SergSkol](https://github.com/SergSkol)
- Twitter: [@sps676](https://twitter.com/sps676)
- LinkedIn: [SergSkol](https://www.linkedin.com/in/sergskol/)
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- FUTURE FEATURES -->
## 🔭 Future Features <a name="future-features"></a>
- [ ] **Add tests**
- [ ] **Add UI**
- [ ] **Add styling**
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- CONTRIBUTING -->
## 🤝 Contributing <a name="contributing"></a>
Contributions, issues, and feature requests are welcome!
Feel free to check the [issues page](../../issues/).
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- SUPPORT -->
## ⭐️ Show your support <a name="support"></a>
> Write a message to encourage readers to support your project
If you like this project please add star!
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- ACKNOWLEDGEMENTS -->
## 🙏 Acknowledgments <a name="acknowledgements"></a>
> Give credit to everyone who inspired your codebase.
I would like to thank Microverse for learning.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- LICENSE -->
## 📝 License <a name="license"></a>
This project is [MIT](./LICENSE) licensed.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
const categoriesList = document.querySelector('#categories');
const categoriesItem = categoriesList.querySelectorAll('.item');
console.log('');
console.log(`Number of categories: ${categoriesItem.length}`);
categoriesItem.forEach(category => {
const categoryName = category.querySelector(`h2`).textContent;
const categoryElement = category.querySelectorAll(`li`).length;
console.log('')
console.log(`Category: ${categoryName}`);
console.log(`Elements: ${categoryElement}`);
});
/*
TAREA 1
Existe una lista de categorías en el HTML ul#categories.
<ul id="categories">
<li class="item">
<h2>Animals</h2>
<ul>
<li>Cat</li>
<li>Hamster</li>
<li>Horse</li>
<li>Parrot</li>
</ul>
</li>
<li class="item">
<h2>Products</h2>
<ul>
<li>Bread</li>
<li>Prasley</li>
<li>Cheese</li>
</ul>
</li>
<li class="item">
<h2>Technologies</h2>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>React</li>
<li>Node.js</li>
</ul>
</li>
</ul>
Escriba un script que:
Cuente y muestre en la consola el número de categorías en ul#categories, es decir. los artículos li.item.
Para cada elemento li.item en la lista ul#categories, encuentre y envíe a la consola el texto del título
del artículo (tag <h2>) y el número de artículos en la categoría (todo anidado <li>).
Como resultado, se mostrarán los siguientes mensajes en la consola.
Number of categories: 3
Category: Animals
Elements: 4
Category: Products
Elements: 3
Category: Technologies
Elements: 5
EXPLICACIÓN:
Este código permite contar y mostrar el número total de categorías en una lista, así como el nombre y
el número de elementos en cada categoría.
1. Se obtiene una referencia al elemento del DOM con el id "categories" utilizando `querySelector()`.
Esto permite acceder a la lista de categorías.
2. Se utiliza `querySelectorAll()` en el elemento de la lista de categorías para obtener una colección
de elementos con la clase "item".
Estos elementos representan cada categoría individual en la lista.
3. Se utiliza `console.log()` para imprimir una línea vacía en la consola
y mostrar el número total de categorías utilizando la propiedad `length` de la colección `categoriesItem`.
4. Se utiliza un bucle `forEach` para iterar sobre cada elemento de la colección `categoriesItem`.
Para cada elemento de categoría, se realiza lo siguiente:
- Se utiliza `querySelector()` en el elemento de categoría para obtener una referencia al elemento `<h2>`
dentro de ese elemento.
Luego, se accede al contenido de texto del elemento `<h2>` utilizando la propiedad `textContent`.
Esto da el nombre de la categoría.
- Se utiliza `querySelectorAll()` en el elemento de categoría para obtener una colección de elementos `<li>`
dentro de ese elemento.
Luego, se usa la propiedad `length` de esa colección para obtener el número total de elementos en esa categoría.
- Finalmente, se utiliza `console.log()` para imprimir líneas vacías en la consola y mostrar el nombre de la categoría
y el número total de elementos en esa categoría.
*/
|
import "bootstrap/dist/css/bootstrap.min.css"
import React from 'react'
import EstacaoClimatica from "./EstacaoClimatica"
// imrd
import ReactDOM from 'react-dom'
import Loading from "./Loading"
// rfce
export default class App extends React.Component {
state = {
latitude: null,
longititude: null,
estacao: null,
data: null,
icone: null,
mensagemDeErro: null
}
componentDidMount(){
this.obterLocalizacao()
}
componentDidUpdate(){
}
componentWillUnmount(){
}
obterEstacao = (data, latitude) => {
const anoAtual = data.getFullYear()
// 21/06
// new Date(ano, mes, dia): mes começa do zero
const d1 = new Date(anoAtual, 5, 21)
// 24/09
const d2 = new Date(anoAtual, 8, 24)
// 22/12
const d3 = new Date(anoAtual, 11, 22)
// 21/03
const d4 = new Date(anoAtual, 2, 22)
const sul = latitude < 0
if (data >= d1 && data < d2)
return sul ? 'Inverno' : 'Verão'
if (data >= d2 && data < d3)
return sul ? 'Primavera' : 'Outono'
if (data >= d3 && data < d4)
return sul ? 'Verão' : 'Inverno'
return sul ? 'Outono' : 'Primavera'
}
icones = {
'Primavera': 'fa-seedling',
'Verão': 'fa-umbrella-beach',
'Outono': 'fa-tree',
'Inverno': 'fa-snowman'
}
obterLocalizacao = () => {
window.navigator.geolocation.getCurrentPosition(
(position) => {
// Extrair a data do sistema
let data = new Date()
// Calcular a estação climática do usuário
let estacao = this.obterEstacao(data, position.coords.latitude)
// Decidir qual ícone exibir
let icone = this.icones[estacao]
// Atualizar o estado do componente
this.setState({
latitude: position.coords.latitude,
longititude: position.coords.longitude,
estacao,
data: data.toLocaleTimeString(),
icone
})
},
(erro) => {this.setState({mensagemDeErro: 'Tente novamente mais tarde!'})}
)
}
render(){
return (
<div className="container mt-2">
<div className="row justify-content-center">
<div className="col-md-8">
{ (!this.state.mensagemDeErro && !this.state.latitude) ?
<Loading mensagem = "Autorize o acesso à localização!"
/>
:
this.state.mensagemDeErro ?
<p className="border rounded p-2 fs-1 text-center">
É preciso dar permissão!
</p>
:
<EstacaoClimatica
icone = {this.state.icone}
estacao = {this.state.estacao}
latitude = {this.state.latitude}
longititude = {this.state.longititude}
mensagemDeErro = {this.state.mensagemDeErro}
obterLocalizacao = {this.obterLocalizacao}
/>
}
</div>
</div>
</div>
)
}
}
ReactDOM.render(
<App />,
document.querySelector('#root')
)
|
package org.ethelred.minecraft.events;
import org.ethelred.minecraft.events.model.Dimension;
import org.ethelred.minecraft.events.model.Location;
import org.ethelred.minecraft.events.model.Player;
import org.ethelred.minecraft.events.model.PlayerUpdate;
import org.ethelred.minecraft.events.model.Vector3;
import org.ethelred.minecraft.events.model.World;
import org.jdbi.v3.sqlobject.GenerateSqlObject;
import org.jdbi.v3.sqlobject.config.RegisterConstructorMapper;
import org.jdbi.v3.sqlobject.customizer.Bind;
import org.jdbi.v3.sqlobject.customizer.BindMethods;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
import org.jdbi.v3.sqlobject.transaction.Transactional;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
@GenerateSqlObject
public interface EventDAO extends Transactional<EventDAO> {
@SqlUpdate(
// language=sql
"""
insert into location(world, player, dimension, x, y, z) values (:world, :name, :dimension, :location.x, :location.y, :location.z)
""")
boolean insertLocation(@Bind String world, @BindMethods PlayerUpdate playerUpdate);
record LocationDTO(String world, String player, Dimension dimension, double x, double y, double z){}
@SqlQuery(
// language=sql
"""
with recent_location as (
select max(id) as recent_id, world, player as recent_id from location group by world, player
)
select l.world, l.player, l.dimension, l.x, l.y, l.z from location l join recent_location rl on l.id = rl.recent_id
"""
)
@RegisterConstructorMapper(LocationDTO.class)
List<LocationDTO> findLatestLocationRows();
default SortedSet<World> findLatestLocations() {
return findLatestLocationRows()
.stream()
.collect(Collectors.groupingBy(LocationDTO::world,
Collectors.mapping(l -> new Player(l.player, new Location(l.dimension, new Vector3(l.x,l.y,l.z))),
Collectors.toCollection(TreeSet::new))))
.entrySet()
.stream()
.map(e -> new World(e.getKey(), e.getValue()))
.collect(Collectors.toCollection(TreeSet::new));
}
}
|
import React, { useContext, useEffect, useState } from "react";
import { Image, Text, TouchableHighlight, View } from "react-native";
import get_course_list from "../../api/get/get_course_list";
import { Rating, AirbnbRating } from "react-native-ratings";
import { useNavigation } from "@react-navigation/native";
import { AppContext } from "../../../App";
const CourseList = () => {
const [data, setData] = useState([]);
const {user }= useContext(AppContext)
const navigation= useNavigation()
useEffect(() => {
(async () => {
const result = await get_course_list();
setData(result.courses);
})();
}, []);
const handlePress= (id)=> {
if(user) {
const isPurchased = user.courses?.find(
(item) => item._id === id
);
if(isPurchased) {
navigation.navigate("CourseAccess", {courseId: id})
}
else {
navigation.navigate("DetailCourse", {courseId: id})
}
}
else {
navigation.navigate("DetailCourse", {courseId: id})
}
}
const renderData = (data) => {
return data?.map((item, key) => (
<TouchableHighlight key={key} onPress={()=> handlePress(item._id)} style={{width: "100%"}} underlayColor={"unset"}>
<View
key={key}
style={{
width: "100%",
borderRadius: 5,
padding: 10,
borderColor: "#e7e7e7",
borderStyle: "solid",
borderWidth: 1,
marginBottom: 24,
}}
>
<Image
style={{
width: "100%",
aspectRatio: 1,
objectFit: "contain",
borderRadius: 5,
marginBottom: 24,
}}
source={{ uri: item?.thumbnail?.url }}
/>
<Text style={{ fontWeight: "600", fontSize: 18, marginBottom: 12 }}>
{item.name}
</Text>
<View style={{width: "100%", display: "flex", justifyContent: "flex-start", flexDirection: "row"}}>
<Rating
ratingCount={item.ratings}
style={{ paddingVertical: 10 }}
imageSize={18}
/>
</View>
</View>
</TouchableHighlight>
));
};
return (
<View
style={{
width: "100%",
display: "flex",
justifyContent: "center",
alignItems: "center",
padding: 10,
}}
>
{renderData(data)}
</View>
);
};
export default CourseList;
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HeroesComponent } from './../heroes/heroes.component';
import { DashboardComponent } from './../dashboard/dashboard.component';
import { HeroDetailComponent } from './../hero-detail/hero-detail.component';
/**
* Definição do roteamento do app
* Cada caminho (path) renderiza um determinado componente ou redireciona
* para outro path.
*/
const routes: Routes = [
{ path: 'heroes', component: HeroesComponent },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }
];
@NgModule({
exports: [RouterModule],
imports: [RouterModule.forRoot(routes)]
})
export class AppRoutingModule {}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateBuysTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('buys', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
// $table->foreign('user_id')->references('id')->on('users');
$table->unsignedBigInteger('transaction_id')->nullable();
// $table->foreign('transaction_id')->references('id')->on('transactions');
$table->unsignedBigInteger('currency_id')->nullable();
// $table->foreign('currency_id')->references('id')->on('currencies');
$table->unsignedBigInteger('status_id');
// $table->foreign('status_id')->references('id')->on('statuses');
$table->unsignedBigInteger('type_id');
// $table->foreign('type_id')->references('id')->on('types');
$table->unsignedBigInteger('request_amount');
$table->unsignedDecimal('price', $precision = 20, $scale = 2);
$table->unsignedDecimal('amount', $precision = 20, $scale = 2);
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('buys');
}
}
|
<?php
namespace App\DataTables;
use App\Models\TipoSolicitud;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Html\Builder as HtmlBuilder;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Services\DataTable;
use Illuminate\Support\Facades\Gate;
class TipoSolicitudDataTable extends DataTable
{
/**
* Build the DataTable class.
*
* @param QueryBuilder $query Results from query() method.
*/
public function dataTable(QueryBuilder $query): EloquentDataTable
{
return (new EloquentDataTable($query))
->setRowId('id')
->escapeColumns([])
->addColumn('opciones', function ($row) {
$action = '';
if (Gate::allows('tiposolicitud-editar')) {
$action .= '<button data-action="edit" data-id="' . $row->id . '" class="btn btn-sm btn-icon btn-warning action"><i class="fas fa-edit"></i></button>';
}
if (Gate::allows('tiposolicitud-activar')) {
if ($row->activo) {
$action .= ' <button data-action="desactivar" data-id="' . $row->id . '" class="btn btn-sm btn-icon btn-success action"><i class="fas fa-check"></i></button>';
} else {
$action .= ' <button data-action="activar" data-id="' . $row->id . '" class="btn btn-sm btn-icon btn-danger action"><i class="fas fa-times"></i> </button>';
}
}
return $action;
})
->addColumn('vimagen', function ($row) {
$url = empty($row->imagen) ? asset("assets/noimage.png") : asset("uploads/tipoSolicitudes/$row->imagen");
return '<img src="' . $url . '" border="0" width="40" class="img-rounded" align="center" />';
})
->addColumn('activo', function ($row) {
return $row->activo ? 'Activo' : 'Desactivado';
})
->rawColumns(['opciones', 'vimagen', 'activo']);
}
/**
* Get the query source of dataTable.
*/
public function query(TipoSolicitud $model): QueryBuilder
{
return $model->newQuery();
}
/**
* Optional method if you want to use the html builder.
*/
public function html(): HtmlBuilder
{
return $this->builder()
->setTableId('table-listado')
->columns($this->getColumns())
->minifiedAjax()
->orderBy(1)
->parameters([
'language' => ['url' => '/assets/datatables/i18n/es-ES.json'],
'dom' => 'Bfrtip',
'buttons' => [
'excel', 'csv', 'pdf', 'print', 'reset', 'reload'
]
]);
}
/**
* Get the dataTable columns definition.
*/
public function getColumns(): array
{
return [
Column::computed('opciones')
->exportable(false)
->printable(false)
->addClass('text-center')
->title('Opciones'),
Column::make('id'),
Column::make('nombre')->title('Nombre'),
Column::make('activo')->title('Estado'),
Column::computed('vimagen')
->exportable(false)
->printable(false)
->addClass('text-center')
->title('Imagen'),
];
}
/**
* Get the filename for export.
*/
protected function filename(): string
{
return 'TipoSolicitud_' . date('YmdHis');
}
}
|
<script>
import SetSignature from "../contents/SetSignature";
import Mailing from "./options/Mailing";
import PassSlip from "./options/PassSlip";
import Risograph from "./options/Risograph";
import Default from "./options/Default";
import Certification from "./options/Certification";
import IssueSlip from "./options/IssueSlip";
import CctvReview from "./options/CctvReview";
import GatePass from "./options/GatePass";
import RequestForServices from "./options/RequestForServices";
import form from "./options/form";
export default {
name: "Compose",
components: {
SetSignature,
Mailing,
PassSlip,
Default,
Risograph,
Certification,
IssueSlip,
CctvReview,
GatePass,
RequestForServices,
},
data: () => ({
signature_view: { shown: false },
others: false,
rules: [(v) => !!v || "This field is not allowed to be empty"],
items: ["A4", "Letter"],
timeout: 3000,
form,
}),
computed: {
getFacultyProfile() {
return this.$store.getters["faculty/getProfile"];
},
getAllServiceProviders() {
return this.$store.getters["faculty/getAllServiceProviders"];
},
getAllAdmin() {
return this.$store.getters["admin/getAllAdmin"];
},
getAllServices() {
return this.$store.getters["service/getAllServices"];
},
getComposeLoading() {
return this.$store.getters["request/getLoading"].create;
},
isLoading() {
const { getters } = this.$store;
return (
getters["faculty/getLoading"].all_service_provider ||
getters["admin/getLoading"].all_admin ||
getters["service/getAllServices"].all_admin
);
},
},
methods: {
getOptionalComponent() {
const [optionalComponent] = this.getAllServices.filter(
({ _id }) => _id === this.form.service_id
);
return optionalComponent ? optionalComponent.component : "Default";
},
hideAndSeekSignature() {
this.signature_view.shown = !this.signature_view.shown;
},
customService(bool) {
this.others = bool;
if (bool) {
this.form.service_id = "";
this.form.options = { persons_involved: [] };
}
this.form.other_service = "";
},
handleChangeService(e) {
const [selectedOption] = this.getAllServices.filter(
({ _id }) => _id === e
);
this.form.options = selectedOption
? selectedOption.options
: { persons_involved: [] };
},
handleSetSignature(signatureId, hideSignatures) {
const signatureElement = document.getElementById(signatureId).innerHTML;
this.form.user.signature = signatureElement
.toString()
.replace('height="300"', 'height="175" viewBox="0 0 300 175"');
this.form.hideSignatures = hideSignatures;
},
handleSubmit(status) {
(e) => {
e.preventDefault();
};
localStorage.removeItem("compose");
this.form.reports.status = status || "created";
if (this.form.service_id) delete this.form.other_service;
if (this.$refs.form.validate()) {
if (!this.form.user.signature)
return this.$store.dispatch(
"message/errorMessage",
"You must sign this document to proceed"
);
this.$store.dispatch("request/Create", this.form);
}
},
handleSetLocalStorage() {
localStorage.setItem("compose", JSON.stringify(this.form));
},
},
created() {
const compose = localStorage.getItem("compose");
if (compose) {
this.form = JSON.parse(compose);
this.form.user.signature = "";
}
this.$store.dispatch("faculty/allServiceProviders");
this.$store.dispatch("admin/allAdmin");
this.$store.dispatch("service/allServices");
},
unmounted() {
this.form.user.signature = "";
},
};
</script>
<template>
<v-container fluid class="pa-3">
<v-row justify="start" align="start">
<v-col cols="12">
<v-form
ref="form"
@submit="(e) => e.preventDefault()"
:disabled="getComposeLoading"
v-if="!isLoading"
>
<v-row justify="start" align="start" no-gutters dense>
<v-col cols="12">
<v-container fluid class="px-0">
<v-subheader class="text-h5">
Create Service Request
</v-subheader>
<v-divider />
</v-container>
</v-col>
<v-col cols="12">
<v-container fluid>
<v-row justify="start">
<v-col cols="12" sm="12" md="6" class="pa-0 pa-md-3 py-0">
<component
:options="form.options"
:rules="rules"
:is="getOptionalComponent()"
/>
<v-col cols="12" class="py-0 px-0 pt-2">
<v-container fluid class="py-0">
<v-subheader class="text-h6 px-0">
Authorized Signees
</v-subheader>
<v-divider />
</v-container>
</v-col>
<v-col cols="12" class="px-0">
<v-container fluid class="pt-2 pb-0">
<v-row justify="start" align="start" dense>
<v-col cols="12">
<v-autocomplete
v-model="form.admin.staff_id"
@change="handleSetLocalStorage"
:rules="rules"
small
:items="getAllAdmin"
class="caption"
item-text="name"
item-value="staff_id"
outlined
label="Chief Administration Officers"
title="Select CAO Officer (required)"
dense
prepend-inner-icon="mdi-close"
@click:prepend-inner="form.admin.staff_id = ''"
/>
</v-col>
<v-col cols="12">
<v-autocomplete
v-model="form.service_provider.staff_id"
@change="handleSetLocalStorage"
:items="getAllServiceProviders"
class="caption"
item-text="text"
item-value="staff_id"
outlined
title="Select a service provider (optional)"
label="Service Provider (optional)"
hint="(optional)"
dense
prepend-inner-icon="mdi-close"
@click:prepend-inner="
form.service_provider.staff_id = ''
"
/>
</v-col>
<v-col cols="12" class="py-0">
<v-btn
:disabled="getComposeLoading"
color="success"
type="button"
@click="hideAndSeekSignature"
block
large
elevation="0"
title="Apply your E-Signature (required)"
>
Apply Your E-Signature
<v-icon right> mdi-signature </v-icon>
</v-btn>
</v-col>
</v-row>
</v-container>
</v-col>
</v-col>
<v-col cols="12" sm="12" md="6">
<v-row justify="start">
<v-col cols="12" class="pb-3">
<v-row align="start">
<v-col cols="12" sm="12" v-if="!others">
<v-autocomplete
v-model="form.service_id"
outlined
label="Service Type"
title="Select service type (required)"
persistent-hint
:rules="others ? rules : []"
:items="getAllServices"
@change="handleChangeService"
item-text="type"
item-value="_id"
dense
/>
</v-col>
<v-col cols="12" class="pb-0" v-if="others">
<v-text-field
v-model="form.other_service"
append-icon="mdi-eye-off"
label="Custom Service"
title="Create your own service type"
hint="please specify custom service"
@click:append="customService(false)"
outlined
dense
/>
</v-col>
<v-col v-else cols="12" class="pt-0 mt-n3">
<v-btn
@click="customService(true)"
elevation="0"
block
color="primary"
title="Click to create custom service type"
>
Custom service
</v-btn>
</v-col>
</v-row>
</v-col>
<v-col cols="12" class="pb-0">
<v-text-field
v-model="form.subject"
@change="handleSetLocalStorage"
autofocus
outlined
:rules="rules"
label="Description"
title="Description of your request (required)"
dense
counter
maxlength="50"
/>
</v-col>
<v-col cols="12" class="py-0">
<v-textarea
rows="10"
class="body-2"
v-model="form.body"
@change="handleSetLocalStorage"
outlined
height="100%"
:rules="rules"
label="Purpose"
title="Purpose/Body of your request (required)"
auto-grow
/>
</v-col>
<v-col cols="12" class="pa-0 pa-md-3">
<v-container fluid>
<v-subheader class="px-0">
Save As
<v-subheader
class="caption font-weight-bold py-0 hidden-sm-and-down"
>
(This will set to draft as a default)
</v-subheader>
</v-subheader>
<v-divider />
</v-container>
</v-col>
<v-col cols="12">
<v-row justify="start" align="start" dense>
<v-col cols="12" sm="12" md="6">
<v-btn
:disabled="getComposeLoading"
color="warning"
type="submit"
@click="handleSubmit()"
rounded
outlined
block
elevation="0"
title="Save this service request as draft"
>
draft
<v-icon right> mdi-paperclip </v-icon>
</v-btn>
</v-col>
<v-col cols="12" sm="12" md="6">
<v-btn
:disabled="getComposeLoading"
color="primary"
type="button"
@click="handleSubmit('sent')"
rounded
outlined
block
elevation="0"
title="Send this service request immediately"
>
send
<v-icon right> mdi-send </v-icon>
</v-btn>
</v-col>
</v-row>
</v-col>
<v-col cols="12" class="hidden-sm-and-up">
<v-divider />
</v-col>
</v-row>
</v-col>
<v-divider class="hidden-sm-and-down" vertical />
</v-row>
</v-container>
</v-col>
</v-row>
</v-form>
<v-skeleton-loader v-else class="mx-auto" type="card, card, card" />
</v-col>
</v-row>
<SetSignature
v-if="signature_view.shown"
:data="signature_view"
:hideAndSeekSignature="hideAndSeekSignature"
:handleSetSignature="handleSetSignature"
/>
</v-container>
</template>
|
// Copyright 2023 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use anyhow::Result;
use system_api::shadercached::UnmountRequest;
use crate::common::SteamAppId;
use crate::service::handle_unmount;
use crate::shader_cache_mount::{new_mount_map, VmId};
use crate::test::common::{
foz_db_list_contains, foz_db_list_empty, get_unmount_queue, mock_gpucache, simulate_mounted,
};
use super::common::add_shader_cache_mount;
fn mock_unmount_request(vm_name: &str, vm_owner_id: &str, game_id: SteamAppId) -> UnmountRequest {
let mut install_request = UnmountRequest::new();
install_request.vm_name = vm_name.to_string();
install_request.vm_owner_id = vm_owner_id.to_string();
install_request.steam_app_id = game_id;
install_request
}
#[tokio::test]
async fn unmount_single() -> Result<()> {
let mock_gpu_cache = mock_gpucache().expect("Failed to create mock gpu cache");
let vm_id = VmId::new("vm", "owner");
let mount_map = new_mount_map();
add_shader_cache_mount(&mock_gpu_cache, mount_map.clone(), &vm_id).await?;
simulate_mounted(&mock_gpu_cache, 42).await?;
assert!(foz_db_list_contains(&mock_gpu_cache, 42)?);
let unmount_request = mock_unmount_request("vm", "owner", 42);
let raw_bytes = protobuf::Message::write_to_bytes(&unmount_request)?;
handle_unmount(raw_bytes, mount_map.clone()).await?;
let mount_map_read = mount_map.read().await;
let shader_cache_mount = mount_map_read.get(&vm_id).unwrap();
let unmount_queue = shader_cache_mount.get_unmount_queue();
assert_eq!(unmount_queue.len(), 1);
assert!(unmount_queue.contains(&42));
assert!(foz_db_list_empty(&mock_gpu_cache)?);
Ok(())
}
#[tokio::test]
async fn unmount_single_among_many() -> Result<()> {
let mock_gpu_cache = mock_gpucache().expect("Failed to create mock gpu cache");
let vm_id = VmId::new("vm", "owner");
let mount_map = new_mount_map();
add_shader_cache_mount(&mock_gpu_cache, mount_map.clone(), &vm_id).await?;
simulate_mounted(&mock_gpu_cache, 42).await?;
simulate_mounted(&mock_gpu_cache, 1337).await?;
assert!(foz_db_list_contains(&mock_gpu_cache, 1337)?);
assert!(foz_db_list_contains(&mock_gpu_cache, 42)?);
let unmount_request = mock_unmount_request("vm", "owner", 42);
let raw_bytes = protobuf::Message::write_to_bytes(&unmount_request)?;
handle_unmount(raw_bytes, mount_map.clone()).await?;
let unmount_queue = get_unmount_queue(mount_map.clone(), &vm_id).await?;
assert_eq!(unmount_queue.len(), 1);
assert!(unmount_queue.contains(&42));
assert!(foz_db_list_contains(&mock_gpu_cache, 1337)?);
assert!(!foz_db_list_contains(&mock_gpu_cache, 42)?);
Ok(())
}
#[tokio::test]
async fn unmount_multiple_vms_and_games() -> Result<()> {
let mock_gpu_cache1 = mock_gpucache().expect("Failed to create mock gpu cache");
let vm_id1 = VmId::new("vm", "owner");
let mount_map1 = new_mount_map();
add_shader_cache_mount(&mock_gpu_cache1, mount_map1.clone(), &vm_id1).await?;
simulate_mounted(&mock_gpu_cache1, 42).await?;
simulate_mounted(&mock_gpu_cache1, 1337).await?;
assert!(foz_db_list_contains(&mock_gpu_cache1, 1337)?);
assert!(foz_db_list_contains(&mock_gpu_cache1, 42)?);
let mock_gpu_cache2 = mock_gpucache().expect("Failed to create mock gpu cache");
let vm_id2 = VmId::new("vm", "owner2");
let mount_map2 = new_mount_map();
add_shader_cache_mount(&mock_gpu_cache2, mount_map2.clone(), &vm_id2).await?;
simulate_mounted(&mock_gpu_cache2, 42).await?;
assert!(foz_db_list_contains(&mock_gpu_cache2, 42)?);
let mock_gpu_cache3 = mock_gpucache().expect("Failed to create mock gpu cache");
let vm_id3 = VmId::new("vm2", "owner2");
let mount_map3 = new_mount_map();
add_shader_cache_mount(&mock_gpu_cache3, mount_map3.clone(), &vm_id3).await?;
simulate_mounted(&mock_gpu_cache3, 1234).await?;
assert!(foz_db_list_contains(&mock_gpu_cache3, 1234)?);
// Unmount vm_id1 42
let unmount_request = mock_unmount_request("vm", "owner", 42);
let raw_bytes = protobuf::Message::write_to_bytes(&unmount_request)?;
handle_unmount(raw_bytes, mount_map1.clone()).await?;
let unmount_queue = get_unmount_queue(mount_map1.clone(), &vm_id1).await?;
assert_eq!(unmount_queue.len(), 1);
assert!(unmount_queue.contains(&42));
assert!(foz_db_list_contains(&mock_gpu_cache1, 1337)?);
assert!(!foz_db_list_contains(&mock_gpu_cache1, 42)?);
assert!(foz_db_list_contains(&mock_gpu_cache2, 42)?);
assert!(foz_db_list_contains(&mock_gpu_cache3, 1234)?);
// Unmount vm_id2 42
let unmount_request = mock_unmount_request("vm", "owner2", 42);
let raw_bytes = protobuf::Message::write_to_bytes(&unmount_request)?;
handle_unmount(raw_bytes, mount_map2.clone()).await?;
let unmount_queue = get_unmount_queue(mount_map2.clone(), &vm_id2).await?;
assert_eq!(unmount_queue.len(), 1);
assert!(unmount_queue.contains(&42));
assert!(foz_db_list_contains(&mock_gpu_cache1, 1337)?);
assert!(!foz_db_list_contains(&mock_gpu_cache1, 42)?);
assert!(foz_db_list_empty(&mock_gpu_cache2)?);
assert!(foz_db_list_contains(&mock_gpu_cache3, 1234)?);
Ok(())
}
#[tokio::test]
async fn unmount_not_mounted() -> Result<()> {
let mock_gpu_cache = mock_gpucache().expect("Failed to create mock gpu cache");
let vm_id = VmId::new("vm", "owner");
let mount_map = new_mount_map();
add_shader_cache_mount(&mock_gpu_cache, mount_map.clone(), &vm_id).await?;
let unmount_request = mock_unmount_request("vm", "owner", 42);
let raw_bytes = protobuf::Message::write_to_bytes(&unmount_request)?;
handle_unmount(raw_bytes, mount_map.clone()).await?;
let unmount_queue = get_unmount_queue(mount_map.clone(), &vm_id).await?;
assert_eq!(unmount_queue.len(), 0);
Ok(())
}
|
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getAllProducts, getCartItems, removeItem } from "../feature/cart/CartSlice";
const Cart = () => {
const products = useSelector(getAllProducts)
const cartItems = useSelector(getCartItems);
const dispatch = useDispatch();
let totalPrice=0
if(cartItems.length>0){
totalPrice = cartItems.reduce((sum,item)=>{
console.log(Number(item.price)+" "+item.title)
return sum = sum + Number(item.price)
},0)
}
function handleRemove(item){
console.log(item.id);
dispatch(removeItem(item))
}
return (
<div className="cartMain"
// style={{ margin: "15% 0 0 0" }}
>
<div>
{cartItems.map((item) => (
<div
key={item.id}
style={{
background: "lavender",
mixBlendMode: "darken",
height: "15%",
border: "3px solid lavender",
borderRadius: "5%",
padding: "4%",
margin: "2% 15% 2% 15%",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
<div style={{ width: "50%" }}>
<img style={{ width: "80%" }} src={item.image} alt="image"></img>
</div>
<div>
<div>
<h3>{item.title}</h3>
<h3>Price: Rs.{Math.round(item.price * 80)}</h3>
</div>
<div>
<button
style={{
border: "1px solid plum",
background: "plum",
}}
className="btn"
onClick={() => handleRemove(item)}
>
Remove
</button>
</div>
</div>
</div>
))}
</div>
<div style={{ padding: "1%" }}>
<h3>Total Amount: {Math.round(totalPrice * 80)}</h3>
</div>
<div>
<button
style={{
border: "1px solid plum",
background: "plum",
margin:"5%",
width:"30%"
}}
className="btn"
>
Place Order
</button>
</div>
</div>
);
};
export default Cart;
|
const { capitalize, reverseString, calculator, caesarCipher, analyzeArray } = require('./testing');
it('capitalize', () => {
expect(capitalize('hello')).toBe('Hello');
});
it('reverseString', () => {
expect(reverseString('World')).toBe('dlroW');
});
it('calculatorAdd', () => {
expect(calculator.add(1, 2)).toBe(3);
})
it('calculatorSub', () => {
expect(calculator.subtract(2, 1)).toBe(1);
})
it('calculatorMul', () => {
expect(calculator.multiply(2, 2)).toBe(4);
})
it('calculatorDiv', () => {
expect(calculator.divide(4, 2)).toBe(2);
})
it('cipher test no.1', () => {
expect(caesarCipher('z', 5)).toBe('e');
})
it('cipher test no.2', () => {
expect(caesarCipher('a', -3)).toBe('x');
})
it('cipher test no.3', () => {
expect(caesarCipher(' ', -3)).toBe(' ');
})
it('cipher test no.4', () => {
expect(caesarCipher('a')).toBe('a');
})
it('cipher test no.5', () => {
expect(caesarCipher('A')).toBe('A');
})
it('cipher test no.5', () => {
expect(caesarCipher('0 a', 1)).toBe('0 b');
})
it('analyzeArray test no.1', () => {
expect(analyzeArray([1,2,3])).toEqual({ average: 2, min: 1, max: 3, length: 3 });
})
|
import { apiSlice } from "../api/apiSlice";
const userApi = apiSlice.injectEndpoints({
endpoints:builders=>({
getAllUsers : builders.query({
query:()=>'/users',
providesTags:['Users']
}),
getSignInUser : builders.mutation({
query: (data) => ({
url: '/signin',
method: 'POST',
body: data,
}),
invalidatesTags:['Users']
}),
getVerifyUser : builders.mutation({
query: ()=>({
url:'/verifyuser',
method: 'POST',
}),
invalidatesTags:['Users']
}),
createUser : builders.mutation({
query:(data)=>({
url:'/signup',
method: 'POST',
body : data
}),
invalidatesTags:['Users']
}),
googleSignUp : builders.mutation({
query: ()=>({
url:"/googlesignup",
method:"POST",
}),
invalidatesTags:['Users']
}),
googleSignIn : builders.mutation({
query:()=>({
url:"/googlesignin",
method:"POST"
}),
invalidatesTags:['Users']
}),
getUserUpdateProfile : builders.mutation({
query : ({id , data} ) =>({
url:`/users/${id}`,
method:"PATCH",
body: data
}),
invalidatesTags:['Users']
}),
getUserAddress : builders.query({
query : (mail)=>({
url:`/address/${mail}`,
method:'GET'
}),
providesTags:['Address']
}),
addUserAddress : builders.mutation({
query : (data)=>({
url:'/address',
method:"POST",
body : { data }
}),
invalidatesTags:['Address']
}),
getforgetPassword : builders.mutation({
query:(email)=>({
url:'/forgetpassword',
method:'POST',
body: { email }
})
}),
addResetPassword : builders.mutation({
query:({token , data})=>({
url:'/resetpassword',
method:'POST',
body:{ token , data}
})
}) ,
getVerifymailAfter : builders.mutation({
query : (email)=>({
url:'/mailverify',
method:'POST',
body:{ email }
})
}),
getVerifyMail : builders.mutation({
query: (token)=>({
url:'/verifymailconfrom',
method:'POST',
body:{ token }
})
}) ,
getDeleteAddress : builders.mutation({
query:(email)=>({
url:'/address',
method:'DELETE',
body : { email }
}),
invalidatesTags:['Address']
}),
})
})
export const { useGetAllUsersQuery,
useGetSignInUserMutation,
useGetVerifyUserMutation,
useCreateUserMutation ,
useGoogleSignUpMutation ,
useGoogleSignInMutation,
useGetUserUpdateProfileMutation,
useAddUserAddressMutation,
useGetUserAddressQuery,
useGetforgetPasswordMutation ,
useAddResetPasswordMutation ,
useGetVerifymailAfterMutation,
useGetVerifyMailMutation,
useGetDeleteAddressMutation,
} = userApi
export default userApi
|
class BeliefSystemSimulator:
def __init__(self, belief_types):
self.belief_types = belief_types
def analyze_belief_impacts(self):
impacts = {}
for belief_type, beliefs in self.belief_types.items():
if belief_type in ['inner', 'external', 'nonconscious', 'unconscious', 'subconscious']:
impacts[belief_type] = self._personal_belief_impact(beliefs)
elif belief_type == 'superconscious':
impacts[belief_type] = self._superconscious_impact(beliefs)
elif belief_type == 'subliminal':
impacts[belief_type] = self._subliminal_impact(beliefs)
elif belief_type in ['unknown', 'spiritual', 'religious', 'supernatural']:
impacts[belief_type] = self._transcendent_belief_impact(beliefs)
return impacts
def _personal_belief_impact(self, beliefs):
return f'Influences personal behavior and cognitive processing: {beliefs}'
def _superconscious_impact(self, beliefs):
return f'Provides intuition and deep insights: {beliefs}'
def _subliminal_impact(self, beliefs):
return f'Subtly influences without conscious awareness: {beliefs}'
def _transcendent_belief_impact(self, beliefs):
return f'Influences worldview and perception of reality: {beliefs}'
individual_beliefs = {
"inner": ["self-worth", "capabilities"],
"external": ["cultural norms", "media influence"],
"nonconscious": ["childhood experiences"],
"unconscious": ["deep-seated fears"],
"subconscious": ["ingrained habits"],
"superconscious": ["intuitive guidance"],
"subliminal": ["background advertising"],
"unknown": ["beliefs about extraterrestrial life"],
"spiritual": ["connection to a higher power"],
"religious": ["devotion to specific deities"],
"supernatural": ["belief in ghosts"]
}
belief_simulator = BeliefSystemSimulator(individual_beliefs)
belief_impacts = belief_simulator.analyze_belief_impacts()
print("Belief Impacts Analysis:", belief_impacts)
class EnhancedBeliefSystemSimulator(BeliefSystemSimulator):
def __init__(self, belief_types):
super().__init__(belief_types)
self.cumulative_effects = {}
def update_beliefs_based_on_interactions(self):
# Simulate the dynamic interaction between different belief types
if 'superconscious' in self.belief_types and 'inner' in self.belief_types:
if 'intuitive guidance' in self.belief_types['superconscious']:
self.belief_types['inner'] = [belief + ' (enhanced by intuition)' for belief in self.belief_types['inner']]
# Add more interactions as needed
def calculate_cumulative_effects(self):
# Assess the overall impact of the combined belief system
self.cumulative_effects['behavioral_changes'] = []
self.cumulative_effects['cognitive_changes'] = []
for belief_type, impacts in self.analyze_belief_impacts().items():
if 'behavior' in impacts:
self.cumulative_effects['behavioral_changes'].append(impacts)
if 'cognitive' in impacts:
self.cumulative_effects['cognitive_changes'].append(impacts)
return self.cumulative_effects
enhanced_beliefs = {
# ... [use the individual beliefs as defined earlier]
}
enhanced_belief_simulator = EnhancedBeliefSystemSimulator(enhanced_beliefs)
enhanced_belief_simulator.update_beliefs_based_on_interactions()
cumulative_effects = enhanced_belief_simulator.calculate_cumulative_effects()
print("Cumulative Effects of Beliefs on Behavior and Cognition:", cumulative_effects)
class DigitalBeliefsSimulator:
def __init__(self, online_sources, online_interactions, tech_experiences):
self.online_sources = online_sources
self.online_interactions = online_interactions
self.tech_experiences = tech_experiences
def simulate_belief_formation(self):
beliefs = {}
for source in self.online_sources:
beliefs[source] = "influenced by online content"
for interaction in self.online_interactions:
beliefs[interaction] = "shaped by digital interactions"
for experience in self.tech_experiences:
belief_quality = "positive" if experience['experience'] == "good" else "negative"
beliefs[experience['tech']] = belief_quality
return beliefs
class WrittenBeliefsSimulator:
def __init__(self, written_expressions):
self.written_expressions = written_expressions
def analyze_written_beliefs(self):
analyzed_beliefs = {}
for expression in self.written_expressions:
if expression['type'] == 'manifesto':
analyzed_beliefs[expression['content']] = "personal values and guiding principles"
elif expression['type'] == 'statement of faith':
analyzed_beliefs[expression['content']] = "declaration of religious beliefs"
elif expression['type'] == 'philosophical treatise':
analyzed_beliefs[expression['content']] = "exploration of philosophical ideas"
return analyzed_beliefs
digital_beliefs_simulator = DigitalBeliefsSimulator(
online_sources=["news websites", "social media"],
online_interactions=["community forums", "online groups"],
tech_experiences=[{"tech": "smartphone", "experience": "good"}]
)
digital_beliefs = digital_beliefs_simulator.simulate_belief_formation()
print("Digital Beliefs:", digital_beliefs)
written_beliefs_simulator = WrittenBeliefsSimulator(
written_expressions=[
{"type": "manifesto", "content": "Personal Growth Manifesto"},
{"type": "statement of faith", "content": "My Faith Journey"},
{"type": "philosophical treatise", "content": "On the Nature of Reality"}
]
)
written_beliefs = written_beliefs_simulator.analyze_written_beliefs()
print("Written Beliefs:", written_beliefs)
class IntegratedBeliefSystemSimulator:
def __init__(self, digital_beliefs_simulator, written_beliefs_simulator):
self.digital_beliefs_simulator = digital_beliefs_simulator
self.written_beliefs_simulator = written_beliefs_simulator
self.integrated_beliefs = {}
def integrate_and_analyze_beliefs(self):
digital_beliefs = self.digital_beliefs_simulator.simulate_belief_formation()
written_beliefs = self.written_beliefs_simulator.analyze_written_beliefs()
for belief, source in digital_beliefs.items():
if belief in written_beliefs:
self.integrated_beliefs[belief] = f"Digitally influenced and personally expressed as {written_beliefs[belief]}"
else:
self.integrated_beliefs[belief] = f"Primarily digitally influenced as {source}"
for belief, expression in written_beliefs.items():
if belief not in digital_beliefs:
self.integrated_beliefs[belief] = f"Personally expressed as {expression}"
return self.integrated_beliefs
digital_beliefs_sim = DigitalBeliefsSimulator(
online_sources=["news websites", "educational platforms"],
online_interactions=["online learning communities", "discussion forums"],
tech_experiences=[{"tech": "virtual reality", "experience": "good"}]
)
written_beliefs_sim = WrittenBeliefsSimulator(
written_expressions=[
{"type": "manifesto", "content": "Sustainable Living Manifesto"},
{"type": "philosophical treatise", "content": "On the Ethics of Technology"}
]
)
integrated_belief_system_sim = IntegratedBeliefSystemSimulator(digital_beliefs_sim, written_beliefs_sim)
integrated_beliefs = integrated_belief_system_sim.integrate_and_analyze_beliefs()
print("Integrated Beliefs:", integrated_beliefs)
class BeliefEnergySimulator:
def __init__(self, belief_types):
self.belief_types = belief_types
self.energy_field = {'positive': 0, 'negative': 0, 'limiting': 0, 'empowering': 0}
def analyze_belief_impacts(self):
impacts = {}
for belief_type, beliefs in self.belief_types.items():
impacts[belief_type] = f"Belief influenced by {belief_type}"
self.update_energy_field(impacts)
return impacts
def update_energy_field(self, impacts):
for belief_type, impact in impacts.items():
if 'positive' in belief_type or 'empowering' in impact:
self.energy_field['positive'] += 1
elif 'negative' in belief_type or 'limiting' in impact:
self.energy_field['negative'] += 1
# Add more conditions as appropriate
def get_energy_field_status(self):
return self.energy_field
belief_types = {
"ideals": ["equality", "freedom"],
"morals": ["honesty", "integrity"],
"truths": ["scientific facts", "observable realities"],
"virtues": ["patience", "kindness"],
"dreams": ["exploration of other dimensions"],
"heart": ["deep love", "compassion"],
"intuition": ["gut feelings about decisions"],
"astronomy": ["beliefs about the universe"],
"spirit": ["connection to something greater"],
"soul": ["innermost self-beliefs"],
"mental": ["self-efficacy", "personal capabilities"],
"emotional": ["emotional responses to experiences"],
"vocal": ["beliefs about vocal abilities"]
}
belief_energy_simulator = BeliefEnergySimulator(belief_types)
belief_impacts = belief_energy_simulator.analyze_belief_impacts()
energy_field_status = belief_energy_simulator.get_energy_field_status()
print("Belief Impacts:", belief_impacts)
print("Energy Field Status:", energy_field_status)
class AdvancedBeliefEnergySimulator(BeliefEnergySimulator):
def evolve_beliefs_over_time(self, new_experiences):
for experience in new_experiences:
for belief_type in self.belief_types:
if experience in self.belief_types[belief_type]:
self.belief_types[belief_type].remove(experience)
self.belief_types[belief_type].append(f"{experience} (evolved)")
self.update_energy_field(self.belief_types)
def simulate_feedback_loop(self):
for field, value in self.energy_field.items():
if value > 5: # Threshold for significant energy impact
for belief_type in self.belief_types:
self.belief_types[belief_type] = [f"{belief} (influenced by {field} energy)" for belief in self.belief_types[belief_type]]
return self.belief_types
new_experiences = ["global travel", "learning a new language", "spiritual retreat"]
advanced_belief_energy_simulator = AdvancedBeliefEnergySimulator(belief_types)
advanced_belief_energy_simulator.evolve_beliefs_over_time(new_experiences)
evolved_beliefs = advanced_belief_energy_simulator.simulate_feedback_loop()
print("Evolved Beliefs:", evolved_beliefs)
print("Updated Energy Field:", advanced_belief_energy_simulator.get_energy_field_status())
class BeliefHormoneNeuroplasticitySimulator:
def __init__(self, beliefs):
self.beliefs = beliefs
self.hormone_levels = {'serotonin': 0, 'dopamine': 0, 'cortisol': 0, 'adrenaline': 0}
self.neuroplasticity = 0
def update_hormones_and_neuroplasticity(self):
for belief, state in self.beliefs.items():
if state == 'positive':
self.hormone_levels['serotonin'] += 1
self.hormone_levels['dopamine'] += 1
self.neuroplasticity += 1
elif state == 'negative':
self.hormone_levels['cortisol'] += 1
self.hormone_levels['adrenaline'] += 1
self.neuroplasticity -= 1
def get_current_state(self):
return {
'Hormone Levels': self.hormone_levels,
'Neuroplasticity': self.neuroplasticity
}
individual_beliefs = {
"capability": "positive",
"worthiness": "positive",
"changeability": "positive",
"self-doubt": "negative",
"fear of failure": "negative"
}
belief_hormone_neuroplasticity_simulator = BeliefHormoneNeuroplasticitySimulator(individual_beliefs)
belief_hormone_neuroplasticity_simulator.update_hormones_and_neuroplasticity()
current_state = belief_hormone_neuroplasticity_simulator.get_current_state()
print("Current State of Hormones and Neuroplasticity:", current_state)
|
# Polaris project
Polaris is Open API, HTML Web Server, based on the Rx, Netty, for non-blocking web application server
## Getting Started
### Prerequisites
- [JDK 11 +](https://jdk.java.net/)
- [MongoDB 4.4.X +](https://www.mongodb.com/download-center/community/releases)
- [Git (latest)](https://rogerdudler.github.io/git-guide/index.ko.html)
### Installing
```shell
cd <your project root path>
git clone https://bitbucket.org/andbut/polaris.git
```
### Editing mongodb configuration file
```text
Add path 'mongo home directory' to 'mongodb.home' key into the following file
<your project root path>/polaris/src/main/resources/config.dev.properties
Usage:
mongodb.home=/home/userhabit/app/mongodb-linux-x86_64-ubuntu2004-4.4.4
```
### S3 를 사용하는 경우 auth.keys
s3 를 사용하는 경우 `auth.keys`라는 이름의 파일을 `<server-root>` directory 에 넣어놔야 한다.
```aidl
<server-root>
|
+--- auth.keys
+--- bin/
+--- console/
+--- lib/
```
auth.keys 는 아래와 같은 내용을 가지고 있다.
```
$ cat auth.keys
s3.access_key=DFSGECN2OEDX3C5KE
s3.secret_key=fjdkslgjdfzTx+rxt8yGYkqiG9/J1QW1gCqmQF
```
### Running the server in dev mode
```shell
cd <your project root path>/polaris
./gradlew dev
# ./gradlew stage
# ./gradlew prod
# or for windows
./gradlew.bat dev
# with debug
./gradlew run --args="env=dev log.level=debug" # dev
#./gradlew run --args="env=stage log.level=debug"
#./gradlew run --args="env=prod log.level=debug"
```
### Running the benchmark test with the sample data
```shell
cd <your project root path>/polaris
# only one
./gradlew benchmark
# or for windows
./gradlew.bat benchmark
# multiple
./gradlew benchmark -Plimit=10000
```
### Running the client test by sample data
```shell
cd <your project root path>/polaris/src/main/resources/test
# session & event post,put(CrUd)
./polaris_sdk_post.sh |jq
# session get(cRud)
TOKEN="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6InRlc3QwMUB1c2VyaGFiaXQuaW8iLCJpYXQiOjE2MDU2OTE5NTcsImV4cCI6MTYwODI4Mzk1NywiYWlsIjpbImU2YzEwMWYwMjBlMTAxOGI1YmExN2NkYmUzMmFkZTJkNjc5YjQ0YmMiXX0.57HzpLuMlzxhohW7NOS1gfVt-Uvjvy_AClWSYfBr5AA"
FROM_DATE=$(date -d "-1 months" -u "+%Y-%m-%dT%H:%M:%SZ")
TO_DATE=$(date -d "0 months" -u "+%Y-%m-%dT%H:%M:%SZ")
# usage :curl -H "Authorization: Bearer <json token>" "localhost:8000/v3/session/<session id>?param=value" |jq
curl -H "Authorization: Bearer ${TOKEN}" "localhost:8000/v3/session/1_cf9f99b08d6744d9bd3fac192538c3c7?is_crash=true&from_date=${FROM_DATE}&to_date=${TO_DATE}&limit=2&skip=2" |jq
# event get(cRud)
# usage :curl -H "Authorization: Bearer <json token>" "localhost:8000/v3/event/<event id>?param=value" |jq
curl -H "Authorization: Bearer ${TOKEN}" "localhost:8000/v3/event?session_id_list=0_cf9f99b08d6744d9bd3fac192538c3c7&from_date=${FROM_DATE}&to_date=${TO_DATE}&limit=5&skip=2" | jq
```
### Deployment for production
```shell
./gradlew build
# usage :
# unzip ./build/distributions/polaris*.zip -d <target path>
unzip ./build/distributions/polaris*.zip -d ~/polaris/
cd ~/polaris/polaris*
./bin/polaris
# or for windows
./bin/polaris.bat
# with env, log.level
./bin/polaris env=dev log.level=debug
#./bin/polaris env=stage log.level=debug
#./bin/polaris env=prod log.level=debug
```
|
#ifndef __CLIENT_STUB_H__
#define __CLIENT_STUB_H__
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "serialization.h"
[struct_header]
typedef struct client
{
int socketFd;
} *client_t;
client_t create_client(char *client_addr, int client_port)
{
client_t client = (client_t) malloc(sizeof(struct client));
client->socketFd = socket(AF_INET, SOCK_STREAM, 0);
bool initialization;
if (setsockopt(client->socketFd, SOL_SOCKET, SO_REUSEADDR, &initialization, sizeof(int)) == -1)
{
printf("Error during socket configuration!\n");
free(client);
return NULL;
}
struct sockaddr_in serverAddr;
bzero(&serverAddr, sizeof(serverAddr));
serverAddr.sin_addr.s_addr = inet_addr(client_addr);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(client_port);
int connect_result = connect(client->socketFd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr_in));
if (connect_result < 0)
{
printf("Error during connection!\n");
free(client);
return NULL;
}
return client;
}
void close_client(client_t client)
{
if (client == NULL)
return;
shutdown(client->socketFd, 0);
free(client);
}
int rpc_send(client_t client, [struct_param]_t request, [struct_reply]_t response)
{
if (send(client->socketFd, request, sizeof(struct [struct_param]), 0) < 0)
{
printf("Unable to send request\n");
return -1;
}
printf("Sended request.\n");
if (recv(client->socketFd, response, sizeof(response), 0) < 0)
{
printf("Unable to receive response\n");
return -2;
}
return 0;
}
#endif
|
package mvc2;
//a/s 및 부품신청 게시판 글쓰기 컨트롤러
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;
import fileupload.FileUtil;
import utils.JSFunction;
public class WriteController2 extends HttpServlet{
//글쓰기 2번 글쓰기 뷰로 이동
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/pages/ComponentRequest.jsp").forward(req, resp);
}
//글쓰기4 dopost로 넘겨받은 폼값을 처리
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//글쓰기5.
//1. 파일 업로드 처리
//업로드 폴더의 물리적 경로를 확인 파일이 업로드 될 Uploads 폴더의 물리적인 경로를 확인
String saveDirectory = req.getServletContext().getRealPath("/Upload");
//web.xml에 컨텍스트 매개변수로 저장한 첨부파일의 최대용량 확인
ServletContext application = getServletContext();
int maxPostSize = Integer.parseInt(application.getInitParameter("maxPostSize"));
//글쓰기6. 파일업로드를 위해 FileUtil.uploadFile() 메소드를 호출
MultipartRequest mr = FileUtil.uploadFile(req, saveDirectory, maxPostSize);
//글쓰기9. 글쓰기8에서 리턴받은 결과가 공백이면
if(mr == null) {
//글쓰기10 만약 파일 업로드 실패하면
JSFunction.alertLocation(resp,"첨부 파일이 용량을 초과했습니다.", "../mvc2/writecomp.do");
return;
}
//글쓰기 15. 파일 업로드 외 처리 > 일반적인 글쓰기와 동일
//2. 파일 업로드 외 처리
//객체생성해서 dto
ComponentBoardDTO dto = new ComponentBoardDTO();
dto.setName(mr.getParameter("name"));
dto.setTitle(mr.getParameter("title"));
dto.setContent(mr.getParameter("content"));
dto.setPass(mr.getParameter("pass"));
dto.setMemberid(mr.getParameter("memberid"));
//글쓰기 16. 원본 파일명(ofile)과 저장된 파일명(sfile)설정
String fileName = mr.getFilesystemName("ofile");
//글쓰기 17. 첨부파일이 있으면
if(fileName != null) {
//글쓰기18 파일명을 변경하기 위해 새로운 파일명 생성
String now = new SimpleDateFormat("yyyyMMdd_HmsS").format(new Date());
String ext = fileName.substring(fileName.lastIndexOf("."));
String newFileName = now + ext;
//글쓰기19 저장된 파일명 변경/ 원래파일명과 저장된 파일명을 따로 기록함
File oldFile = new File(saveDirectory + File.separator + fileName);
File newFile = new File(saveDirectory + File.separator + newFileName);
oldFile.renameTo(newFile); //실제파일명이 변경되는 곳
dto.setOfile(fileName); //원래이름
dto.setSfile(newFileName); //서버에 저장된 새로운 파일이름
//글쓰기20. DAO를 통해 DB에 작성된 내용을 저장
ComponentBoardDAO dao = new ComponentBoardDAO();
//글쓰기24 dao의 insertWrite()메서드 실행하여 결과값 받아오기
int result = dao.insertWrite(dto);
dao.close();
//글쓰기25. 성공이냐 실패냐 >> 글쓰기 끝
if(result == 1 ) { //성공이면
resp.sendRedirect("../mvc2/listAS.do"); //성공하면 목록으로
}else { //실패면
//글쓰기 실패시 다시 글쓰기 창으로 보내줌
resp.sendRedirect("../mvc2/writecomp.do"); //글쓰기 창으로
}
//첨부파일이 없을 때
}else {
//글쓰기20. DAO를 통해 DB에 작성된 내용을 저장
ComponentBoardDAO dao = new ComponentBoardDAO();
//글쓰기24 dao의 insertWrite()메서드 실행하여 결과값 받아오기
int result = dao.insertWrite(dto);
dao.close();
//글쓰기25. 성공이냐 실패냐 >> 글쓰기 끝
if(result == 1 ) { //성공이면
resp.sendRedirect("../mvc2/listAS.do"); //성공하면 목록으로
}else { //실패면
//글쓰기 실패시 다시 글쓰기 창으로 보내줌
resp.sendRedirect("../mvc2/writecomp.do"); //글쓰기 창으로
}
}
}
}
|
export interface Product {
description: string;
price: number;
}
interface TaxCalculationsOptions {
tax: number;
products: Product[];
}
const phone: Product = {
description: 'Nokia A1',
price: 150.0,
};
const tablet: Product = {
description: 'ipad Air',
price: 250.0,
};
const shopingCart = [phone, tablet];
const tax = 0.15;
export function taxtCalculation(
options: TaxCalculationsOptions
): [number, number] {
let total = 0;
const { tax, products } = options;
products.forEach(({ price }) => {
total += price;
});
return [total, tax];
}
const [total, taxTotal] = taxtCalculation({
products: shopingCart,
tax: tax,
});
console.log('Total', total);
console.log('Taxt', taxTotal);
|
package com.edu.forwad.sec06.ex02;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//-----------------------------------------------------------------------------------------------------------
//loadOnStartup=1 ==> 서블릿들 간에 초기화 우선 순위
//여러 서블릿들 사이에 <load-on-starup>값이 동일한 경우 web.xml에 먼저 선언된 서블릿이 먼저 초기화 된다.
//-----------------------------------------------------------------------------------------------------------
@WebServlet(name="loadConfig", urlPatterns = {"/loadConfig"}, loadOnStartup=1)
public class LoadAppConfig extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletContext context;
//-----------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
public void init(ServletConfig config) throws ServletException {
System.out.println("LoadAppConfig의 init 메서드를 호출하였습니다.");
context = config.getServletContext();
String menu_member = context.getInitParameter("menu_member");
String menu_order = context.getInitParameter("menu_order");
String menu_goods = context.getInitParameter("menu_goods");
context.setAttribute("menu_member", menu_member);
context.setAttribute("menu_order", menu_order);
context.setAttribute("menu_goods", menu_goods);
}
//-----------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String menu_member = (String) context.getAttribute("menu_member");
String menu_order = (String) context.getAttribute("menu_order");
String menu_goods = (String) context.getAttribute("menu_goods");
out.print("<html>");
out.print("<body>");
out.print("<h1>파일에서 메뉴 불러오기</h1>");
out.print("<table border=1 cellspacing=0>");
out.print("<tr>메뉴 목록</tr>");
out.print("<tr><td><h3>" + menu_member + "</h3></td></tr>");
out.print("<tr><td><h3>" + menu_order + "</h3></td></tr>");
out.print("<tr><td><h3>" + menu_goods + "</h3></td></tr>");
out.print("</table>");
out.print("</body>");
out.print("</html>");
}
}
|
import { DownOutlined } from '@ant-design/icons';
import { Menu, Dropdown, Button } from 'antd';
import { BigNumber } from 'bignumber.js';
import React from 'react';
import { tezosMeta, unknownAssetMeta } from '@tezospayments/common';
import { getTokenBalanceDiff } from '../../../store/balances/helpers';
import { selectBalancesState } from '../../../store/balances/selectors';
import { selectTokensState } from '../../../store/currentPayment/selectors';
import { selectSwapState } from '../../../store/swap/selectors';
import { useAppSelector } from '../../hooks';
import './TokenSwapper.scss';
interface TokenSwapperProps {
amount: BigNumber;
payAsset: string;
swapAsset?: string;
onSwapAssetChange?: (value: string) => void;
}
export const TokenSwapper = (props: TokenSwapperProps) => {
const balances = useAppSelector(selectBalancesState);
const diff = getTokenBalanceDiff(props.payAsset, props.amount, balances);
const insufficientAmount = BigNumber.max(diff.multipliedBy(-1), 0);
const tokens = useAppSelector(selectTokensState);
const ticker = props.payAsset ? (tokens.get(props.payAsset)?.metadata || unknownAssetMeta).symbol : tezosMeta.symbol;
const swapTokensState = useAppSelector(selectSwapState);
const assets: Array<{ ticker: string; name: string; value: string; imageUrl: string, amount: BigNumber }> = [];
if (swapTokensState?.tezos)
assets.push({ value: '', ticker: tezosMeta.symbol, name: tezosMeta.name, imageUrl: tezosMeta.thumbnailUri, amount: swapTokensState.tezos });
tokens.forEach(t => {
if (t.metadata) {
const amount = swapTokensState ? swapTokensState.tokens?.[t.contractAddress] : null;
if (amount) {
assets.push({
value: t.contractAddress,
ticker: t.metadata.symbol,
name: t.metadata.name,
imageUrl: t.metadata.thumbnailUri,
amount
});
}
}
});
const selectedAsset = assets.find(a => a.value === props.swapAsset);
const menu = <Menu>
{assets.map(a => <Menu.Item className="token-swapper-menu-item" key={a.value} onClick={() => props.onSwapAssetChange?.(a.value)}>
<span className="token-swapper-menu-item__icon">{a.amount.toString()}</span>
<img className="token-swapper-menu-item__icon" src={a.imageUrl} alt={a.ticker} />
<span className="token-swapper-menu-item__ticker">{a.ticker}</span>
<span className="token-swapper-menu-item__name">{a.name}</span>
</Menu.Item >)}
</Menu>;
return <div className="token-swapper">
<span>Not enough {insufficientAmount.toString()} {ticker}</span>
{assets.length > 0 && <div className="token-swapper__swap-line">
<div>Swap</div>
<div className="token-swapper__input-container">
<Dropdown trigger={['click']} overlay={menu} placement="bottomRight">
<Button className="token-swapper__container">
<div className="token-swapper__currency">
<span className="token-swapper__amount">{selectedAsset?.amount.toString()}</span>
<img className="token-swapper__icon" src={selectedAsset?.imageUrl} alt={selectedAsset?.ticker} />
<span className="token-swapper__ticker">{selectedAsset?.ticker}</span>
</div>
<DownOutlined />
</Button>
</Dropdown>
</div>
</div>}
</div >;
};
export const TokenSwapperPure = React.memo(TokenSwapper);
|
package com.example.myapplication.di
import android.content.Context
import androidx.room.Room
import com.example.myapplication.data.local.EmployeeDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Named
@Module
@InstallIn(SingletonComponent::class)
object TestAppModule {
@Provides
@Named("test_db")
fun provideInMemoryDb(@ApplicationContext context: Context) =
Room.inMemoryDatabaseBuilder(context, EmployeeDatabase::class.java)
.allowMainThreadQueries()
.build()
}
|
import configparser
from dataclasses import dataclass
from enum import Enum
from typing import Dict, Union
from src.main.cdp.common.exceptions import NotImplementedException
from src.main.cdp.utils.s3_utils import get_client, read_s3_file
class ConfigFile(Enum):
LOGGER_START_MSG = "base.logger_start_msg"
LOGGER_END_MSG = "base.logger_end_msg"
REQUIRED_PARAMS = "base.required_params"
OPTIONAL_PARAMS = "base.optional_params"
class InputOutType(Enum):
# directory
S3_DIR_CSV = "s3-dir-csv"
S3_DIR_TSV = "s3-dir-tsv"
S3_DIR_TXT = "s3-dir-txt"
S3_DIR_FIXED = "s3-dir-fixed"
S3_DIR_PARQUET = "s3-dir-parquet"
# table
CATALOG = "catalog"
MYSQL = "mysql"
REDSHIFT = "redshift"
# file
S3_CSV = "s3-csv"
S3_TSV = "s3-tsv"
S3_TEXT = "s3-text"
S3_FIXED = "s3-fixed"
class InputOutputConfig(Enum):
TYPE = "type"
BUCKET = "bucket"
PATH = "path"
TABLE_NAME = "table_name"
REQUIRED = "required"
SCHEMA = "schema"
ERROR_MSG = "error_msg"
SUCCESS_MSG = "success_msg"
class ConfigType(Enum):
S3 = "s3"
LOCAL = "local"
@dataclass
class Config:
config_type: str
bucket: Union[None, str]
prefix: Union[None, str]
file_path: Union[None, str]
def load_config(self) -> Dict[str, str]:
if self.config_type == ConfigType.S3.value and self.bucket is not None and self.prefix is not None:
return self.load_config_from_s3(self.bucket, self.prefix)
elif self.config_type == ConfigType.LOCAL.value and self.file_path is not None:
return self.load_config_from_file(self.file_path)
else:
raise NotImplementedException()
def load_config_from_file(self, file_path: str) -> Dict[str, str]:
config = configparser.ConfigParser()
config.read(file_path)
return self.read_config_to_dict(config)
def load_config_from_s3(self, bucket: str, prefix: str) -> Dict[str, str]:
content = read_s3_file(get_client(), bucket, prefix)
config = configparser.ConfigParser()
config.read_string(content)
return self.read_config_to_dict(config)
def read_config_to_dict(self, config: configparser.ConfigParser) -> Dict[str, str]:
config_dict: Dict[str, str] = {}
for section in config.sections():
for option in config.options(section):
config_dict[f"{section}.{option}"] = config.get(section, option)
return config_dict
|
import argparse
import os
import torch
import evaluate
import random
from transformers import AutoTokenizer, PreTrainedTokenizerBase
from utils.base_poet_models import PoetModelBase
from corpus_capsulated_datasets import CorpusDatasetPytorch
parser = argparse.ArgumentParser()
parser.add_argument("--model_path_full", default=os.path.abspath(os.path.join(os.path.dirname(__file__), 'backup_LMS', 'CZ-New-Syllable-BPE-NormalText-gpt-cz-poetry-all-e4e16_LM')), type=str, help="Path to Model")
parser.add_argument("--sample", default=True, type=bool, help="If to sample during generation")
parser.add_argument("--data_path", default=os.path.abspath(os.path.join(os.path.dirname(__file__), "corpusCzechVerse", "ccv")), type=str, help="Path to Data")
#parser.add_argument("--reference_model", default='lchaloupsky/czech-gpt2-oscar', type=str, help="Model to measure perplexity")
parser.add_argument("--reference_model", default='BUT-FIT/csmpt7b', type=str, help="Model to measure perplexity")
#parser.add_argument("--reference_model", default='simecek/cswikimistral_0.1', type=str, help="Model to measure perplexity")
parser.add_argument("--result_file", default= os.path.abspath(os.path.join(os.path.dirname(__file__),'results_new', "model_perplexity.txt")), type=str, help="Where to store the decoding efforts")
parser.add_argument("--num_runs", default=10_000, type=int, help="Number of runs per setting")
if __name__ == "__main__":
args = parser.parse_args([] if "__file__" not in globals() else None)
_ ,model_rel_name = os.path.split(args.model_path_full)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
with torch.no_grad():
model = PoetModelBase(args.model_path_full).to(device)
model.eval()
# Load LM tokenizers
tokenizer: PreTrainedTokenizerBase = AutoTokenizer.from_pretrained(args.model_path_full)
def remove_params(gen_poem:str):
lines = gen_poem.splitlines()[1:]
lines = list(filter(lambda x: x, lines))
lines = [line.split('#')[-1].strip() for line in lines ]
return "\n".join(lines)
def decoder_helper(type, rhyme, year, meter):
if type == "BASIC":
start = f"# {rhyme} # {year}\n{meter}"
tokenized = tokenizer.encode(start, return_tensors='pt', truncation=True)
out = model.model.generate(tokenized.to(device),
max_length=512,
do_sample=True,
top_k=50,
eos_token_id = tokenizer.eos_token_id,
early_stopping=True,
pad_token_id= tokenizer.pad_token_id)
return tokenizer.decode(out.cpu()[0], skip_special_tokens=True)
if type=="FORCED":
start_forced = f"# {rhyme} # {year}\n{meter} #"
return model.generate_forced(start_forced, tokenizer, verse_len=len(rhyme), sample=True, device=device)
dataset = CorpusDatasetPytorch('BASE', data_dir=args.data_path)
sampled_data = random.choices(dataset.test_strophes, k=args.num_runs)
ground = list(filter(lambda x: x, [remove_params(datum['input_ids']) for datum in sampled_data]))
generated_basic = list(filter(lambda x: x, [remove_params(decoder_helper("BASIC", datum['rhyme'], datum['year'], datum['metre_ids'][0])) for datum in sampled_data]))
generated_forced = list(filter(lambda x: x, [remove_params(decoder_helper("FORCED", datum['rhyme'], datum['year'], datum['metre_ids'][0])) for datum in sampled_data]))
perplexity = evaluate.load("perplexity", module_type="metric")
results_ground = perplexity.compute(model_id=args.reference_model,
add_start_token=False,
predictions=ground)
results_basic = perplexity.compute(model_id=args.reference_model,
add_start_token=False,
predictions=generated_basic)
results_forced = perplexity.compute(model_id=args.reference_model,
add_start_token=False,
predictions=generated_forced)
with open(args.result_file, 'a', encoding="utf-8") as file:
print(f"==== MODEL: {model_rel_name} ==== REFERENCE MODEL: {args.reference_model} ==== SAMPLES: {args.num_runs} ====", file=file)
print(f"GROUND PERPLEXITY: {results_ground['mean_perplexity']}, BASIC GEN PER: {results_basic['mean_perplexity']}, FORCED GEN PER: {results_forced['mean_perplexity']}\n", file=file)
|
import 'package:flutter/material.dart';
import 'package:smart_mobapp/fungsi/color_theme.dart';
class ReusableTextField extends StatefulWidget {
final String text;
final bool isPasswordType;
final TextEditingController controller;
const ReusableTextField({
Key? key,
required this.text,
required this.isPasswordType,
required this.controller,
}) : super(key: key);
@override
_ReusableTextFieldState createState() => _ReusableTextFieldState();
}
class _ReusableTextFieldState extends State<ReusableTextField> {
bool obscureText = false;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: TextField(
controller: widget.controller,
obscureText: obscureText,
enableSuggestions: !widget.isPasswordType,
autocorrect: !widget.isPasswordType,
cursorColor: LightTheme.primacCyan,
style: const TextStyle(color: LightTheme.primacCyan),
decoration: InputDecoration(
labelText: widget.text,
labelStyle: const TextStyle(color: LightTheme.primacCyan),
filled: true,
floatingLabelBehavior: FloatingLabelBehavior.never,
fillColor: LightTheme.themeWhite,
contentPadding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(
color: LightTheme.primacCyan,
width: 2,
),
),
suffixIcon: widget.isPasswordType
? Padding(
padding: const EdgeInsets.only(left: 8.0),
child: IconButton(
icon: Icon(
obscureText ? Icons.visibility : Icons.visibility_off,
color: LightTheme.primacCyan,
),
onPressed: () {
setState(() {
obscureText = !obscureText;
});
},
),
)
: null,
),
keyboardType: widget.isPasswordType
? TextInputType.visiblePassword
: TextInputType.emailAddress,
),
);
}
}
|
from django.db import models
from user_api.models import CustomUser
from django.utils.translation import gettext_lazy as _
from datetime import datetime
def upload_to(instance, filename):
return 'posts/{filename}/{date}'.format(filename=filename, date=datetime.utcnow())
# Create your models here.
class BaseModel(models.Model):
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(auto_now=True, null=False)
updated_at = models.DateTimeField(auto_now=True, null=False)
class Meta:
abstract = True
class Category(BaseModel):
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name
class Tag(BaseModel):
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name
class Blog(BaseModel):
author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
title = models.CharField(max_length=100, null=False)
content = models.TextField(null=False)
image = models.ImageField(_("Image"), upload_to=upload_to, default='default.jpg')
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1)
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.title
class Comment(BaseModel):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
content = models.TextField(null=False)
def __str__(self):
return f"Comment by {self.author.username} on {self.blog.title}"
|
import React, { useState, useEffect, useReducer } from 'react'
import { v4 as uuidv4 } from 'uuid'
import './App.css'
import ToDoList from './components/ToDoList'
import ToDoForm from './components/ToDoForm'
// reducers
import todoReducer from './ToDoReducer'
import ListReducer from './ListReducer'
import List from './components/List'
import ListForm from './components/ListForm'
function App () {
const [todos, toDoDispatch] = useReducer(todoReducer, [])
const [lists, listDispatch] = useReducer(ListReducer, getItems())
const [name, setName] = useState('')
const [currentId, setCurrentId] = useState(0)
useEffect(() => console.log('todos:',todos), [todos])
useEffect(() => console.log('lists:',lists), [lists])
useEffect(() => console.log('name:',name), [name])
useEffect(() => console.log('currentId:',currentId), [currentId])
const handleSubmit = (newTask) => {
toDoDispatch({
type: 'added',
id: uuidv4(),
task: newTask
})
}
const handleDelete = (id) => {
toDoDispatch({
type: 'deleted',
id
})
}
const handleSaveList = () => {
if (currentId) {
listDispatch({
type: 'changedList',
id: currentId,
list: todos,
name
})
} else {
const newId = uuidv4();
setCurrentId(newId)
listDispatch({
type: 'addedList',
id: newId,
list: todos,
name
})
}
}
useEffect(() => {
listDispatch({
type: 'changedList',
id: currentId,
list: todos,
name
})
}, [name])
const handleNameChange = (e) => {
const event = e.target.value
setName(event);
}
useEffect(() => {
localStorage.setItem('lists', JSON.stringify(lists))
}, [lists])
const handleCreateList = () => {
listDispatch({
type: 'changedList',
id: currentId,
list: todos,
name
})
toDoDispatch({
type: 'create'
})
const newId = uuidv4();
setCurrentId(newId)
listDispatch({
type: 'addedList',
id: newId,
list: todos,
name: 'Untitled'
})
setName('')
}
const handleSetCurrentList = (tlist) => {
listDispatch({
type: 'changedList',
id: currentId,
list: todos,
name
})
toDoDispatch({
type: 'set',
list: tlist.list
})
setCurrentId(tlist.id);
setName(tlist.name);
}
const handleDeleteList = (id) => {
listDispatch({
type: 'deletedList',
id
})
if(id === currentId){
toDoDispatch({
type: 'create'
})
setCurrentId(0);
}
}
return (
<section id='all' >
<section id='all-1'>
<section id='list-section' >
<h1>ListWave</h1>
<button onClick={handleCreateList}
id='create-button' >create list
</button>
</section>
<List lists={lists}
handleSetCurrentList={handleSetCurrentList}
handleDeleteList={handleDeleteList}
handleSaveList={handleSaveList}
/>
</section>
{currentId !== 0 &&
<section id='all-2'>
<aside id='forms'>
<ListForm name={name}
handleNameChange={handleNameChange}
handleSaveList={handleSaveList}
/>
<ToDoForm handleSubmit={handleSubmit} currentId={currentId}/>
</aside>
<ToDoList toDoList={todos}
handleDelete={handleDelete}
dispatch = {toDoDispatch}
currentId={currentId} />
</section>
}
</section>
)
}
const getItems = () => {
const storedToDoList = localStorage.getItem('lists')
return storedToDoList ? JSON.parse(storedToDoList) : []
}
export default App
|
#include "main.h"
/**
* flip_bits:- Count number of bit used to be
* flipped to get from one number to another.
* @n:- Number Values.
* @m:- Number to be flip n to.
*
* Return: Necessary number of bit to flip to get from n to m.
*/
unsigned int flip_bits(unsigned long int n, unsigned long int m)
{
unsigned long int xor = n ^ m, bits = 0;
while (xor > 0)
{
bits += (xor & 1);
xor >>= 1;
}
return (bits);
}
|
import React, { useEffect, useState } from 'react'
import useRequestData from '../hooks/useRequestData'
import parse from 'html-react-parser';
import Book from '../components/Book';
import { Link } from 'react-router-dom';
import Error from '../components/Error';
import Loader from '../components/Loader'
const Services = () => {
const [expandedCards, setExpandedCards] = useState({});
const { data, isLoading, error, makeRequest } = useRequestData();
const { data: dataService, isLoading: isLoadingService, error: errorService, makeRequest: makeRequestService } = useRequestData()
useEffect(() => {
makeRequest("http://localhost:5029/treatment")
makeRequestService("http://localhost:5029/treatment")
}, [])
const limitWords = (text, limit) => {
const words = text.split(' ');
if (words.length > limit) {
return words.slice(0, limit).join(' ') + '...';
}
return text;
};
const toggleCard = (index) => {
setExpandedCards(prevState => ({
...prevState,
[index]: !prevState[index]
}));
};
return (
<>
<section className='serviceContainer'>
<div className='serviceHeading'>
<img className="serviceHeadingImage" src="/public/assets/butterfly.png" alt="butterfly" />
<h1>Treatment</h1>
<p className='serviceHeading'>To doesn´t his appear replenish together called he of mad place won´t <br />
wherein blessed second every wherein were meat kind wherein and martcin</p>
<div className="line serviceLine"></div>
</div>
<div className="treatmentCardContainer">
{isLoading && <Loader />}
{error && <Error />}
{data?.map((cardItem, index) => (
<div className="treatmentCard" key={index}>
<img className='treatmentCardImage' src={`http://localhost:5029/images/treatment/${cardItem.image}`} alt="treatment product images" />
<div className='treatmentCardContent'>
<h2>{cardItem.title}</h2>
{expandedCards[index]
? parse(cardItem.content)
: parse(limitWords(cardItem.content, 15))}
</div>
<div className='btnContainer'>
<div>{cardItem.content.split(' ').length > 20 && (
<button onClick={() => toggleCard(index)} className='btn serviceCardShowMoreBtn'>
{expandedCards[index] ? "Vis mindre" : "Læs mere"}
</button>
)}</div>
<div>
<a href="#book" className='btn serviceCardBookBtn'>
Book
</a>
</div>
</div>
</div>
))}
</div>
<div id='book'>
<Book />
</div>
</section>
</>
)
}
export default Services
|
#include "U8glib.h"
#include <SPI.h> //SPI?
#include <nRF24L01.h>//Radio
#include <RF24.h> //Radio
//set up OLED display on pins 3,4,5,6
U8GLIB_NHD31OLED_GR u8g(4, 5, 6, 3);
// Set up nRF24L01 radio on SPI bus plus pins 9 & 10
RF24 radio(9, 10);
// Radio pipe addresses for the 2 nodes to communicate.
const uint64_t pipes[2] = {
0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL};
char summaryStr[27];
char timeStr[10];
char locationStr[22];
void setup() {
//Serial.begin(9600);
u8g.setContrast(255);
u8g.setDefaultForegroundColor();
radio.begin();
// optionally, increase the delay between retries & # of retries
radio.setRetries(15, 15);
// optionally, reduce the payload size. seems to improve reliability
radio.setPayloadSize(28);
// This simple sketch opens two pipes for these two nodes to communicate
// back and forth.
// Open 'our' pipe for writing
// Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading)
radio.openWritingPipe(pipes[1]);
radio.openReadingPipe(1, pipes[0]);
radio.startListening();
}
bool done = false;
unsigned long started_waiting_at = millis();
void loop() {
// if there is data ready
if ( radio.available() ) {
bool timeout = false;
started_waiting_at = millis();
bool readSummary = false;
bool readTime = false;
bool readLoc = false;
while (!timeout ) {
if (!readSummary ) {
done = radio.read( &summaryStr, sizeof(summaryStr));
readSummary = true;
// Serial.print(millis()-started_waiting_at);
// Serial.println(radio.available());
//Serial.print(" Got Summary: ");
// Serial.println(summaryStr);
}
else if (!readTime && radio.available()) {
done = radio.read( &timeStr, sizeof(timeStr));
readTime = true;
// Serial.print(millis()-started_waiting_at);
// Serial.println(radio.available());
// Serial.print(" Got Time: ");
// Serial.println(timeStr);
}
else if (!readLoc && radio.available()) {
done = radio.read( &locationStr, sizeof(locationStr));
readLoc = true;
//Serial.print(millis()-started_waiting_at);
//Serial.println(radio.available());
//Serial.print("Got Location: ");
//Serial.println(locationStr);
}
else {
delay(10);
}
if (millis() - started_waiting_at >= 500 ) {
timeout = true;
}
}
if (readSummary && readLoc && readTime) {
// Serial.println("Success");
// Serial.println(summaryStr);
// Serial.println(timeStr);
// Serial.println(locationStr);
//Draw input on display
u8g.firstPage();
do {
draw();
} while ( u8g.nextPage() );
}
else {
//Serial.println("Failure");
}
clearStrings();
}
}
void draw(void) {
u8g.setFont(u8g_font_fur14r);
u8g.setPrintPos(1, 20);
u8g.print(summaryStr);
// u8g.setFont(u8g_font_fur14r);
// u8g.setPrintPos(5,60);
// u8g.print(mode2);
u8g.setFont(u8g_font_profont10);
u8g.drawStr(1, 40, "At:");
u8g.setFont(u8g_font_fur11r);
u8g.setPrintPos(1, 63);
u8g.print(locationStr);
u8g.setFont(u8g_font_profont10);
u8g.drawStr(170, 40, "Until:");
u8g.setFont(u8g_font_fur11r);
u8g.setPrintPos(170, 63);
u8g.print(timeStr);
}
void clearStrings() {
for( int i = 0; i < sizeof(summaryStr); i++ )
summaryStr[i] = ' ';
for( int i = 0; i < sizeof(timeStr); i++ )
timeStr[i] = ' ';
for( int i = 0; i < sizeof(locationStr); i++ )
locationStr[i] = ' ';
}
|
<template>
<div>
<p class="mt-0 uppercase font-bold text-slate-400 mb-1">
Lesson {{ chapter.number }} - {{ lesson.number }}
</p>
<h2 class="my-0">{{ lesson.title }}</h2>
<div class="flex space-x-4 mt-2 mb-8">
<NuxtLink
v-if="lesson.sourceUrl"
class="font-normal text-md text-gray-500"
:href="lesson.sourceUrl"
>Download Source Code
</NuxtLink
>
</div>
<NuxtLink
v-if="lesson.downloadUrl"
class="font-normal text-md text-gray-500"
:to="lesson.downloadUrl"
>
Download Video
</NuxtLink>
<VideoPlayer v-if="lesson.videoId" :videoId="lesson.videoId"/>
<p>{{ lesson.text }}</p>
<ClientOnly>
<LessonCompleteButton
:model-value="isLessonComplete"
@update:model-value="toggleComplete"
/>
</ClientOnly>
</div>
</template>
<script setup>
const course = useCourse();
const route = useRoute();
definePageMeta({
middleware: function (to, from) {
const course = useCourse();
const route = useRoute();
const chapter = course.chapters.find(
(chapter) => chapter.slug === to.params.chapterSlug
);
// error no server side
if (!chapter) {
return abortNavigation(
createError({
statusCode: 404,
message: 'Chapter not found from definePageMeta'
})
)
}
console.log('url route', to.params.lessonSlug,)
const lesson = chapter.lessons.find((lesson) => {
return lesson.slug === to.params.lessonSlug;
});
console.log('lesson aqui', lesson)
// error no server side
if (!lesson) {
return abortNavigation(
createError({
statusCode: 404,
message: 'Lesson not found from definePageMeta'
})
)
}
}
});
const chapter = computed(() => {
return course.chapters.find((chapter) => {
return chapter.slug === route.params.chapterSlug;
});
});
// error no server side
// if (!chapter.value) {
// throw createError({
// statusCode: 404,
// message: "Chapter not found",
// });
// }
const lesson = computed(() => {
return chapter.value.lessons.find((lesson) => {
return lesson.slug === route.params.lessonSlug;
});
});
// error no server side
// if (!lesson.value) {
// throw createError({
// statusCode: 404,
// message: "Lesson not found",
// });
// }
const title = computed(() => {
return `${lesson.value.title} - ${course.title}`;
});
useHead({
title: title,
});
const progress = useLocalStorage("progress", []);
const isLessonComplete = computed(() => {
if (!progress.value[chapter.value.number - 1]) {
return false;
}
if (!progress.value[chapter.value.number - 1][lesson.value.number - 1]) {
return false;
}
return progress.value[chapter.value.number - 1][lesson.value.number - 1];
});
const toggleComplete = () => {
if (!progress.value[chapter.value.number - 1]) {
progress.value[chapter.value.number - 1] = [];
}
progress.value[chapter.value.number - 1][lesson.value.number - 1] =
!isLessonComplete.value;
};
</script>
<style lang="scss" scoped></style>
|
import os
import tensorflow
os.environ['KERAS_BACKEND'] = 'tensorflow'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # 3 = INFO, WARNING, and ERROR messages are not printed
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from keras.preprocessing.image import ImageDataGenerator
dataset = pd.read_csv('../input/driver_imgs_list.csv')
dataset.head(5)
import os
from IPython.display import display, Image
import matplotlib.image as mpimg
activity_map = {'c0': 'Safe driving',
'c1': 'Texting - right',
'c2': 'Talking on the phone - right',
'c3': 'Texting - left',
'c4': 'Talking on the phone - left',
'c5': 'Operating the radio',
'c6': 'Drinking',
'c7': 'Reaching behind',
'c8': 'Hair and makeup',
'c9': 'Talking to passenger'}
plt.figure(figsize = (12, 20))
image_count = 1
BASE_URL = '../input/imgs/train/'
for directory in os.listdir(BASE_URL):
if directory[0] != '.':
for i, file in enumerate(os.listdir(BASE_URL + directory)):
if i == 1:
break
else:
fig = plt.subplot(5, 2, image_count)
image_count += 1
image = mpimg.imread(BASE_URL + directory + '/' + file)
plt.imshow(image)
plt.title(activity_map[directory])
classifier = Sequential()
classifier.add(Conv2D(filters = 128, kernel_size = (3, 3), activation = 'relu', input_shape = (240, 240, 3), data_format = 'channels_last'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Conv2D(filters = 64, kernel_size = (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Conv2D(filters = 32, kernel_size = (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Flatten())
classifier.add(Dense(units = 1024, activation = 'relu'))
classifier.add(Dense(units = 256, activation = 'relu'))
classifier.add(Dense(units = 10, activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])
classifier.summary()
train_datagen = ImageDataGenerator(rescale = 1.0/255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True,
validation_split = 0.2)
training_set = train_datagen.flow_from_directory('../input/imgs/train',
target_size = (240, 240),
batch_size = 32,
subset = 'training')
validation_set = train_datagen.flow_from_directory('../input/imgs/train',
target_size = (240, 240),
batch_size = 32,
subset = 'validation')
classifier.fit_generator(training_set,
steps_per_epoch = 17943/32,
epochs = 10,
validation_data = validation_set,
validation_steps = 4481/32)
classifier.save_weights("model.h5")
# serialize model to JSON
model_json = classifier.to_json()
with open("model.json", "w") as json_file:
json_file.write(model_json)
# load json and create model
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model.h5")
print("Loaded model from disk")
from PIL import Image
def get_data(image_path):
img = Image.open(image_path)
img = img.resize((240, 240), Image.ANTIALIAS) # resizes image in-place
return np.asarray(img)/255
test_file = pd.read_csv('../input/sample_submission.csv')
test_file.head(5)
for i, file in enumerate(test_file['img']):
image = get_data('../input/imgs/test/' + file)
image = np.reshape(image, (1, image.shape[0], image.shape[1], image.shape[2]))
result = classifier.predict(image)
test_file.iloc[i, 1:] = result[0]
test_file.to_csv('results.csv', index = False)
|
{{-- Hablo el layout menu para luego poner en los
contenedores correspondientes su informacion
en este caso titulo y contenido --}}
@extends('layouts.menu')
<!-- Mando agregar en el contenedor titulo lo siguiente -->
@section('titulo')
Crear un costo variable
@endsection
<!-- Mando agregar en el contenedor contenido lo siguiente -->
@section('contenido')
<div class="max-w-md mx-auto bg-gray-200 p-8 border rounded-md shadow-md">
{{-- Formulario que envia a guardar el nuevo costo variable --}}
<form action="{{route('costos_variables.store')}}" method="POST">
@csrf
{{-- Combo box para su formulario --}}
<div class="mb-4">
<label for="id_financiero" class="block text-dark text-sm font-bold mb-2">ID Financiero:</label>
<select name="id_financiero" id="id_financiero" class="w-full px-4 py-2 border rounded-md">
{{-- Solo sirve como mensaje para que selecione otro --}}
<option value=" ">Selecciona un estudio financiero</option>
{{-- Guardo el nombre y el id del estudio financiero para que pueda seleccionar
de los que ya estan en la base de datos --}}
@foreach ($estudiosFinancieros as $datofinanciero)
<option value="{{ $datofinanciero->id }}">{{ $datofinanciero->name }}</option>
@endforeach
</select>
</div>
{{-- Si hay un error mostrara lo siguiente --}}
@error('id_financiero')
<p class="bg-red-500 text-white rounded-lg text-sm p-2 text-center">
{{ $message }}
</p>
@enderror
{{-- Input para el nombre --}}
<div class="mb-4">
<label for="name" class="block text-dark text-sm font-bold mb-2">Nombre:</label>
<input type="text" name="name" id="name" class="w-full px-4 py-2 border rounded-md">
</div>
{{-- Muestra esto si hay un error con el nombre --}}
@error('name')
<p class="bg-red-500 text-white rounded-lg text-sm p-2 text-center">
{{ $message }}
</p>
@enderror
{{-- Input para el mes --}}
<div class="mb-4">
<label for="month" class="block text-dark text-sm font-bold mb-2">Mes:</label>
<select name="month" id="month" class="w-full px-4 py-2 border rounded-md">
<!-- Opciones del combo box (del 1 al 12) -->
@for ($i = 1; $i <= 12; $i++)
<option value="{{ $i }}">{{ $i }}</option>
@endfor
</select>
</div>
{{-- Muestra un error si hay con meses --}}
@error('month')
<p class="bg-red-500 text-white rounded-lg text-sm p-2 text-center">
{{ $message }}
</p>
@enderror
{{-- Input para la cantidad --}}
<div class="mb-4">
<label for="amount" class="block text-dark text-sm font-bold mb-2">Cantidad:</label>
<input type="text" name="amount" id="amount" class="w-full px-4 py-2 border rounded-md">
</div>
{{-- muestra erro si hay con amount --}}
@error('amount')
<p class="bg-red-500 text-white rounded-lg text-sm p-2 text-center">
{{ $message }}
</p>
@enderror
{{-- Boton para guardar el nuevo costo variable --}}
<div class="flex items-center justify-between">
<button type="submit" class="px-4 py-2 w-full bg-blue-500 text-white rounded-md cursor-pointer">Guardar</button>
</div>
</form>
</div>
@endsection
|
import 'package:day_night_switcher/day_night_switcher.dart';
import 'package:flutter/material.dart';
import 'package:habit_tracker/Models/dark_light.dart';
import 'package:provider/provider.dart';
class Switcher extends StatefulWidget {
Switcher({Key? key, required this.callback}) : super(key: key);
VoidCallback callback;
@override
State<Switcher> createState() => _SwitcherState();
}
class _SwitcherState extends State<Switcher> {
@override
Widget build(BuildContext context) {
final themeProvider = Provider.of<ThemeController>(context);
return DayNightSwitcher(
isDarkModeEnabled: themeProvider.isDark,
onStateChanged: (newBool) {
final provider = Provider.of<ThemeController>(context, listen: false);
provider.toggleDark();
});
}
}
class SwitcherMini extends StatefulWidget {
const SwitcherMini({Key? key, required this.callback}) : super(key: key);
final VoidCallback callback;
@override
State<SwitcherMini> createState() => _SwitcherMiniState();
}
class _SwitcherMiniState extends State<SwitcherMini> {
@override
Widget build(BuildContext context) {
final themeProvider = Provider.of<ThemeController>(context);
return DayNightSwitcherIcon(
isDarkModeEnabled: themeProvider.isDark,
onStateChanged: (newBool) {
final provider = Provider.of<ThemeController>(context, listen: false);
provider.toggleDark();
widget.callback();
});
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.