text
stringlengths 184
4.48M
|
---|
<?php
declare(strict_types=1);
namespace Src\Broadcasting\Mail;
use Src\Core\Additional\EmailSender;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Src\Models\Views\EmailTemplate;
/**
* Class ParkManagerInsuranceDaysLeftMail
* @package Src\Mail
*/
class ParkManagerInsuranceDaysLeftMail extends Mailable
{
use Queueable;
use SerializesModels;
public $tries = 1;
/**
* @var EmailSender
*/
protected EmailSender $body;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($car, $days)
{
$props = [
'days' => $days,
'mark' => $car->mark,
'model' => $car->model,
'vin_code' => $car->vin_code,
'drivers' => $car->drivers->implode('name', ', '),
];
$this->body = new EmailSender(EmailTemplate::INSPECTION_DAYS_LEFT_PARK_ADMIN, $props);
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('vendor.mail.client-code-agree', ['body' => $this->body]);
}
}
|
/**
* @file milis.h
* @brief Datoteka koja deklarise funkcije za upravljanje vremenom (milisekundi)
* @author David Arsenijevic
* @date 16-5-2021
* @version 1.0
*/
#ifndef TIMER0_H_
#define TIMER0_H_
#include <avr/io.h>
#include <avr/interrupt.h>
/// Promenljiva koja skladisti broj milisekundi proteklih od pokretanja aplikacije
volatile unsigned long ms = 0;
/**
* timer0DelayMs - Funkcija koja implementira pauzu u broju milisekundi koji je prosledjen
* kao parametar
* @param delay_length - ulaz tipa unsigned long - Duzina pauze u milisekundama
* @return Povratna vrednost je tipa unsigned long i ima vrednost broja milisekundi
* proteklih od pocetka aplikacije do trenutka izlaska iz funkcije
*/
unsigned long timer0DelayMs(unsigned long delay_length);
/**
* timer0InteruptInit - Funkcija koja inicijalizuje timer 0 tako da pravi prekide
* svake milisekunde
* @return Nema povratnu vrednost
*/
void timer0InteruptInit();
/**
* calculateHalfPeriod - Funkcija koja izracunava polovinu prosledjene
periode
* @param period - input tipa unsigned long - Duzina periode
* @return Povratna vrednost je tipa unsigned long i predstavlja polovinu
periode
*/
calculateHalfPeriod(unsigned long period);
#endif /* TIMER0_H_ */
|
package helloworld
import (
"context"
"fmt"
GoText2Speech "github.com/FaaSTools/GoText2Speech/GoSpeech2Text"
"github.com/FaaSTools/GoText2Speech/GoSpeech2Text/providers"
"github.com/GoogleCloudPlatform/functions-framework-go/functions"
"golang.org/x/oauth2/google"
"io"
"net/http"
)
func execT2S(r *http.Request) error {
var MyEvent struct { // don't count this struct
Text string `json:"Text"`
VoiceId string `json:"VoiceId"`
TargetBucket string `json:"TargetBucket"`
TargetKey string `json:"TargetKey"`
}
MyEvent.TargetKey = "example01/example01-got2s.mp3"
MyEvent.TargetBucket = "test"
MyEvent.VoiceId = "en-US-News-N"
MyEvent.Text = "Hello World"
region := "us-east-1"
googleCredentials, err := google.CredentialsFromJSON(
context.Background(),
[]byte("CREDENTIALS_HERE"),
"https://www.googleapis.com/auth/devstorage.full_control",
"https://www.googleapis.com/auth/cloud-platform",
)
fmt.Println("err while reading credentials:", err)
cred := &goS2TShared.CredentialsHolder{
GoogleCredentials: googleCredentials,
}
s2tClient := GoText2Speech.CreateGoS2TClient(nil, "us-east-1")
options := GetDefaultSpeechToTextOptions()
options.LanguageConfig.LanguageCode = "en"
options.Provider = providers.ProviderGCP
var err2 error = nil
target := "https://" + bucket + ".s3.amazonaws.com/" + key
s2tClient, err2 = s2tClient.S2T("https://test.s3.amazonaws.com/testfile.mp3", target, *options)
if err2 != nil {
return err2
}
return nil
}
func init() {
// Register an HTTP function with the Functions Framework
functions.HTTP("MyHTTPFunction", MyHTTPFunction)
}
func main() {} // needs to be here, otherwise it can't be built
// MyHTTPFunction Function is an HTTP handler
func MyHTTPFunction(w http.ResponseWriter, r *http.Request) {
err := execT2S(r)
if err != nil {
fmt.Println("Error:", err.Error())
_, err1 := io.WriteString(w, "Error: "+err.Error())
if err1 != nil {
fmt.Println("Error while writing error to output: ", err1)
}
} else {
_, err1 := io.WriteString(w, "Done successfully!")
if err1 != nil {
fmt.Println("Error while writing success message to output: ", err1)
}
}
}
|
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
<style>
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
#calculator {
max-width: 300px;
margin: 0 auto;
padding: 20px;
background-color: #ffffff;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}
h1 {
text-align: center;
}
#result {
display: block;
width: 100%;
height: 40px;
font-size: 20px;
margin-bottom: 10px;
text-align: right;
padding: 5px;
}
button {
width: 50px;
height: 50px;
font-size: 24px;
margin: 5px;
border: none;
border-radius: 4px;
background-color: #f0f0f0;
cursor: pointer;
}
button:hover {
background-color: #e0e0e0;
}
</style>
</head>
<body>
<div id="calculator">
<h1>Simple Calculator</h1>
<input type="text" id="result" disabled>
<br>
<button onclick="appendNumber(1)">1</button>
<button onclick="appendNumber(2)">2</button>
<button onclick="appendNumber(3)">3</button>
<button onclick="appendOperator('+')">+</button>
<br>
<button onclick="appendNumber(4)">4</button>
<button onclick="appendNumber(5)">5</button>
<button onclick="appendNumber(6)">6</button>
<button onclick="appendOperator('-')">-</button>
<br>
<button onclick="appendNumber(7)">7</button>
<button onclick="appendNumber(8)">8</button>
<button onclick="appendNumber(9)">9</button>
<button onclick="appendOperator('*')">*</button>
<br>
<button onclick="appendNumber(0)">0</button>
<button onclick="calculate()">=</button>
<button onclick="appendOperator('/')">/</button>
<button onclick="clearResult()">C</button>
</div>
<script>
let currentResult = '';
let currentOperator = '';
function appendNumber(number) {
currentResult += number;
updateDisplay();
}
function appendOperator(operator) {
if (currentOperator !== '') {
calculate();
}
currentOperator = operator;
currentResult += operator;
updateDisplay();
}
function calculate() {
if (currentOperator !== '') {
const operands = currentResult.split(currentOperator);
if (operands.length === 2) {
const num1 = parseFloat(operands[0]);
const num2 = parseFloat(operands[1]);
switch (currentOperator) {
case '+':
currentResult = (num1 + num2).toString();
break;
case '-':
currentResult = (num1 - num2).toString();
break;
case '*':
currentResult = (num1 * num2).toString();
break;
case '/':
currentResult = (num1 / num2).toString();
break;
default:
currentResult = 'Error';
}
currentOperator = '';
updateDisplay();
}
}
}
function clearResult() {
currentResult = '';
currentOperator = '';
updateDisplay();
}
function updateDisplay() {
document.getElementById('result').value = currentResult;
}
</script>
</body>
</html>
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\MasterClass;
use DB;
use Session;
use App\SchoolType;
class ClassController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$classes =MasterClass::with('schoolType')->get();
return view('backEnd.classManage.all_class_info',compact('classes'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$school_types= self::getSchoolTypes();
return view('backEnd.classManage.create',compact('school_types'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'name'=>'required',
'school_type_id'=>'required'
]);
if ($this->createCheck($request->name)){
Session::flash('errmgs', 'শ্রেণীটি পূর্বেই যোগ করা হয়েছে !');
return redirect()->back();
}
$data['name']=$request->name;
$data['school_type_id']=$request->school_type_id;
MasterClass::insert($data);
Session::flash('sccmgs', 'শ্রেণী সফলভাবে যোগ করা হয়েছে !');
return redirect()->back();
}
public function createCheck($name){
$result=MasterClass::where(['name'=>$name])->first();
return $result;
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$class= MasterClass::where(['id'=>$id])->first();
$school_types= self::getSchoolTypes();
return view('backEnd.classManage.edit', compact('class','school_types'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$this->validate($request,[
'name'=>'required',
'school_type_id'=>'required'
]);
if ($this->createCheck($request->name)->count() > 0 && $this->createCheck($request->name)->id != $request->class_id){
Session::flash('errmgs', 'শ্রেণীটি পূর্বেই যোগ করা হয়েছে ! !');
return redirect()->back();
}
$data['name']=$request->name;
$data['school_type_id']=$request->school_type_id;
MasterClass::where(['id'=>$request->class_id])->update($data);
Session::flash('sccmgs', 'শ্রেণীটি সফলভাবে আপডেট করা হয়েছে ! !');
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
MasterClass::where(['id'=>$id])->delete();
Session::flash('sccmgs', 'শ্রেণীটি সফলভাবে মুছে ফেলা হয়েছে !');
return redirect()->back();
}
public static function getSchoolTypes()
{
$school_types=SchoolType::all();
return $school_types;
}
}
|
# CaptchaSolver
Model to solve six character captchas. The code available on this repository is based on the example presented [here](https://keras.io/examples/vision/captcha_ocr/), which solves captchas with five characters. Besides the size of the captchas, the main difference in the code available here is that it applies morphological filtering to reduce the noise on the captcha images.

## Dependencies
The dependencies for this repository are listed on the requirements file. To install them:
```
$ python -m pip install -r requirements.txt
```
## How to run
To run the API for the captcha solver model:
```
$ python api.py
```
It will start a server locally, using the port 5000. In order to test this server, just run the test script:
```
$ python test.py
```
This script will iterate through all images on data/captcha_dataset, making a request for the server using each one of them.
## Docker image
This repository also contains a docker image, which may facilitate the execution on a different environment. To build this image:
```
$ docker build -t captcha-api:latest -f Dockerfile .
```
After the image is built, you can start the server just running the image like this:
```
$ docker run -p 5000:5000 --name captcha-api captcha-api:latest
```
## Documentation
With the server running, the API documentation may be found on http://localhost:5000/docs (or any other base url where the server is running).
|
import 'package:flutter/material.dart';
import 'package:hi_clinic_app/common/constans/string.dart';
import 'package:hi_clinic_app/common/styles.dart';
import 'package:hi_clinic_app/tool/hex_color.dart';
import 'package:hi_clinic_app/tool/skeleton_animation.dart';
class CardShimmer extends StatelessWidget {
const CardShimmer({super.key});
@override
Widget build(BuildContext context) {
return ListView.separated(
padding: const EdgeInsets.symmetric(
horizontal: 18,
vertical: 20,
),
itemBuilder: (context, index) {
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 15,
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.all(Radius.circular(13)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 0,
blurRadius: 6,
offset: const Offset(
1,
2,
), // changes position of shadow
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SkeletonAnimation(
width: 68,
height: 15,
radius: 0,
),
const SizedBox(height: 2),
const SkeletonAnimation(
width: 110,
height: 27,
radius: 0,
),
const SizedBox(height: 5),
Text(
'Ringkasan',
style: AppTextStyle.bold(
fontSize: 12,
color: HexColor('495DE0'),
),
),
const SizedBox(height: 2),
const SkeletonAnimation(
width: 87,
height: 16,
radius: 0,
),
const SizedBox(height: 5),
Text(
'Dokter',
style: AppTextStyle.bold(
fontSize: 12,
color: HexColor('495DE0'),
),
),
const SizedBox(height: 5),
Row(
children: [
CircleAvatar(
radius: 20,
backgroundColor: Colors.grey.withOpacity(.15),
child: const CircleAvatar(
radius: 17,
backgroundColor: Colors.white,
child: CircleAvatar(
radius: 15,
backgroundImage: NetworkImage(
noImage,
),
backgroundColor: Colors.white,
),
),
),
const SizedBox(width: 4),
const SkeletonAnimation(
width: 104,
height: 16,
radius: 0,
),
],
),
const SizedBox(height: 5),
],
),
);
},
separatorBuilder: (_, i) => const SizedBox(height: 20),
itemCount: 5,
);
}
}
|
import React from 'react';
// import './movie.styles.css'
const Movie = ({result}) => {
// The image complete path
const IMG_PATH = 'https://image.tmdb.org/t/p/w1280';
// This function takes in the vote from the result props and checks what value the rating is
function getClassByRate(vote){
if (vote >= 8){
return 'green'
}
else if (vote >= 5 ){
return 'orange'
}
else{
return 'red'
}
}
return(
// The movie component that takes in the data from the result props
<div className="movie">
<img src={IMG_PATH + result.poster_path} alt={result.title} />
<div className="movie-info">
<h3>{result.title}</h3>
<span className={getClassByRate(result.vote_average)}>{result.vote_average}</span>
</div>
<div className="overview">
<h3>Overview</h3>
<p>{result.overview}</p>
</div>
</div>
)
}
export default Movie
|
package auth_test
import (
"context"
"github.com/IliyaYavorovPetrov/api-gateway/app/common/models"
"github.com/IliyaYavorovPetrov/api-gateway/app/server/auth"
"log"
"reflect"
"testing"
)
func setup(ctx context.Context) {
auth.Init(ctx)
err := auth.ClearSessionStore(ctx)
if err != nil {
log.Fatal("could not clear session store")
}
}
func TestAddAndGetFromSessionStore(t *testing.T) {
ctx := context.Background()
setup(ctx)
session1 := models.Session{
UserID: "id1",
Username: "ivan",
UserRole: "User",
IsBlacklisted: false,
}
sessionID, err := auth.AddToSessionStore(ctx, session1)
if err != nil {
t.Fatalf("AddToSessionStore failed: %v", err)
}
session2, err := auth.GetSessionFromSessionID(ctx, sessionID)
if err != nil {
t.Fatalf("GetSessionFromSessionID failed: %v", err)
}
if !reflect.DeepEqual(session1, session2) {
t.Errorf("sessions are different")
}
}
func TestRemovingSessionFromSessionStore(t *testing.T) {
ctx := context.Background()
setup(ctx)
s1 := models.Session{
UserID: "id1",
Username: "ivan",
UserRole: "User",
IsBlacklisted: false,
}
sessionID1, err := auth.AddToSessionStore(ctx, s1)
if err != nil {
t.Fatalf("AddToSessionStore failed: %v", err)
}
s2 := models.Session{
UserID: "id2",
Username: "gosho",
UserRole: "Admin",
IsBlacklisted: false,
}
sessionID2, err := auth.AddToSessionStore(ctx, s2)
if err != nil {
t.Fatalf("AddToSessionStore failed: %v", err)
}
valuesToCheck := make(map[string]struct{})
valuesToCheck[sessionID1] = struct{}{}
valuesToCheck[sessionID2] = struct{}{}
allSessionIDs, err := auth.GetAllSessionIDs(ctx)
if err != nil {
t.Fatalf("GetAllSessionIDs failed: %v", err)
}
if len(allSessionIDs) != len(valuesToCheck) {
t.Errorf("wrong number of session ids, %d expected, %d received", len(allSessionIDs), len(valuesToCheck))
}
for _, str := range allSessionIDs {
sID, err := auth.ExtractSessionIDFromSessionHashKey(str)
if err != nil {
t.Errorf("%v", err)
}
if _, found := valuesToCheck[sID]; !found {
t.Errorf("value %s not found in the list", str)
}
}
}
|
@orange
Feature: orange Login Test
@orangeunsuccessful @orangeLoginunsuccessful
Scenario: Unsuccessful login
Given the user visits Orange page
When the user clicks on the login button
Then an error message is displayed
@orangesuccessful @orangeLoginsuccessful
Scenario Outline: Successful login
Given the user visits Orange page
When user use credentials '<user>' and '<password>'
And the user clicks on the login button
Then login successful
Examples:
| user | password |
| Admin | admin123 |
@dashboard
Scenario Outline: Click element of dashboard
Given the user login with credentials '<user>' and '<password>'
When click element of dashboard
Then the element has been clicked
Examples:
| user | password |
| Admin | admin123 |
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package mozilla.components.support.locale
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancel
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.setMain
import mozilla.components.browser.state.action.LocaleAction
import mozilla.components.browser.state.state.BrowserState
import mozilla.components.browser.state.store.BrowserStore
import mozilla.components.support.test.ext.joinBlocking
import mozilla.components.support.test.libstate.ext.waitUntilIdle
import mozilla.components.support.test.robolectric.testContext
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.spy
import org.mockito.Mockito.verify
import org.robolectric.annotation.Config
@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
class LocaleMiddlewareTest {
private lateinit var dispatcher: TestCoroutineDispatcher
private lateinit var scope: CoroutineScope
@Before
fun setUp() {
dispatcher = TestCoroutineDispatcher()
scope = CoroutineScope(dispatcher)
Dispatchers.setMain(dispatcher)
LocaleManager.clear(testContext)
}
@After
fun tearDown() {
dispatcher.cleanupTestCoroutines()
scope.cancel()
Dispatchers.resetMain()
}
@Test
@Ignore("Failing intermittently. To be fixed for https://github.com/mozilla-mobile/android-components/issues/9954")
@Config(qualifiers = "en-rUS")
fun `GIVEN a locale has been chosen in the app WHEN we restore state THEN locale is retrieved from storage`() = runBlockingTest {
val localeManager = spy(LocaleManager)
val currentLocale = localeManager.getCurrentLocale(testContext)
assertNull(currentLocale)
val localeMiddleware = spy(
LocaleMiddleware(
testContext,
coroutineContext = dispatcher,
localeManager = localeManager
)
)
val store = BrowserStore(
initialState = BrowserState(),
middleware = listOf(localeMiddleware)
)
assertEquals(store.state.locale, null)
store.dispatch(LocaleAction.RestoreLocaleStateAction).joinBlocking()
store.waitUntilIdle()
dispatcher.advanceUntilIdle()
assertEquals(store.state.locale, currentLocale)
}
@Test
@Config(qualifiers = "en-rUS")
fun `WHEN we update the locale THEN the locale manager is updated`() = runBlockingTest {
val localeManager = spy(LocaleManager)
val currentLocale = localeManager.getCurrentLocale(testContext)
assertNull(currentLocale)
val localeMiddleware = spy(
LocaleMiddleware(
testContext,
coroutineContext = dispatcher,
localeManager = localeManager
)
)
val store = BrowserStore(
initialState = BrowserState(),
middleware = listOf(localeMiddleware)
)
assertEquals(store.state.locale, null)
val newLocale = "es".toLocale()
store.dispatch(LocaleAction.UpdateLocaleAction(newLocale)).joinBlocking()
dispatcher.advanceUntilIdle()
verify(localeManager).setNewLocale(testContext, locale = newLocale)
}
}
|
---
title: 单硬盘三系统安装记录
date: 2020-04-04 15:04:15
updated: 2020-05-25 10:24:00
categories:
- [工具, 软件配置]
- [操作系统, Linux]
- [操作系统, macOS]
- [操作系统, Windows]
- [启动, GRUB]
---
分享一下我在同一个SSD里同时安装Ubuntu, Windows, macOS三个系统并以GRUB作为开机引导的经验. 说实话过程并不复杂.
<!-- More -->
也不知道最近自己时间都浪费哪里去了😑 3月7号弄好的东西现在才得以闲下来记录一番. 先秀一张GRUB界面😏

## 动机
说说我的心路历程😏
直到上大学我都对电脑了解甚少, **只知道有Windows系统**, 并不知道还可以有其他系统, 更别说在这之上的骚操作了😂 上大学后**我逐渐熟悉了Windows系统**并且喜欢上了这个很有现代感的系统. 但随着我对编程的学习逐渐深入, 以及我为了尽早熟悉机器人相关知识而想要了解Linux系统, 在听人介绍后我费了些力气**在虚拟机里装上了Ubuntu16.04**, 不过那时候了解的还是太少, 只是跟着网上的教程将这个东西装好了, 没什么收获. 装好后因为那时也没什么夸张到要开虚拟机在Ubuntu里编程的项目, 所以就体验了几下就束之高阁了. 毕竟那时对于编程, 甚至查找资料的经验都太少了, 只看到一些令人头大的辣鸡资料, 因此并没能学到什么.
大一下的时候我选了一门叫智能嵌入式的课, 其中有个课题是要编写一个能手势识别的程序并移植到树莓派上. 因此我就买了一个树莓派3b+. 不过那时懵懂的我对于怎么给一个SD卡安装系统手足无措, 就在网上搜资料给树莓派依次装了Ubuntu Mate, ArchLinux, 最后才是Raspbian😂 (我记得Mate是因为我当时没有找到arm架构的国内源就抛弃了, 而ArchLinux我就根本没装上...) 费劲心力我最后总算是把那个课题做完了, 但一方面我写得很差, 再加上树莓派3b+对图像处理的性能很一般, 所以我的手势识别程序移植到树莓派后十分卡顿😅 那是我**第一次将程序移植到Linux平台, 也是第一次接触Linux嵌入式**
后来在一个实验室学习时接触到了ROS, 而那时Ubuntu18.04已经较为成熟了, 我就安装了个Ubuntu18.04的虚拟机在里面跟着刷了一遍ROS基础教程, 这回算是**对Ubuntu的基本使用比较了解了**. 不过那时其实并完全不了解ROS的最大作用是什么, 只是知道很牛逼, 跟着教程做了一遍, 没多久就忘了, 只是了解到有那么些概念😁 那时我以为Linux系统也就那样, 我在虚拟机体验到的就是它的全部了. 因此那时有同学和我讨论装Linux虚拟机好还是Windows, Linux双系统好时, 我的想法就是这系统又没那么便利, 误操作带来的危险性又那么大, 当然是装在虚拟机好.
而我装Windows, Ubuntu双系统的契机应该是[我电脑的机械硬盘开始老化](/zh-CN/2019/03/30/我打算换电脑了/), 速度变得极慢. 那应该是我大二下刚开学的时候, 我实在忍受不了在机械硬盘运行本身就很耗资源的Windows系统了, 而那时我的编程活动也开始多起来, 再加上我偶然得知Ubuntu能识别到已经存在的Windows系统并傻瓜式安装, 我就给自己**装了个Windows, Ubuntu双系统**. 不久后我的机械硬盘彻底不行了就买个一个1T的SSD. 不过换了硬盘后我也还是装的双系统, 因为我**逐渐尝到了Linux系统的甜头**.
> 我在[另一篇文章](https://leojhonsong.github.io/zh-CN/2019/05/17/%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E7%94%A8Linux%E8%80%8C%E4%B8%8D%E6%98%AFWindows/)写了自己对Linux和Windows的对比
而随着我逐渐熟悉Ubuntu, 我开始像大多数Linux用户那样折腾自己的配置, 美化环境😏 期间也尝试了挺多东西, 到现在也形成了自己的使用习惯. 不过很尴尬的是在美化方面, 我经常看到这个好康的在Linux没有但macOS有的字眼. 所以**我开始眼馋macOS**. 不过那时我也就是眼馋, 因为我对比了一番, 发现macOS从接口, 生态等角度都不太适合做嵌入式开发就没有想过安一个试试. (我也在VMware里折腾过macOS虚拟机, 但和Ubuntu虚拟机一样装了没多久就删了)
而直到最近, 我看到了很详细的黑苹果安装教程, 加上我一个同学根据那份教程成功安上了黑苹果, 我也蠢蠢欲动了. 毕竟疫情期间闲着也是闲着+都用双系统了再多一个也不多. 于是我折腾一番**给单硬盘安装了三个系统**😁
P.S. 第一次体验macOS的本土包一开始连怎么删除文件都没搞懂, 还是现查的😅 使用逻辑与Windows/Linux差得真的太多了! 甚至因为别扭一度弃用了几天. 不过光是macOS下终端的美观程度就把俺勾回来了🤤
之前也看到网上有人装三系统的文章, 但基本都用了些杂牌子工具一通瞎操作... 所以我分享一下自己较为**清爽**的安装方法.
❗️ 我的电脑是真的一点不矫情, 安装很顺利, 不保证你的电脑上同样的不会出幺蛾子.
## 关于镜像烧录
### 镜像烧录工具
镜像烧录工具是唯一需要的第三方工具了. 强烈推荐使用[Ventoy](https://www.ventoy.net/cn/doc_start.html)! 这个软件可以将你的U盘创建为一个启动盘, 之后只需要将各种系统镜像放进这个U盘, 到时候以这个U盘启动时会进入一个GRUB界面, 在这个页面再来选择到底进入哪个镜像 👍 有了Ventoy, 装三系统的操作简单了很多!
### 下载镜像
因此将U盘创建为启动盘后就把要用到的三个镜像都放进U盘的**Ventoy**这个分区就完事.
- MacOS镜像: [这个文章最后的百度云链接](https://blog.daliansky.net/macOS-Catalina-10.15.4-19E266-Release-version-with-Clover-5107-original-image-Double-EFI-Version-UEFI-and-MBR.html)
- Windows10镜像: 微软现在提供了[官方的镜像下载网站](https://www.microsoft.com/zh-cn/software-download/windows10ISO) 👍 当然要激活的话还是需要激活码的. 而激活码在淘宝就可以买到, 只是需要巧妙措辞 😏
- [Ubuntu镜像](https://cn.ubuntu.com/download)
安装每个系统平均下来十五分钟, 因此全过程**一个小时内**就能搞定.
## 系统安装
我安装系统的顺序是:
1. macOS10.15.4
2. Windows10
3. Ubuntu18.04
之所以是先安装macOS是因为看网上都说**macOS要求EFI分区不小于200MB**, 否则在安装时会提示无法安装. 然后我搜了搜EFI分区扩容, 似乎并没什么清爽的办法. 因此时刻准备着重装系统的我判定**还是直接格式化硬盘来得清爽**. 然后在安装的时候先安装macOS那它自己就会处理好这个事情, 不需要我担心😁
(不过我把三个系统都装完这个EFI分区也才用了120MB, 也不知道它要那么大干嘛)
而最后才安装Ubuntu是基于两方面考虑:
1. 如果先装Ubuntu就意味着得给Windows系统留下一定空间. 那么就需要在安装Ubuntu过程中"Installation Type"这一页选择`Something else`来**自己给Linux系统分区** (如果不选这种方式, 另外两种方式都会使用硬盘剩余的所有空间). 然而麻烦的是你不光需要给Ubuntu系统分一个主分区, 你还需要讲这个主分区分成几个逻辑分区, 而且每个逻辑分区的大小有一定的讲究. 我目前没有研究过这里的门道并且我对Ubuntu安装程序帮我规划的各个分区的大小没有不满. 因此我决定不去管这种事, **我选择最后来安装Ubuntu, 让安装程序用我给它剩下的空间自己看着办**😏
2. Ubuntu安装程序能识别电脑里已经安装的Windows系统 (识别不到我的黑苹果系统), 并**自动处理好与Windows系统共存的配置**, 将Windows添加到GRUB引导项中. 因为我的主力系统是Ubuntu而且我也很喜欢使用GRUB作为开机引导程序, 因此这帮我省了一些事.
### macOS安装
我使用的黑苹果镜像是[在这个文章最后的百度云链接](https://blog.daliansky.net/macOS-Catalina-10.15.4-19E266-Release-version-with-Clover-5107-original-image-Double-EFI-Version-UEFI-and-MBR.html)
❗️ 我安装完之后才从使用苹果系统的同学们那得知macOS10.15, 也就是Catalina目前bug还比较多, 外观上和10.14也没什么区别, 因此建议安装macOS**10.14**, 而不是10.15.
这个镜像很棒的一点是它不止包含一个macOS系统安装程序, **还有一个Windows PE**, 也就是一个可以从U盘启动的专门魔改过, 用于修复系统的Windows系统. 这个Windows PE中包含了大多数你在网上教你修复系统发中文教程中提到的各种看起来有点不靠谱的工具 😂
我安装macOS使用的是[这个教程](https://blog.daliansky.net/MacOS-installation-tutorial-XiaoMi-Pro-installation-process-records.html). 跟着一步步操作就可以了. 安装好后发现有驱动问题等先放着不管, 把三个系统都装好再来看上面那个镜像的链接里提供的问题解决方案好了, 不然容易心情变得焦躁的 🤗
#### 更改EFI分区文件
看到网上说装黑苹果最重要的就是要有对应自己电脑型号的EFI文件, 过了这一关就八九不离十了.
[这里](https://github.com/daliansky/Hackintosh#%E9%BB%91%E8%8B%B9%E6%9E%9C%E9%95%BF%E6%9C%9F%E7%BB%B4%E6%8A%A4%E6%9C%BA%E5%9E%8B%E6%95%B4%E7%90%86-by-%E6%88%91%E6%84%8F)是一份黑苹果爱好者们提供了EFI分区文件的笔记本和台式机的型号列表, 也有他们自己的安装过程分享. 我使用的是其中的[Dell Inspiron 3568](https://github.com/YGQ8988/dell-3568)
💡 在安装前我也曾担心后续两个系统的安装会不会破坏已经安装好的macOS的EFI文件, 实验表明他们是互不干扰的, 不会看对方不顺眼就删掉对方 😏
#### 网卡问题
这似乎是在实体机安装黑苹果一定会有的问题, 有人是直接买了一个苹果能识别的网卡换上, 而我懒一点, 我买了一个有macOS驱动的外置网卡, Comfast的**CF-811 AC**, 很小一个, 不贵, 速度也很不错. macOS在使用这个外置网卡时不会认为在使用WiFi, 而是认为是接入了一个以太网. 唯一缺点是我还没有搞清如何让使用这样外置网卡的macOS连接上星巴克WiFi这样需要等它弹出登录页面才能用的公共WiFi--并不会有什么页面弹出 😓
### Windows安装
在安装系统的第一步就会要你选择安装在哪里, 在此时创建一个想要的大小的分区选中就可以进行安装了. 因为我的硬盘是1TSSD, 所以我分了一个274G的分区给Windows, 绰绰有余. 如果我真用满了也意味着我该重装了.
#### System Reserved分区
当你安好Windows系统后会发现在给Windows划分的分区前后多了两个分区, 一个叫**System Reserved**, 一个叫**Microsoft Windows Recovery Environment**如果你断定自己不会用到安装在硬盘的Windows系统的恢复模式 (实际上Windows安装盘的恢复模式或者Windows PE盘可能会是你遇到麻烦时的更好选择), 那么**Microsoft Windows Recovery Environment**这个分区可以随便删. 而**System Reserved**这个分区**绝对不能随便删, 最好是别动**. 血泪教训啊! 一次我看这分区不爽一气之下删掉了, 然后就因为缺少文件而无法启动Windows了...
🔗 [Windows的System Reserved分区是什么以及能否删除](https://www.zhihu.com/question/60154583)
我找到了这个[Windows Boot Environment - Murali Ravirala (Microsoft)](http://www.uefi.org/sites/default/files/resources/UEFI-Plugfest-WindowsBootEnvironment.pdf), 里面讲述了Windows系统的启动过程, 提到了这个分区的作用.
总结下来意思就是**System Reserved**这个分区不能随便删, 要删还要不会出错操作很麻烦, 因此就别动它了 🤦♂
💡 值得一提的是Windows现在有了**开发人员模式**, 开启这个模式后在Windows开发的体验会好很多, 不会经常弄出些乱七八糟的错误.
### Ubuntu安装
Ubuntu系统的安装就跟着[官网安装教程](https://ubuntu.com/tutorials/tutorial-install-ubuntu-desktop#1-overview)来是最简洁正确的. 唯一需要注意的是在官网教程第六步时, 因为之前安装了Windows系统, Ubuntu安装程序会检测到已安装的Windows系统, 并给出一个**Install Ubuntu alongside Windows 10**的选项. 选择这个是这种情况下最简单的安装方式. 另外选择这个的话Ubuntu安装程序会自动把Windows系统加入到GRUB中, 属实舒服.
**系统安装就全部完成了!** 🎉
## GRUB配置及开机美化
然后是我在这次重装前一直不确定的事: 是否能把macOS引导项也加入GRUB? 经过我的尝试答案是可以!
在网上搜索后我知道了怎么样来配置GRUB的引导项, 其实真心不难.
### 引导项设置
第一步是进入`/etc/grub.d/`, 添加/编辑引导项. ❗️ 建议在先备份这个路径下的文件, 等确认改动成功了再删除备份也不迟.
在我的这个路径下有这样一些文件. 是的这里甚至有一个README 😂
```shell
00_header
05_debian_theme
10_linux
20_linux_xen
20_memtest86+
30_os-prober
30_uefi-firmware
40_custom
41_custom
README
```
这个README的内容是这样的:
> All executable files in this directory are processed in shell expansion order.
>
> 00_*: Reserved for 00_header.
> 10_*: Native boot entries.
> 20_*: Third party apps (e.g. memtest86+).
>
> The number namespace in-between is configurable by system installer and/or
> administrator. For example, you can add an entry to boot another OS as
> 01_otheros, 11_otheros, etc, depending on the position you want it to occupy in
> the menu; and then adjust the default setting via /etc/default/grub.
也就是说:
- **00_**开头的是为`00_header`这个文件保留的, **10_**开头的是系统自带的引导项, 这个稍后解释. **20_**开头的是一些第三方软件的东西, 比如`20_memtest86+`是一个叫memtest86+的内存测试软件 (虽然不知道是干啥的).
- 除了上面这三个前缀的文件名是可以自由改动的, 要把数字改成多少取决于你想让这个文件代表的引导项出现代GRUB引导菜单的第几个. (这个文件的顺序看起来就是最后生成出的`/boot/grub/grub.cfg`这个文件里引导项的顺序)
- 这些文件写好之后在`/etc/default/grub`这个文件可以调一调设置.
一个引导项文件的写法示例 (也就是我的macOS的引导项文件):
```
#!/bin/sh
exec tail -n +3 $0
# This file provides an easy way to add custom menu entries. Simply type the
# menu entries you want to add after this comment. Be careful not to change
# the 'exec tail' line above.
menuentry 'macOS Catalina 10.15.3' --class macosx {
insmod part_gpt
insmod fat
search --no-floppy --fs-uuid --set=root 67E3-17ED
chainloader /EFI/CLOVER/CLOVERX64.efi
}
```
其中前5行是`40_custom`中给出的注释, 我就抄过来了. 然后由`menuentry`起头声明一个引导项. 然后`--class`用来设置这个引导项的类型, 直观来说就是在GRUB界面里图标的名字. 此处的类型为**macosx**, 也就是说在我使用的GRUB主题的`icons`文件夹中有同名 (除了后缀名) 图标的话到时候这个引导项在GRUB界面里的文字前面的图标就是这个叫`macosx.png`的图标.
在这个引导项大括号里的内容是和在GRUB命令行进入一个系统需要输入的命令是一样的, 我感觉算是一种脚本? 我也不太懂, 只能说说大概理解:
- 第一行指定硬盘分区表的格式
- 第二行指定文件系统
- 第三行指定在uuid为**67E3-17ED**的分区搜索引导项的启动文件
- 第四行指定这个引导项使用的启动文件 (因为黑苹果实际是有Clover启动的, 因此macOS引导项的指定启动文件为Clover的启动文件)
💡 其中`insmod`是**ins**ert **mod**e的缩写.
### Grub tone
在`/etc/default/grub`这个文件里可以进行的设置有`GRUB_CMDLINE_LINUX_DEFAULT`, 这个在显卡不兼容时常用到的设置, 也有`GRUB_THEME`这个设置GRUB图形界面的主题的, 甚至可以通过`GRUB_INIT_TUNE`可以设置开机彩铃 😂
GRUB tone的值是什么意思以及可以看[GRUB_INIT_TUNE tester](https://breadmaker.github.io/grub-tune-tester/), 这里也提供了一些好听的铃声. 我用过这个超级马里奥音效:
```
GRUB_INIT_TUNE="1750 523 1 392 1 523 1 659 1 784 1 1047 1 784 1 415 1 523 1 622 1 831 1 622 1 831 1 1046 1 1244 1 1661 1 1244 1 466 1 587 1 698 1 932 1 1175 1 1397 1 1865 1 1397 1"
```
但是这个音效声音大小无法调节, 只能是最大声, 真的很大声那种😏 所以虽然很好玩, 我后来还是取消了这个设置.
### GRUB图形界面分辨率
如果你像我这样是4k屏幕, 那么当`/etc/default/grub`中分辨率参数为**GRUB_GFXMODE=auto**, 那么GRUB会是4k分辨率, 字会比较小, 然后画面刷新率很低, 导致有点卡, 于是我换成了`GRUB_GFXMODE=1920x1440x32` (32表示32位色深). 要注意这个分辨率必须是在GRUB图形化界面中按<kbd>c</kbd>进入命令行模式, 输入`videoinfo`后所列出的分辨率, 不然对分辨率的指定无效.
### 最后微调
调整完上面三个后运行`update-grub`来更新`/boot/grub/grub.cfg`. 最后可以到`/boot/grub/grub.cfg`进行最后微调 (如果需要的话).
### 开机美化
> 因为最开始写这篇文章时我还没体验过Manjaro, 因此这部分就保留好了, 但我要说Manjaro真的比Ubuntu容易个性化太多了!!! ([安利文](/zh-CN/2020/07/26/我从Ubuntu换到了Manjaro/))
Ubuntu开机过程中一共有三处可以美化:
- GRUB theme
- [Plymouth](https://wiki.archlinux.org/index.php/plymouth) theme
- [GDM](https://wiki.archlinux.org/index.php/GDM) theme
我的GRUB主题是[Aurora Penguinis GRUB2 Theme](https://www.gnome-look.org/p/1009533/), Plymouth主题是[Aurora Penguinis Plymouth 2 Theme](https://www.gnome-look.org/p/1009239/). 而Gnome能使用的GDM主题我没看到什么我中意的, 就自行改动了一下`/usr/share/gnome-shell/theme/ubuntu.css`里的样式, 给登录界面加了个背景图片.
```CSS
#lockDialogGroup {
background: #2c001e url(file:///home/leo/Pictures/login-screen/custom.jpg);
background-repeat: no-repeat;
background-size: cover;
background-position: center; }
```
## 关于启动
最后放上几个在搜索资料过程中看到的好资料:
- [Ubuntu系统安装教程考古](https://help.ubuntu.com/community/Installation?_ga=2.230386906.774703488.1586350910-773002345.1585209571) 在**Either Shrink the Windows C: Drive to Make Room for Linux OR Turn off Windows Updating**这部分可以找到有人遇到的Windows系统更新却破坏了Ubuntu系统是怎么回事. (也很明显我这不会出现这问题)
- [阮一峰-计算机是如何启动的?](http://www.ruanyifeng.com/blog/2013/02/booting.html) 在这里可以看到启动为什么叫**boot**, 也可以对启动过程中发生了什么有个大概了解.
|
export function sortByProductNameAZ(products: any) {
// Sử dụng thuật toán sắp xếp nhanh để sắp xếp mảng sản phẩm theo tên sản phẩm
const quickSort = (arr: any, left: number, right: number) => {
if (left < right) {
const pivotIndex = Math.floor((left + right) / 2);
const pivotValue = arr[pivotIndex].name;
let i = left;
let j = right;
while (i <= j) {
while (arr[i].name < pivotValue) {
i++;
}
while (arr[j].name > pivotValue) {
j--;
}
if (i <= j) {
[arr[i], arr[j]] = [arr[j], arr[i]];
i++;
j--;
}
}
quickSort(arr, left, j);
quickSort(arr, i, right);
}
return arr;
};
return quickSort([...products], 0, products.length - 1);
}
export function sortByProductNameZA(products: any) {
const quickSort = (arr: any, left: number, right: number) => {
if (left < right) {
const pivotIndex = Math.floor((left + right) / 2);
const pivotValue = arr[pivotIndex].name;
let i = left;
let j = right;
while (i <= j) {
while (arr[i].name > pivotValue) { // Đổi dấu lớn hơn thành dấu nhỏ hơn
i++;
}
while (arr[j].name < pivotValue) { // Đổi dấu nhỏ hơn thành dấu lớn hơn
j--;
}
if (i <= j) {
[arr[i], arr[j]] = [arr[j], arr[i]];
i++;
j--;
}
}
quickSort(arr, left, j);
quickSort(arr, i, right);
}
return arr;
};
return quickSort([...products], 0, products.length - 1);
}
export function sortByProductLowPrice(products: any) {
const quickSort = (arr: any, left: number, right: number) => {
if (left < right) {
const pivotIndex = Math.floor((left + right) / 2);
const pivotValue = arr[pivotIndex].price;
let i = left;
let j = right;
while (i <= j) {
while (arr[i].price < pivotValue) { // Sửa dấu so sánh ở đây
i++;
}
while (arr[j].price > pivotValue) { // Sửa dấu so sánh ở đây
j--;
}
if (i <= j) {
[arr[i], arr[j]] = [arr[j], arr[i]];
i++;
j--;
}
}
quickSort(arr, left, j);
quickSort(arr, i, right);
}
return arr;
};
return quickSort([...products], 0, products.length - 1);
}
export function sortByProductHightPrice(products: any) {
const quickSort = (arr: any, left: number, right: number) => {
if (left < right) {
const pivotIndex = Math.floor((left + right) / 2);
const pivotValue = arr[pivotIndex].price;
let i = left;
let j = right;
while (i <= j) {
while (arr[i].price > pivotValue) { // Sửa dấu so sánh ở đây
i++;
}
while (arr[j].price < pivotValue) { // Sửa dấu so sánh ở đây
j--;
}
if (i <= j) {
[arr[i], arr[j]] = [arr[j], arr[i]];
i++;
j--;
}
}
quickSort(arr, left, j);
quickSort(arr, i, right);
}
return arr;
};
return quickSort([...products], 0, products.length - 1);
}
export function sortByProductOutOfStock(products: any) {
return products.filter((item: any) => item.remaining == 0)
}
|
@inject ILocalStorageService LocalStorageService
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager NavigationManager
@inject ICartService CartService
<div class="dropdown">
<button @onclick="ToggleUserMenu"
@onfocusout="HideUserMenu"
class="btn btn-secondary dropdown-toggle user-button">
<i class="oi oi-person"></i>
</button>
<div class="dropdown-menu dropdown-menu-right @userMenuCssClass">
<AuthorizeView>
<Authorized>
<a href="profile" class="dropdown-item">Profile</a>
<button class="dropdown-item" @onclick="Logout">Logout</button>
</Authorized>
<NotAuthorized>
<a href="[email protected](NavigationManager.Uri)" class="dropdown-item">
Login
</a>
<a href="/register" class="dropdown-item">Register</a>
</NotAuthorized>
</AuthorizeView>
</div>
</div>
@code {
public bool showUserMenu = false;
public string userMenuCssClass => showUserMenu ? "show-menu" : null;
public void ToggleUserMenu()
{
showUserMenu = !showUserMenu;
}
public async Task HideUserMenu()
{
await Task.Delay(200);
showUserMenu = false;
}
private async Task Logout()
{
//ao remover o authToken, o metodo GetAuthenticationStateAsync nao vai mais gerar User c/ Identity ??
await LocalStorageService.RemoveItemAsync("authToken");
await CartService.GetCartItemsCount();
await AuthenticationStateProvider.GetAuthenticationStateAsync();
NavigationManager.NavigateTo("");
}
}
|
In part 10 you created an iterable shopping list, and we just learnt that an object created from an iterable class can be used with list comprehensions. The exercise template contains a stripped down version of the ShoppingList with just enough functionality to fulfil the requirements of this exercise.
Please write a function named products_in_shopping_list(shopping_list, amount: int) which takes a ShoppingList object and an integer value as its arguments. The function returns a list of product names. The list should include only the products with at least the number of items specified by the amount parameter.
The function should be implemented using list comprehensions. The maximum length of the function is two lines of code, including the header line beginning with the def keyword. The ShoppingList class definition should not be modified.
The function should work as follows:
my_list = ShoppingList()
my_list.add("bananas", 10)
my_list.add("apples", 5)
my_list.add("alcohol free beer", 24)
my_list.add("pineapple", 1)
print("the shopping list contains at least 8 of the following items:")
for product in products_in_shopping_list(my_list, 8):
print(product)
Sample output
the shopping list contains at least 8 of the following items:
bananas
alcohol free beer
|
# Parser
[](https://github.com/FollowTheProcess/parser)
[](https://pkg.go.dev/github.com/FollowTheProcess/parser)
[](https://goreportcard.com/report/github.com/FollowTheProcess/parser)
[](https://github.com/FollowTheProcess/parser)
[](https://github.com/FollowTheProcess/parser/actions?query=workflow%3ACI)
[](https://codecov.io/gh/FollowTheProcess/parser)
Simple, fast, zero-allocation [combinatorial parsing] with Go
## Project Description
`parser` is intended to be a simple, expressive and easy to use API for all your text parsing needs. It aims to be:
- **Fast:** Performant text parsing can be tricky, `parser` aims to be as fast as possible without compromising safety or error handling. Every parser function has a benchmark and has been written with performance in mind, almost none of them allocate on the heap ⚡️
- **Correct:** You get the correct behaviour at all times, on any valid UTF-8 text. Errors are well handled and reported for easy debugging. 100% test coverage and every base level parsing function is Fuzzed.
- **Intuitive:** Some parser combinator libraries are tricky to wrap your head around, I want `parser` to be super simple to use so that anyone can pick it up and be productive quickly
- **Well Documented:** Every combinator in `parser` has a comprehensive doc comment describing it's entire behaviour, as well as an executable example of its use
## Installation
```shell
go get github.com/FollowTheProcess/parser@latest
```
## Quickstart
Let's borrow the [nom] example and parse a hex colour!
```go
package main
import (
"fmt"
"log"
"strconv"
"github.com/FollowTheProcess/parser"
)
// RGB represents a colour.
type RGB struct {
Red int
Green int
Blue int
}
// fromHex parses a string into a hex digit.
func fromHex(s string) (int, error) {
hx, err := strconv.ParseUint(s, 16, 64)
return int(hx), err
}
// hexPair is a parser that converts a hex string into it's integer value.
func hexPair(colour string) (int, string, error) {
return parser.Map(
parser.Take(2),
fromHex,
)(colour)
}
func main() {
// Let's parse this into an RGB
colour := "#2F14DF"
// We don't actually care about the #
_, colour, err := parser.Char('#')(colour)
if err != nil {
log.Fatalln(err)
}
// We want 3 hex pairs
pairs, _, err := parser.Count(hexPair, 3)(colour)
if err != nil {
log.Fatalln(err)
}
if len(pairs) != 3 {
log.Fatalln("Not enough pairs")
}
rgb := RGB{
Red: pairs[0],
Green: pairs[1],
Blue: pairs[2],
}
fmt.Printf("%#v\n", rgb) // main.RGB{Red:47, Green:20, Blue:223}
}
```
### Credits
This package was created with [copier] and the [FollowTheProcess/go_copier] project template.
It is also heavily inspired by [nom], an excellent combinatorial parsing library written in [Rust].
[copier]: https://copier.readthedocs.io/en/stable/
[FollowTheProcess/go_copier]: https://github.com/FollowTheProcess/go_copier
[combinatorial parsing]: https://en.wikipedia.org/wiki/Parser_combinator
[nom]: https://github.com/rust-bakery/nom
[Rust]: https://www.rust-lang.org
|
import React, { useEffect, useState } from "react"
import styled from "styled-components";
import Layout from "../components/Layout";
import StarRating from "../components/StarRating";
import { BlackBg, FilterOption, RatingsFilterWrapper, Sidebar, SidebarSection, Wrapper } from "../components/Shared";
import { HeadFC, graphql } from "gatsby";
interface IReview {
dateCreated: string;
images: string;
place_id: string;
author: string;
reviewBody: string;
reviewRating: number;
}
const PracticePage = (props: any) => {
const { pageContext } = props;
console.log(props)
const queryResponse = props?.data?.allReviewsDataJson.edges;
const [ratingsFilter, setRatingsFilter] = useState([{
rating: "All",
selected: true
},
{
rating: "3.0",
selected: false
},
{
rating: "4.0",
selected: false
},
{
rating: "4.5",
selected: false
}])
const [sortOptions, setSortOptions] = useState([{
type: "newest",
selected: true
}, {
type: "oldest",
selected: false
}]);
const [treatmentFilter, setTreatmentFilter] = useState([{
treatment: "All",
selected: true
}]);
const [sidebarOpen, setSidebarOpen] = useState(false);
const [isMobile, setIsMobile] = useState(false);
const [reviews, SetReviews] = useState<IReview[]>(queryResponse.map(x => x.node));
useEffect(() => {
if (isMobile) {
document.getElementsByTagName("body")[0].classList.toggle("set-overflow");
}
}, [!sidebarOpen]);
useEffect(() => {
if (window.innerWidth < 760) {
setIsMobile(true);
}
}, []);
const activeFilters = () => {
const filter: any = {
...ratingsFilter.find(x => x.selected)
}
delete filter["selected"];
delete filter["id"];
if (filter["rating"] === "All") {
delete filter["rating"];
}
return filter;
}
const filterByRating = (rating: string) => {
setRatingsFilter(ratingsFilter.map(x => {
x.selected = x.rating === rating;
return x;
}))
}
const sortByDate = (type: string) => {
setSortOptions(sortOptions.map(x => {
x.selected = x.type === type;
return x;
}))
}
const filterByTreatment = (event: any) => {
const treatment = event.target.value;
setTreatmentFilter(treatmentFilter.map(x => {
x.selected = x.treatment === treatment;
return x;
}))
}
const handleFilterClick = () => {
let copy = !sidebarOpen;
setSidebarOpen(copy)
}
const filterReviewsList = () => {
return reviews
.filter((item: IReview) => {
return Object.entries(activeFilters()).every(([k, v]) => {
return +item.reviewRating > Number(v)
})
})
}
return (
<Layout>
{sidebarOpen && <BlackBg onClick={handleFilterClick} />}
<StyledHeading>{pageContext.name}</StyledHeading>
<Wrapper>
<Reviews>
{
filterReviewsList().map(review => (
<Review>
<ReviewHeader>
<LeftSection>
<ReviewRatingWrapper>
<StarRating rating={`${review.reviewRating}`}/>
</ReviewRatingWrapper>
<Author>- {review.author}</Author>
</LeftSection>
</ReviewHeader>
<ReviewMain>
{review.reviewBody}
</ReviewMain>
<ReviewFooter>
<Treatment></Treatment>
</ReviewFooter>
</Review>
))
}
</Reviews>
<Sidebar className={sidebarOpen ? "open" : ""}>
{/* <SidebarSection>
<h3>Sort by Date</h3>
<SortOptionsWrapper>
{sortOptions.map((x) => (
<FilterOption
key={x.type}
className={x.selected ? "active" : ""}
onClick={() => sortByDate(x.type)}
>
{x.type}
</FilterOption>
))}
</SortOptionsWrapper>
</SidebarSection> */}
<SidebarSection>
<h3>Filter by Rating</h3>
<RatingsFilterWrapper>
{ratingsFilter.map((x) => (
<FilterOption
key={x.rating}
className={x.selected ? "active" : ""}
onClick={() => filterByRating(x.rating)}
>
{x.rating}
</FilterOption>
))}
</RatingsFilterWrapper>
</SidebarSection>
{/* <SidebarSection>
<h3>Filter by Treatment</h3>
<Dropdown name="treatment" id="treatment" onChange={filterByTreatment}>
{treatmentFilter.map((x, i) => (
<option key={i}>{x.treatment}</option>
))}
</Dropdown>
</SidebarSection> */}
</Sidebar>
</Wrapper>
</Layout>
)
}
export const query = graphql`
query GetPracticeById($id: String!) {
allReviewsDataJson(filter: {place_id: {eq: $id}}) {
edges {
node {
reviewBody
author
reviewRating
images
dateCreated
place_id
}
}
}
}
`
const ReviewFooter = styled.footer`
display: none;
`
const LeftSection = styled.div`
display: flex;
gap: 4px;
`
const Treatment = styled.p`
font-size: 14px;
`
const Author = styled.p`
font-size: 18px;
font-weight: bold;
`
const ReviewMain = styled.p`
margin-top: 10px;
line-height: 1.6em;
`
const ReviewRatingWrapper = styled.div`
display: flex;
gap: 10px;
align-items: center;
`
const Reviews = styled.ul`
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
flex-wrap: wrap;
gap: 20px;
`
const Review = styled.li`
padding: 0;
margin: 0;
list-style: none;
padding: 20px;
background-color: #fff;
border-radius: 3px;
box-shadow: 0px 6px 10px rgba(0, 0, 0, 0.1);
span {
min-height: 42px;
display: block;
}
`
const ReviewHeader = styled.div`
display: flex;
justify-content: space-between;
`
const StyledHeading = styled.h1`
flex: 100%;
text-align: center;
font-size: 55px;
grid-column: 1 / 3;
margin: 40px 0;
font-weight: 700;
word-wrap: break-word;
@media only screen and (min-width: 760px) {
margin: 90px 0;
}
`
export default PracticePage
export const Head: HeadFC = (props) => {
return <title>RatedSmile - {(props.pageContext as any).name}</title>;
}
|
// Copyright and related rights are licensed under the Solderpad Hardware
// License, Version 0.51 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://solderpad.org/licenses/SHL-0.51. Unless required by applicable law
// or agreed to in writing, software, hardware and materials distributed under
// this License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
// Language: SystemVerilog
// Design unit: Posit Division Arithmetic
// :
// File name : DIV_Arithmetic.sv
// :
// Description:
// :
// Limitations:
// :
// System : SystemVerilog IEEE 1800-2005
// :
// Author : Xiaoan(Jasper) He Letian(Brian) Chen
// : [email protected] [email protected]
//
// Revision : Version 1.0 25/10/2023
module posit_div #(
parameter posit_pkg::posit_format_e pFormat = posit_pkg::posit_format_e'(0),
localparam int unsigned N = posit_pkg::posit_width(pFormat),
localparam int unsigned ES = posit_pkg::exp_bits(pFormat),
localparam int unsigned RS = $clog2(N)
) (
input logic Enable,
input logic signed Sign1, Sign2,
input logic signed [N-2:0] InRemain1, InRemain2,
input logic signed [RS:0] k1,k2,
input logic [ES-1:0] Exponent1, Exponent2,
input logic [N-1:0] Mantissa1, Mantissa2,
input logic NaR1, NaR2,
input logic zero1, zero2,
output logic [2*N-1:0] Div_Mant_N,
output logic [ES-1:0] E_O,
output logic signed [RS+4:0] R_O,
output logic NaR, zero, Sign,
output logic sign_Exponent_O
);
int i;
logic [3*N-1:0] Div_Mant, Div_Mant_temp_large;
logic [2*N-1:0] Div_Mant_temp;
logic [3*N-1:0] dividend, divisor;
logic signed [1:0] sumE_Ovf;
logic signed[ES+2:0] sumE; // 2 more bit: ES+1 for sign, ES for overflow
logic [RS+ES+4:0] Total_EON, Total_EO;
logic signed [RS+4:0] sumR;
logic signed [ES+1:0]signed_E1, signed_E2;
logic signed [1:0]Div_Mant_underflow;
logic sign_Exponent_o;
always_comb begin
if (Enable) begin
// check NaR and zero
NaR = NaR1 | NaR2;
zero = zero1 | zero2;
// division arithmetic
Sign = Sign1 ^ Sign2;
// dividend = {Mantissa1, {N-1{0}}};
dividend = Mantissa1 << 2*N;
divisor = Mantissa2;
signed_E1 = {2'b00, Exponent1};
signed_E2 = {2'b00, Exponent2};
// Mantissa Division Handling
Div_Mant = dividend / divisor;
Div_Mant_temp_large = Div_Mant << N-3;
Div_Mant_temp = {Div_Mant_temp_large[3*N-1:N-1], |Div_Mant_temp_large[N:0]};
if(Div_Mant_temp[2*N-1]) begin // DMT's MSB is 1 => divisor's fraction < dividend's
Div_Mant_N = Div_Mant_temp;
Div_Mant_underflow = '0;
end else begin // divisor's fraction > dividend's
Div_Mant_N = Div_Mant_temp << 1; // normalise it
Div_Mant_underflow = 2'b11; // will be taking 1 away from exponent
end
sumE = signed_E1 - signed_E2 + Div_Mant_underflow; // signed 2'b11 is -1
sumE_Ovf = {1'b0, sumE[ES]};
sumR = k1-k2;
Total_EO = (sumR<<ES)+ sumE;
E_O = sumE[ES-1:0];
// adjust for rounding
sign_Exponent_O = Total_EO[RS+ES+4];
Total_EON = sign_Exponent_O ? -Total_EO : Total_EO;
R_O = (~sign_Exponent_O || (sign_Exponent_O && |(Total_EON[ES-1:0])))
? Total_EON[ES+RS+3:ES] + 1 : Total_EON[RS+ES+3:ES];
end
end
endmodule
|
import { useEffect, useState } from "react";
import { alchemySDK } from "../utils/alchemy-settings";
import emptyLogo from "../assets/empty-token.webp";
export default function TokenDetails({ token }) {
const [metadata, setMetadata] = useState(null);
useEffect(() => {
async function getMetadata() {
const data = await alchemySDK.core.getTokenMetadata(
token.contractAddress
);
setMetadata(data);
}
getMetadata();
}, [token]);
if (!metadata) {
return <div>Loading...</div>;
}
if (metadata) {
return (
<tr className="text-sm mt-5">
<td className="flex items-center gap-2 py-2">
<img
src={metadata.logo ?? emptyLogo}
alt={`${metadata.name} logo`}
className="rounded-full border w-7"
/>
<p className="text-sm">{metadata.name}</p>
</td>
<td>{metadata.symbol}</td>
<td>{token.contractAddress}</td>
<td>
{parseInt(token.tokenBalance, 16) / Math.pow(10, metadata.decimals)}
</td>
</tr>
);
}
}
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'fileOfData.dart';
class RolesRout extends StatefulWidget {
const RolesRout({super.key});
@override
State<RolesRout> createState() => _RolesRoutState();
}
class _RolesRoutState extends State<RolesRout> {
int index = 0;
String selectedLocation = selectLocation(selectedTheme);
List<String> listOfPlayers = selectSpys();
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: const Color.fromRGBO(35, 35, 45, 1),
appBar: AppBar(
backgroundColor: const Color.fromRGBO(35, 35, 45, 1),
automaticallyImplyLeading: true,
centerTitle: true,
leading: IconButton(
onPressed: (){Navigator.of(context).pop();},
icon: const Icon(
Icons.arrow_back,
color: Color.fromRGBO(121, 104, 216, 1)
),
),
title: const Text(
"Выдаем роли",
style: TextStyle(
color: Color.fromRGBO(121, 104, 216, 1),
fontWeight: FontWeight.w600
)
),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children:[
Center(
child: MaterialButton(
color: const Color.fromRGBO(121, 104, 216, 1),
height: 80,
minWidth: 250,
disabledColor: Colors.white24,
onPressed: (index < countOfPlayers) ? (){
showDialog(context: context, builder: (BuildContext context) {
if (listOfPlayers[index] != "Шпион") {
return AlertDialog(
backgroundColor: const Color.fromRGBO(35, 35, 45, 1),
title: Text(
listOfPlayers[index],
textAlign: TextAlign.center,
style: const TextStyle(
color: Color.fromRGBO(138, 193, 135, 1),
),
),
content: Text(
selectedLocation,
textAlign: TextAlign.center,
style: const TextStyle(
color: Color.fromRGBO(138, 193, 135, 1),
),
),
actionsAlignment: MainAxisAlignment.center,
actions: [
ElevatedButton(
style: const ButtonStyle(
backgroundColor: MaterialStatePropertyAll(Color.fromRGBO(138, 193, 135, 1)),
minimumSize: MaterialStatePropertyAll(Size(150, 50)),
),
onPressed: (){
Navigator.of(context).pop();
setState(() {
index++;
});
},
child: const Text(
"Закрыть",
style: TextStyle(
fontSize: 24,
color: Color.fromRGBO(30, 31, 36, 1)
),
),
),
],
);
} else {
return AlertDialog(
backgroundColor: const Color.fromRGBO(35, 35, 45, 1),
title: Text(
listOfPlayers[index],
textAlign: TextAlign.center,
style: const TextStyle(
color: Color.fromRGBO(255, 170, 199, 1),
),
),
content: const Text(
"Угадай локацию",
textAlign: TextAlign.center,
style: TextStyle(
color: Color.fromRGBO(255, 170, 199, 1),
),
),
actionsAlignment: MainAxisAlignment.center,
actions: [
ElevatedButton(
style: const ButtonStyle(
backgroundColor: MaterialStatePropertyAll(Color.fromRGBO(255, 170, 199, 1)),
minimumSize: MaterialStatePropertyAll(Size(150, 50)),
),
onPressed: (){
Navigator.of(context).pop();
setState(() {
index++;
});
},
child: const Text(
"Закрыть",
style: TextStyle(
fontSize: 24,
color: Color.fromRGBO(30, 31, 36, 1)
),
),
),
],
);
}
});
} : null,
child: const Text(
"Получить роль",
style: TextStyle(
fontSize: 24,
color: Color.fromRGBO(30, 31, 36, 1),
),
),
),
),
Center(
child: MaterialButton(
color: const Color.fromRGBO(121, 104, 216, 1),
height: 80,
minWidth: 250,
disabledColor: Colors.white24,
onPressed: (index == countOfPlayers) ? () {
Navigator.of(context).pushNamed('/TimerPage');
} : null,
child: const Text(
"Продолжить",
style: TextStyle(
fontSize: 24,
color: Color.fromRGBO(30, 31, 36, 1)
),
),
),
),
],
),
),
);
}
}
//Создаем рандомное число из длины массива соответствий тем и выбираем тему из списка
String selectLocation(String selectedTheme) {
int len = themes[selectedTheme].length;
int rand = Random().nextInt(len);
List<String> theme = themes[selectedTheme];
String endingTheme = theme[rand];
return endingTheme;
}
//Создаем список и заполняем его значением. Для кол-ва шпионов проходимся по списку игроков и находим места с нужными индексом. Если уже Шпион, то переизбираем индекс.
List<String> selectSpys() {
List<String> listOfPlayers = List<String>.filled(countOfPlayers, "Гражданин");
int indexRole = 0;
for(int i = 0; i < countOfSpy; i++) {
indexRole = Random().nextInt(countOfPlayers);
while (listOfPlayers[indexRole] == "Шпион") {
indexRole = Random().nextInt(countOfPlayers);
}
listOfPlayers[indexRole] = "Шпион";
}
return listOfPlayers;
}
|
/**
* v0 by Vercel.
* @see https://v0.dev/t/jxWLyLdy7P6
* Documentation: https://v0.dev/docs#integrating-generated-code-into-your-nextjs-app
*/
import { Link } from "react-router-dom";
import { Avatar } from "@/components/ui/avatar";
import { Book, UserCircleIcon } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { MenuIcon, XIcon } from "lucide-react";
import Logout from "./auth/Logout";
import useAuthStore from "../zustand/authStore";
import {
DropdownMenuTrigger,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuContent,
DropdownMenu,
} from "@/components/ui/dropdown-menu";
export default function Component() {
const isAuth = useAuthStore((state) => state.isAuth);
const [menuOpen, setMenuOpen] = useState(false);
return (
<nav className="flex items-center gap-4 text-sm font-medium py-3 px-2">
<div className="flex items-center gap-2">
<Link className="flex items-center gap-2 font-bold" to="/">
<Book className="h-8 w-8" />
<span className="text-xl">OpenBlogs</span>
</Link>
</div>
<div className="ml-auto flex items-center gap-8 font-bold relative">
<button className="sm:hidden" onClick={() => setMenuOpen(!menuOpen)}>
{menuOpen ? (
<XIcon className="h-6 w-6" />
) : (
<MenuIcon className="h-6 w-6" />
)}
</button>
<div
className={`sm:flex ${
menuOpen
? "flex flex-col gap-4 absolute top-full right-0 bg-white p-4 rounded-lg shadow-md"
: "hidden"
}`}
>
<div className="flex gap-4 flex-wrap">
<Link to="/blogs" className="hover:text-blue-500 duration-150">
Blogs
</Link>
<Link to="/dashboard" className="hover:text-blue-500 duration-150">
Dashboard
</Link>
<Link to="/newblog" className="hover:text-blue-500 duration-150">
New Blog
</Link>
</div>
</div>
{isAuth ? (
<PopoverComponent />
) : (
<Link to="/login">
<Button>Login</Button>
</Link>
)}
</div>
</nav>
);
}
function PopoverComponent() {
const auth = useAuthStore((state) => state.authdata);
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
className="rounded-full border-gray-900 w-10 h-10"
variant="ghost"
>
<Avatar className="w-8 h-8">
<UserCircleIcon className="mx-auto my-auto" />
</Avatar>
<span className="sr-only">Toggle user menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem className="">
<strong>{auth?.username}</strong>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem>
{" "}
<Logout />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
|
import 'package:flutter/material.dart';
class ChartBar extends StatelessWidget {
const ChartBar({
Key? key,
required this.label,
required this.spendingAmount,
required this.spendingPctOfTotal,
}) : super(key: key);
final String label;
final double spendingAmount;
final double spendingPctOfTotal;
@override
Widget build(BuildContext context) {
return Column(
children: [
SizedBox(
height: 10,
child: FittedBox(
child: Text("${spendingAmount.toStringAsFixed(0)} €"),
),
),
const SizedBox(
height: 4,
),
SizedBox(
height: 60,
width: 10,
child: Stack(
children: [
Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey,
width: 1.0,
),
color: const Color.fromRGBO(220, 220, 220, 1),
borderRadius: BorderRadius.circular(10),
),
),
FractionallySizedBox(
heightFactor: spendingPctOfTotal,
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10),
),
),
)
],
),
),
const SizedBox(
height: 4,
),
Text(label),
],
);
}
}
|
import cv2
import numpy as np
import dlib
from imutils import face_utils
import pygame
import os
import pywhatkit as kitkat
from datetime import date
from datetime import datetime
import smtplib
time = datetime.now()
date = date.today()
pygame.mixer.init()
cap = cv2.VideoCapture(0)
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
sleep = 0
drowsy = 0
active = 0
status=""
color=(0,0,0)
def compute(ptA,ptB):
dist = np.linalg.norm(ptA - ptB)
return dist
def blinked(a,b,c,d,e,f):
up = compute(b,d) + compute(c,e)
down = compute(a,f)
ratio = up/(2.0*down)
#Checking if it is blinked
if(ratio>0.25):
return 2
elif(ratio>0.21 and ratio<=0.25):
return 1
else:
return 0
while True:
_, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = detector(gray)
face_frame = frame.copy()
#detected face in faces array
for face in faces:
x1 = face.left()
y1 = face.top()
x2 = face.right()
y2 = face.bottom()
cv2.rectangle(face_frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
landmarks = predictor(gray, face)
landmarks = face_utils.shape_to_np(landmarks)
left_blink = blinked(landmarks[36],landmarks[37],
landmarks[38], landmarks[41], landmarks[40], landmarks[39])
right_blink = blinked(landmarks[42],landmarks[43],
landmarks[44], landmarks[47], landmarks[46], landmarks[45])
#Now judge what to do for the eye blinks
if(left_blink==0 or right_blink==0):
sleep+=1
drowsy=0
active=0
if(sleep>6):
pygame.mixer.music.load('alarm.wav')
pygame.mixer.music.play(1)
status="Sleeping !!! zzZZZ"
color=(255,0,0)
kitkat.sendwhatmsg_instantly('#Your mobile number','🚨 SLEEPING 🚨, this message is computer generated !!!\n(-_-) zzzzzzZZZZZZZZZ\n(-_-) zzzzzzZZZZZZZZZZZZ\n(-_-) zzzzzzZZZZZZZZZZZZZZ\n(-_-) zzzzzzZZZZZZZZZZZZZZZZZZZ\n(-_-) zzzzzzZZZZZZZZZZZZZZZZZZZZZZ\n(-_-) zzzzzzZZZZZZZZZZZZZZZZZZZZZZZZZZ')
print("WHATSAPP MESSAGE SENT!!!")
sender_email = "#entersendergmailid1"
rec_email = "#enterrecievergmailid2"
password = "#enter the app specific password(2step verification)"
message = "SLEEPING , this message is computer generated !!!"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, password)
print("Login success")
server.sendmail(sender_email, rec_email, message)
print("Email has been sent to ", rec_email)
elif(left_blink==1 or right_blink==1):
sleep=0
active=0
drowsy+=1
if(drowsy>6):
pygame.mixer.music.load('car.wav')
pygame.mixer.music.play(1)
status="Drowsy !"
color=(0,0,255)
#two.play(1)
#status="Drowsy !"
#color = (0,0,255)
else:
drowsy=0
sleep=0
active+=1
if(active>6):
status="Active :)"
color = (0,255,0)
cv2.putText(frame, status, (100,100), cv2.FONT_HERSHEY_SIMPLEX, 1.2, color,3)
for n in range(0, 68):
(x,y) = landmarks[n]
cv2.circle(face_frame, (x, y), 1, (255,255,255), -1)
cv2.imshow("Frame", frame)
cv2.imshow("Result of detector", face_frame)
key = cv2.waitKey(1)
if key == 27:
break
|
using System.Collections.Generic;
using System.Linq;
using EnumsNET;
using MBW.BlueRiiot2MQTT.Features.Enums;
using MBW.BlueRiiot2MQTT.Features.Pool.Bases;
using MBW.BlueRiiot2MQTT.HASS;
using MBW.BlueRiiot2MQTT.Helpers;
using MBW.Client.BlueRiiotApi.Objects;
using MBW.Client.BlueRiiotApi.RequestsResponses;
using MBW.HassMQTT;
using MBW.HassMQTT.CommonServices.AliveAndWill;
using MBW.HassMQTT.DiscoveryModels.Enum;
using MBW.HassMQTT.DiscoveryModels.Models;
using MBW.HassMQTT.Extensions;
using MBW.HassMQTT.Interfaces;
namespace MBW.BlueRiiot2MQTT.Features.Pool
{
internal abstract class PoolMeasurementFeature : LastMeasurementsFeatureBase
{
private readonly string _displayName;
private readonly string _measurement;
private readonly string _unit;
public PoolMeasurementFeature(HassMqttManager hassMqttManager, string displayName, string measurement, string unit) : base(hassMqttManager)
{
_displayName = displayName;
_measurement = measurement;
_unit = unit;
}
private bool TryGetMeasurement(List<SwpLastMeasurements> measurements, out SwpLastMeasurements measurement)
{
measurement = measurements.FirstOrDefault(s => !s.Expired && s.Name == _measurement);
return measurement != null;
}
protected override bool AppliesTo(SwimmingPool pool, List<SwimmingPoolLastMeasurementsGetResponse> measurements, SwimmingPoolLastMeasurementsGetResponse latest)
{
return latest != null && TryGetMeasurement(latest.Data, out _);
}
protected override void CreateSensor(SwimmingPool pool, List<SwimmingPoolLastMeasurementsGetResponse> measurements, SwimmingPoolLastMeasurementsGetResponse latest)
{
HassMqttManager.ConfigureSensor<MqttSensor>(HassUniqueIdBuilder.GetPoolDeviceId(pool), _measurement)
.ConfigureTopics(HassTopicKind.State, HassTopicKind.JsonAttributes)
.SetHassPoolProperties(pool)
.ConfigureDiscovery(discovery =>
{
discovery.Name = _displayName;
discovery.UnitOfMeasurement = _unit;
discovery.StateClass = HassStateClass.Measurement;
})
.ConfigureAliveService();
}
protected override void UpdateInternal(SwimmingPool pool, List<SwimmingPoolLastMeasurementsGetResponse> measurements, SwimmingPoolLastMeasurementsGetResponse latest)
{
if (!TryGetMeasurement(latest.Data, out SwpLastMeasurements measurement))
return;
ISensorContainer sensor = HassMqttManager
.GetSensor(HassUniqueIdBuilder.GetPoolDeviceId(pool), _measurement)
.SetPoolAttributes(pool);
MqttAttributesTopic attributesSender = sensor.GetAttributesSender();
MeasurementUtility.AddAttributes(attributesSender, measurement);
MeasurementStatus status = MeasurementUtility.GetStatus(measurement);
attributesSender.SetAttribute("status", status.AsString(EnumFormat.EnumMemberValue));
sensor.SetValue(HassTopicKind.State, measurement.Value);
}
internal class PoolTaFeature : PoolMeasurementFeature
{
public PoolTaFeature(HassMqttManager hassMqttManager) : base(hassMqttManager, "Total Alkalinity", "ta", "mg/L")
{
}
}
internal class PoolPhFeature : PoolMeasurementFeature
{
public PoolPhFeature(HassMqttManager hassMqttManager) : base(hassMqttManager, "pH", "ph", "pH")
{
}
}
internal class PoolCyaFeature : PoolMeasurementFeature
{
public PoolCyaFeature(HassMqttManager hassMqttManager) : base(hassMqttManager, "Cyuranic Acid", "cya", "mg/L")
{
}
}
internal class PoolTemperatureFeature : PoolMeasurementFeature
{
public PoolTemperatureFeature(HassMqttManager hassMqttManager) : base(hassMqttManager, "Temperature", "temperature", "°C")
{
}
}
internal class PoolConductivityFeature : PoolMeasurementFeature
{
public PoolConductivityFeature(HassMqttManager hassMqttManager) : base(hassMqttManager, "Conductivity", "conductivity", "µS")
{
}
}
internal class PoolOrpFeature : PoolMeasurementFeature
{
public PoolOrpFeature(HassMqttManager hassMqttManager) : base(hassMqttManager, "ORP", "orp", "mV")
{
}
}
internal class PoolSalinityFeature : PoolMeasurementFeature
{
public PoolSalinityFeature(HassMqttManager hassMqttManager) : base(hassMqttManager, "Salinity", "salinity", "g/L")
{
}
}
internal class PoolFreeChlorineFeature : PoolMeasurementFeature
{
public PoolFreeChlorineFeature(HassMqttManager hassMqttManager) : base(hassMqttManager, "Free Chlorine", "fcl", "ppm")
{
}
}
internal class PoolFreeBromineFeature : PoolMeasurementFeature
{
public PoolFreeBromineFeature(HassMqttManager hassMqttManager) : base(hassMqttManager, "Free Bromine", "fbr", "ppm")
{
}
}
}
}
|
# taxi-management-api
An api for taxi management.
Doc is hosted here: https://github.com/DBMS-CE/taxi-management-api/blob/master/taximanagement.docx
## Description
This is a project based on taxi management. It consists of seven tables named “Consumer”, “Driver”, “Expense”, “Order”, “Owner”, “Taxi” and “Transaction”. Each table consists of attributes that describe it. The main aim of Taxi Management project is to rent taxi and get payments from respective clients. We aim to demonstrate the use of create, read, update and delete MySQL operations through this project. The project starts by adding a taxi and by adding details of driver using the taxi added. The owner provides taxi to the drivers and ads their expenses on daily basis. Booking scene is where a customer can book a taxi to get of the desired location.
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.
Cloning a repository using the command line
On GitHub, navigate to the main page of the repository.
Note: If the repository is empty, you can manually copy the repository page's URL from your browser and skip to step four.
Under the repository name, click Clone or download.
Clone or download button
To clone the repository using HTTPS, under "Clone with HTTPS", click
. To clone the repository using an SSH key, including a certificate issued by your organization's SSH certificate authority, click Use SSH, then click
.
Clone URL button
Open Terminal.
Change the current working directory to the location where you want the cloned directory to be made.
Type git clone, and then paste the URL you copied in Step 2.
$ git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
Press Enter. Your local clone will be created.
$ git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
> Cloning into `Spoon-Knife`...
> remote: Counting objects: 10, done.
> remote: Compressing objects: 100% (8/8), done.
> remove: Total 10 (delta 1), reused 10 (delta 1)
> Unpacking objects: 100% (10/10), done.
Cloning a repository to GitHub Desktop
On GitHub, navigate to the main page of the repository.
Under your repository name, click
to clone your repository in Desktop. Follow the prompts in GitHub Desktop to complete the clone. For more information, see "Cloning a repository from GitHub to GitHub Desktop."
### Prerequisites
As long as you have a pc, with node, npm running and mySql you are good to go!
### Installing
A step by step series of examples that tell you how to get a development env running
```
npm install
```
add your own credentials to existing config.env file,
return to main directory, run
```
npm start
```
In broswer open http://localhost:3000/graphql url for testing.
## Built With
* [mysql](https://dev.mysql.com/doc/) - Database
* [Node.js](https://nodejs.org/en/docs/) - Backend used
* [graphQL](https://graphql.org/learn/) - query language for API
* [Express](https://expressjs.com/en/4x/api.html) - Web application framework used
* [git](https://guides.github.com/) - Used for managing workflow
* [npm](https://docs.npmjs.com/) - Package manager
## Acknowledgments
* Hat tip to all who has contributed here
* And inspired
|
const express = require('express');
// import ApolloServer
const { ApolloServer } = require("apollo-server-express");
const path = require('path');
const db = require('./config/connection');
const routes = require('./routes');
const { authMiddleware } = required("./utils/auth");
// import typeDefs, resolvers in schemas
const app = express();
const PORT = process.env.PORT || 3001;
// `server.js`: Implement the Apollo Server and apply it to the Express server as middleware.
const server = new ApolloServer({
typeDefs,
resolvers,
context: authMiddleware,
});
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// if we're in production, serve client/build as static assets
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '../client/build')));
}
app.use(routes);
db.once('open', () => {
app.listen(PORT, () => console.log(`🌍 Now listening on localhost:${PORT}`));
console.log(`Use GraphQL at http://localhost:${PORT}${server.graphqlPath}`);
});
|
function rxnID = findRxnIDs(model, rxnList)
% Finds reaction indices in a model
%
% USAGE:
%
% rxnID = findRxnIDs(model, rxnList)
%
% INPUTS:
% model: COBRA model structure
% rxnList: cell array of reaction abbreviations
%
% OUTPUT:
% rxnID: indices for reactions corresponding to rxnList
% .. Author: - Ronan Fleming
if ~iscell(rxnList)
rxnList = cellstr(rxnList);
end
try
[~,rxnID] = ismember(rxnList,model.rxns);
catch
model.rxns = cellfun(@num2str,model.rxns,'UniformOutput',false);
[~,rxnID] = ismember(rxnList,model.rxns);
warning('Some model.rxns are double rather than char. Had to convert model.rxns to a cell array of character vectors.')
end
|
import { useState, useEffect } from "react";
import { Chess } from "chess.js";
import { Chessboard } from "react-chessboard";
import { validateFen } from 'chess.js'
import Engine from './Engine.js';
const DEPTH = 8;
const FEN_POSITION =
"rnbqkb1r/pp1p1ppp/2p2n2/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 2 4";
export default function App() {
const onBestMove = (bestMove) => {
setBestMove(bestMove);
}
const onEvaluation = (newEval) => {
setEvaluation(newEval);
}
const [game, setGame] = useState(new Chess());
const [fen, setFen] = useState("");
const [fenInput, setFenInput] = useState("");
const [evaluation, setEvaluation] = useState("0");
const [bestMove, setBestMove] = useState("null");
const { evaluatePosition, getEval, stop } = Engine({onBestMove, onEvaluation});
useEffect(()=> {
return ()=> {
stop();
}
}, [game]);
function onDrop(sourceSquare, targetSquare) {
const move = {
from: sourceSquare,
to: targetSquare,
};
const cpy = new Chess(game.fen());
try {
if (cpy.move(move) != null) {
setGame(cpy);
}
} catch (error) {
console.log(error);
return false;
}
setFen(game.fen());
evaluatePosition(game.fen());
return true;
}
const changEval = (newEval) => {
setEvaluation(newEval);
}
function handleFenChange(event) {
setFenInput(event.target.value);
}
function setBoardWithFen() {
const newGame = new Chess(fenInput);
if (validateFen(fenInput)) {
setGame(newGame);
} else {
console.log("Invalid FEN");
}
}
return (
<div style={{ display: "flex", height: "100vh" }}>
<div style={{ flex: 1 }}>
<Chessboard position={game.fen()} onPieceDrop={onDrop} />
</div>
<div style={{ flex: 1, padding: "10px" }}>
<div>
<h3>Set Board</h3>
<input
type="text"
value={fenInput}
onChange={handleFenChange}
placeholder="FEN"
/>
<button onClick={setBoardWithFen}>Set Board</button>
</div>
<div>
<h3>Evaluation</h3>
<p>{evaluation}</p>
</div>
<div>
<h3>Best Move</h3>
<p>{bestMove}</p>
</div>
<div>
<h3>FEN</h3>
<p>{fen}</p>
</div>
</div>
</div>
);
}
|
/**
* MIT License
*
* Copyright (c) 2022 DragonDreams ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <algorithm>
#include <stdexcept>
#include "denConnection.h"
#include "denServer.h"
#include "denRealMessage.h"
#include "message/denMessage.h"
#include "message/denMessageReader.h"
#include "message/denMessageWriter.h"
#include "socket/denSocketShared.h"
denConnection::denConnection() :
pConnectionState(ConnectionState::disconnected),
pConnectResendInterval( 1.0f ),
pConnectTimeout( 5.0f ),
pReliableResendInterval( 0.5f ),
pReliableTimeout( 3.0f ),
pElapsedConnectResend( 0.0f ),
pElapsedConnectTimeout( 0.0f ),
pProtocol(denProtocol::Protocols::DENetworkProtocol),
pNextLinkIdentifier(0),
pReliableNumberSend(0),
pReliableNumberRecv(0),
pReliableWindowSize(10),
pParentServer(nullptr){
}
denConnection::~denConnection() noexcept{
pParentServer = nullptr; // required to avoid potential segfault in denServer
pDisconnect(false, false);
}
void denConnection::SetConnectResendInterval(float interval){
pConnectResendInterval = std::max(interval, 0.01f);
}
void denConnection::SetConnectTimeout(float timeout){
pConnectTimeout = std::max(timeout, 0.01f);
}
void denConnection::SetReliableResendInterval(float interval){
pReliableResendInterval = std::max(interval, 0.01f);
}
void denConnection::SetReliableTimeout(float timeout){
pReliableTimeout = std::max(timeout, 0.01f);
}
void denConnection::SetLogger(const denLogger::Ref &logger){
pLogger = logger;
}
void denConnection::ConnectTo(const std::string &address){
if(pSocket || pConnectionState != ConnectionState::disconnected){
throw std::invalid_argument("already connected");
}
const denSocketAddress realRemoteAddress(ResolveAddress(address));
pSocket = CreateSocket();
if(realRemoteAddress.type == denSocketAddress::Type::ipv6){
pSocket->SetAddress(denSocketAddress::IPv6Any());
}else{
pSocket->SetAddress(denSocketAddress::IPv4Any());
}
pSocket->Bind();
pLocalAddress = pSocket->GetAddress().ToString();
const denMessage::Ref connectRequest(denMessage::Pool().Get());
{
denMessageWriter writer(connectRequest->Item());
writer.WriteByte((uint8_t)denProtocol::CommandCodes::connectionRequest);
writer.WriteUShort( 1 ); // version
writer.WriteUShort((uint8_t)denProtocol::Protocols::DENetworkProtocol);
}
pRealRemoteAddress = realRemoteAddress;
pRemoteAddress = address;
if(pLogger){
std::stringstream s;
s << "Connection: Connecting to " << pRealRemoteAddress.ToString();
pLogger->Log(denLogger::LogSeverity::info, s.str());
}
pSocket->SendDatagram(connectRequest->Item(), pRealRemoteAddress);
pConnectionState = ConnectionState::connecting;
pElapsedConnectResend = 0.0f;
pElapsedConnectTimeout = 0.0f;
}
void denConnection::Disconnect(){
pDisconnect(true, false);
}
void denConnection::SendMessage(const denMessage::Ref &message){
if(!message){
throw std::invalid_argument("message is nullptr");
}
if(message->Item().GetLength() < 1){
throw std::invalid_argument("message has 0 length");
}
if(pConnectionState != ConnectionState::connected){
throw std::invalid_argument("not connected");
}
// send message
const denMessage::Ref unrealMessage(denMessage::Pool().Get());
{
denMessageWriter writer(unrealMessage->Item());
writer.WriteByte((uint8_t)denProtocol::CommandCodes::message);
writer.Write(message->Item());
}
pSocket->SendDatagram(unrealMessage->Item(), pRealRemoteAddress);
}
void denConnection::SendReliableMessage(const denMessage::Ref &message){
if(!message){
throw std::invalid_argument("message is nullptr");
}
if(message->Item().GetLength() < 1){
throw std::invalid_argument("message has 0 length");
}
if(pConnectionState != ConnectionState::connected){
throw std::invalid_argument("not connected");
}
const denRealMessage::Ref realMessage(denRealMessage::Pool().Get());
realMessage->Item().type = denProtocol::CommandCodes::reliableMessage;
realMessage->Item().number = (pReliableNumberSend + pReliableMessagesSend.size()) % 65535;
realMessage->Item().state = denRealMessage::State::pending;
{
denMessageWriter writer(realMessage->Item().message->Item());
writer.WriteByte((uint8_t)denProtocol::CommandCodes::reliableMessage);
writer.WriteUShort((uint16_t)realMessage->Item().number);
writer.Write(message->Item());
}
pReliableMessagesSend.push_back(realMessage);
// if the message fits into the window send it right now
if(pReliableMessagesSend.size() <= (size_t)pReliableWindowSize){
pSocket->SendDatagram(realMessage->Item().message->Item(), pRealRemoteAddress);
realMessage->Item().state = denRealMessage::State::send;
realMessage->Item().elapsedResend = 0.0f;
realMessage->Item().elapsedTimeout = 0.0f;
}
}
void denConnection::LinkState(const denMessage::Ref &message, const denState::Ref &state, bool readOnly){
if(!message){
throw std::invalid_argument("message is nullptr");
}
if(message->Item().GetLength() < 1){
throw std::invalid_argument("message has 0 length");
}
if(message->Item().GetLength() > 0xffff){
throw std::invalid_argument("message too long");
}
if(!state){
throw std::invalid_argument("state is nullptr");
}
if(pConnectionState != ConnectionState::connected){
throw std::invalid_argument("not connected");
}
// check if a link exists with this state already that is not broken
StateLinks::const_iterator iterLink(std::find_if(pStateLinks.cbegin(),
pStateLinks.cend(), [&](const denStateLink::Ref &each){
return state.get() == each->GetState();
}));
if(iterLink != pStateLinks.cend() && (*iterLink)->GetLinkState() != denStateLink::State::down){
throw std::invalid_argument("link with state present");
}
// create the link if not existing, assign it a new identifier and add it
if(iterLink == pStateLinks.cend()){
const int lastNextLinkIdentifier = pNextLinkIdentifier;
while(std::find_if(pStateLinks.cbegin(), pStateLinks.cend(), [&](const denStateLink::Ref &each){
return each->GetIdentifier() == pNextLinkIdentifier;
}) != pStateLinks.cend()){
pNextLinkIdentifier = (pNextLinkIdentifier + 1) % 65535;
if(pNextLinkIdentifier == lastNextLinkIdentifier){
throw std::invalid_argument("too many state links");
}
}
const denStateLink::Ref link(std::make_shared<denStateLink>(*this, *state));
link->SetIdentifier(pNextLinkIdentifier);
pStateLinks.push_back(link);
iterLink = std::prev(pStateLinks.cend());
state->pLinks.push_back(link);
}
// add message
const denRealMessage::Ref realMessage(denRealMessage::Pool().Get());
realMessage->Item().type = denProtocol::CommandCodes::reliableLinkState;
realMessage->Item().number = (pReliableNumberSend + pReliableMessagesSend.size()) % 65535;
realMessage->Item().state = denRealMessage::State::pending;
{
denMessageWriter writer(realMessage->Item().message->Item());
writer.WriteByte((uint8_t)denProtocol::CommandCodes::reliableLinkState);
writer.WriteUShort((uint16_t)realMessage->Item().number);
writer.WriteUShort((uint16_t)(*iterLink)->GetIdentifier());
writer.WriteByte(readOnly ? 1 : 0); // flags: readOnly=0x1
writer.WriteUShort((uint16_t)message->Item().GetLength());
writer.Write(message->Item());
state->LinkWriteValuesWithVerify(writer);
}
pReliableMessagesSend.push_back(realMessage);
// if the message fits into the window send it right now
if(pReliableMessagesSend.size() <= (size_t)pReliableWindowSize){
pSocket->SendDatagram(realMessage->Item().message->Item(), pRealRemoteAddress);
realMessage->Item().state = denRealMessage::State::send;
realMessage->Item().elapsedResend = 0.0f;
realMessage->Item().elapsedTimeout = 0.0f;
}
(*iterLink)->SetLinkState(denStateLink::State::listening);
}
void denConnection::Update(float elapsedTime){
if(pConnectionState == ConnectionState::disconnected){
return;
}
if(!pParentServer){
while(true){
if(pConnectionState == ConnectionState::disconnected){
return;
}
try{
denSocketAddress addressReceive;
const denMessage::Ref message(pSocket->ReceiveDatagram(addressReceive));
if(!message){
break;
}
denMessageReader reader(message->Item());
ProcessDatagram(reader);
}catch(const std::exception &e){
if(pLogger){
pLogger->Log(denLogger::LogSeverity::error,
std::string("Connection: Update[1]: ") + e.what());
}
}
}
}
try{
if( pUpdateTimeouts(elapsedTime) ){
pUpdateStates();
}
}catch(const std::exception &e){
if(pLogger){
pLogger->Log(denLogger::LogSeverity::error,
std::string("Connection: Update[2]: ") + e.what());
}
}
}
denSocket::Ref denConnection::CreateSocket(){
return denSocketShared::CreateSocket();
}
denSocketAddress denConnection::ResolveAddress(const std::string &address){
return denSocketShared::ResolveAddress(address);
}
void denConnection::ConnectionEstablished(){
}
void denConnection::ConnectionFailed(ConnectionFailedReason){
}
void denConnection::ConnectionClosed(){
}
void denConnection::MessageProgress(size_t){
}
void denConnection::MessageReceived(const denMessage::Ref &){
}
denState::Ref denConnection::CreateState(const denMessage::Ref &, bool){
return nullptr;
}
bool denConnection::Matches(denSocket *bnSocket, const denSocketAddress &address) const{
return pSocket.get() == bnSocket && address == pRealRemoteAddress;
}
void denConnection::ProcessDatagram(denMessageReader& reader){
switch((denProtocol::CommandCodes)reader.ReadByte()){
case denProtocol::CommandCodes::connectionAck:
pProcessConnectionAck(reader);
break;
case denProtocol::CommandCodes::connectionClose:
pProcessConnectionClose(reader);
break;
case denProtocol::CommandCodes::message:
pProcessMessage(reader);
break;
case denProtocol::CommandCodes::reliableMessage:
pProcessReliableMessage(reader);
break;
case denProtocol::CommandCodes::reliableLinkState:
pProcessReliableLinkState(reader);
break;
case denProtocol::CommandCodes::reliableAck:
pProcessReliableAck(reader);
break;
case denProtocol::CommandCodes::linkUp:
pProcessLinkUp(reader);
break;
case denProtocol::CommandCodes::linkDown:
pProcessLinkDown(reader);
break;
case denProtocol::CommandCodes::linkUpdate:
pProcessLinkUpdate(reader);
break;
default:
// throw std::invalid_argument("Invalid command code");
break;
}
}
void denConnection::AcceptConnection(denServer &server, const denSocket::Ref &bnSocket,
const denSocketAddress &address, denProtocol::Protocols protocol){
pSocket = bnSocket;
pRealRemoteAddress = address;
pRemoteAddress = address.ToString();
pConnectionState = ConnectionState::connected;
pElapsedConnectResend = 0.0f;
pElapsedConnectTimeout = 0.0f;
pProtocol = protocol;
pParentServer = &server;
ConnectionEstablished();
}
void denConnection::pDisconnect(bool notify, bool remoteClosed){
if(!pSocket || pConnectionState == ConnectionState::disconnected){
return;
}
if(pConnectionState == ConnectionState::connected){
if(remoteClosed){
if(pLogger){
pLogger->Log(denLogger::LogSeverity::info, "Connection: Remote closed connection");
}
}else{
if(pLogger){
pLogger->Log(denLogger::LogSeverity::info, "Connection: Disconnecting");
}
const denMessage::Ref connectionClose(denMessage::Pool().Get());
{
denMessageWriter writer(connectionClose->Item());
writer.WriteByte((uint8_t)denProtocol::CommandCodes::connectionClose);
}
pSocket->SendDatagram(connectionClose->Item(), pRealRemoteAddress);
}
}
pClearStates();
pReliableMessagesRecv.clear();
pReliableMessagesSend.clear();
pReliableNumberSend = 0;
pReliableNumberRecv = 0;
pCloseSocket();
if(pLogger){
pLogger->Log(denLogger::LogSeverity::info, "Connection: Connection closed");
}
if(notify){
ConnectionClosed();
}
pRemoveConnectionFromParentServer();
}
void denConnection::pClearStates(){
pModifiedStateLinks.clear();
StateLinks::const_iterator iterLink;
for(iterLink = pStateLinks.cbegin(); iterLink != pStateLinks.cend(); iterLink++){
denState * const state = (*iterLink)->GetState();
if(state){
state->pLinks.remove_if([&](const denStateLink::Ref &each){
if(each == *iterLink){
each->pState = nullptr;
return true;
}
return false;
});
}
}
pStateLinks.clear();
}
void denConnection::pCloseSocket(){
pConnectionState = ConnectionState::disconnected;
pElapsedConnectResend = 0.0f;
pElapsedConnectTimeout = 0.0f;
pSocket.reset();
}
void denConnection::pRemoveConnectionFromParentServer(){
if(!pParentServer){
return;
}
denServer::Connections &connections = pParentServer->pConnections;
pParentServer = nullptr;
// below this point has to be save against this-pointer being potentially deleted
denServer::Connections::iterator iter(std::find_if(connections.begin(),
connections.end(), [&](const denConnection::Ref &each){
return each.get() == this;
}));
if(iter != connections.end()){
connections.erase(iter);
}
}
void denConnection::pUpdateStates(){
int linkCount = (int)pModifiedStateLinks.size();
if(linkCount == 0){
return;
}
ModifiedStateLinks::iterator iter;
int changedCount = 0;
for(iter = pModifiedStateLinks.begin(); iter != pModifiedStateLinks.end(); iter++){
if((*iter)->GetLinkState() == denStateLink::State::up && (*iter)->GetChanged()){
changedCount++;
}
}
if(changedCount == 0){
return;
}
changedCount = std::min(changedCount, 255);
const denMessage::Ref updateMessage(denMessage::Pool().Get());
{
denMessageWriter writer(updateMessage->Item());
writer.WriteByte((uint8_t)denProtocol::CommandCodes::linkUpdate);
writer.WriteByte((uint8_t)changedCount);
for(iter = pModifiedStateLinks.begin(); iter != pModifiedStateLinks.end(); ){
if((*iter)->GetLinkState() != denStateLink::State::up || !(*iter)->GetChanged()){
iter++;
continue;
}
writer.WriteUShort((uint16_t)((*iter)->GetIdentifier()));
denState * const state = (*iter)->GetState();
if(!state){
//throw std::invalid_argument("state link droppped");
pModifiedStateLinks.erase(ModifiedStateLinks::iterator(iter++));
continue;
}
state->LinkWriteValues(writer, **iter);
pModifiedStateLinks.erase(ModifiedStateLinks::iterator(iter++));
changedCount--;
if(changedCount == 0){
break;
}
}
}
pSocket->SendDatagram(updateMessage->Item(), pRealRemoteAddress);
}
bool denConnection::pUpdateTimeouts(float elapsedTime){
switch(pConnectionState){
case ConnectionState::connected:{
// increase the timeouts on all send packages
Messages::const_iterator iter;
for(iter = pReliableMessagesSend.cbegin(); iter != pReliableMessagesSend.cend(); iter++){
if((*iter)->Item().state != denRealMessage::State::send){
continue;
}
(*iter)->Item().elapsedTimeout += elapsedTime;
if((*iter)->Item().elapsedTimeout > pReliableTimeout){
if(pLogger){
pLogger->Log(denLogger::LogSeverity::error, "Connection: Reliable message timeout");
}
Disconnect();
return false;
}
(*iter)->Item().elapsedResend += elapsedTime;
if((*iter)->Item().elapsedResend > pReliableResendInterval){
(*iter)->Item().elapsedResend = 0.0f;
pSocket->SendDatagram((*iter)->Item().message->Item(), pRealRemoteAddress);
}
}
}
return true;
case ConnectionState::connecting:
// increase connecting timeout
pElapsedConnectTimeout += elapsedTime;
if(pElapsedConnectTimeout > pConnectTimeout){
pCloseSocket();
if(pLogger){
pLogger->Log(denLogger::LogSeverity::info, "Connection: Connection failed (timeout)");
}
ConnectionFailed(ConnectionFailedReason::timeout);
return false;
}
pElapsedConnectResend += elapsedTime;
if(pElapsedConnectResend > pConnectResendInterval){
if(pLogger){
pLogger->Log(denLogger::LogSeverity::debug, "Connection: Resend connect request");
}
pElapsedConnectResend = 0.0f;
const denMessage::Ref connectRequest(denMessage::Pool().Get());
{
denMessageWriter writer(connectRequest->Item());
writer.WriteByte((uint8_t)denProtocol::CommandCodes::connectionRequest);
writer.WriteUShort( 1 ); // version
writer.WriteUShort((uint8_t)denProtocol::Protocols::DENetworkProtocol);
}
pSocket->SendDatagram(connectRequest->Item(), pRealRemoteAddress);
}
return true;
default:
return true;
}
}
void denConnection::pInvalidateState(const denState::Ref &state){
StateLinks::iterator iter;
for(iter = pStateLinks.begin(); iter != pStateLinks.end(); ){
denStateLink * const link = iter->get();
if(state.get() == link->GetState()){
denState::StateLinks::iterator iter2(state->FindLink(link));
if(iter2 != state->pLinks.end()){
(*iter2)->pState = nullptr;
state->pLinks.erase(iter2);
}
pStateLinks.erase(StateLinks::iterator(iter++));
}else{
iter++;
}
}
}
void denConnection::pAddModifiedStateLink(denStateLink *link){
pModifiedStateLinks.push_back(link);
}
void denConnection::pProcessQueuedMessages(){
Messages::iterator iter(std::find_if(pReliableMessagesRecv.begin(),
pReliableMessagesRecv.end(), [&](const denRealMessage::Ref &each){
return each->Item().number == pReliableNumberRecv;
}));
while(iter != pReliableMessagesRecv.cend()){
switch((*iter)->Item().type){
case denProtocol::CommandCodes::reliableMessage:{
denMessageReader reader((*iter)->Item().message->Item());
pProcessReliableMessageMessage(reader);
}break;
case denProtocol::CommandCodes::reliableLinkState:{
denMessageReader reader((*iter)->Item().message->Item());
pProcessLinkState(reader);
}break;
default:
break;
}
pReliableMessagesRecv.erase(iter);
pReliableNumberRecv = (pReliableNumberRecv + 1) % 65535;
iter = std::find_if(pReliableMessagesRecv.begin(),
pReliableMessagesRecv.end(), [&](const denRealMessage::Ref &each){
return each->Item().number == pReliableNumberRecv;
});
}
}
void denConnection::pProcessConnectionAck(denMessageReader &reader){
if(pConnectionState != ConnectionState::connecting){
//throw std::invalid_argument("Not connecting");
return;
}
switch((denProtocol::ConnectionAck)reader.ReadByte()){
case denProtocol::ConnectionAck::accepted:
pProtocol = (denProtocol::Protocols)reader.ReadUShort();
pConnectionState = ConnectionState::connected;
pElapsedConnectResend = 0.0f;
pElapsedConnectTimeout = 0.0f;
if(pLogger){
pLogger->Log(denLogger::LogSeverity::info, "Connection: Connection established");
}
ConnectionEstablished();
break;
case denProtocol::ConnectionAck::rejected:
pCloseSocket();
if(pLogger){
pLogger->Log(denLogger::LogSeverity::info, "Connection: Connection failed (rejected)");
}
ConnectionFailed(ConnectionFailedReason::rejected);
break;
case denProtocol::ConnectionAck::noCommonProtocol:
pCloseSocket();
if(pLogger){
pLogger->Log(denLogger::LogSeverity::info, "Connection: Connection failed (no common protocol)");
}
ConnectionFailed(ConnectionFailedReason::noCommonProtocol);
break;
default:
pCloseSocket();
if(pLogger){
pLogger->Log(denLogger::LogSeverity::info, "Connection: Connection failed (invalid message)");
}
ConnectionFailed(ConnectionFailedReason::invalidMessage);
}
}
void denConnection::pProcessConnectionClose(denMessageReader&){
pDisconnect(true, true);
}
void denConnection::pProcessMessage(denMessageReader &reader){
const denMessage::Ref message(denMessage::Pool().Get());
message->Item().SetLength(reader.GetLength() - reader.GetPosition());
reader.Read(message->Item());
MessageReceived(message);
}
void denConnection::pProcessReliableMessage(denMessageReader &reader){
if(pConnectionState != ConnectionState::connected){
//throw std::invalid_argument("Reliable message received although not connected.");
return;
}
const int number = reader.ReadUShort();
bool validNumber;
if(number < pReliableNumberRecv){
validNumber = number < (pReliableNumberRecv + pReliableWindowSize) % 65535;
}else{
validNumber = number < pReliableNumberRecv + pReliableWindowSize;
}
if(!validNumber){
//throw std::invalid_argument("Reliable message: invalid sequence number.");
return;
}
const denMessage::Ref ackMessage(denMessage::Pool().Get());
{
denMessageWriter ackWriter(ackMessage->Item());
ackWriter.WriteByte((uint8_t)denProtocol::CommandCodes::reliableAck);
ackWriter.WriteUShort((uint16_t)number);
ackWriter.WriteByte((uint8_t)denProtocol::ReliableAck::success);
}
pSocket->SendDatagram(ackMessage->Item(), pRealRemoteAddress);
if(number == pReliableNumberRecv){
pProcessReliableMessageMessage(reader);
pReliableNumberRecv = (pReliableNumberRecv + 1) % 65535;
pProcessQueuedMessages();
}else{
pAddReliableReceive(denProtocol::CommandCodes::reliableMessage, number, reader);
}
}
void denConnection::pProcessReliableMessageMessage(denMessageReader &reader){
denMessage::Ref message(denMessage::Pool().Get());
message->Item().SetLength(reader.GetLength() - reader.GetPosition());
reader.Read(message->Item());
MessageReceived(message);
}
void denConnection::pProcessReliableAck(denMessageReader &reader){
if(pConnectionState != ConnectionState::connected){
//throw std::invalid_argument("Reliable ack: not connected.");
return;
}
const int number = reader.ReadUShort();
const denProtocol::ReliableAck code = (denProtocol::ReliableAck)reader.ReadByte();
Messages::const_iterator iter(std::find_if(pReliableMessagesSend.begin(),
pReliableMessagesSend.end(), [&](const denRealMessage::Ref &each){
return (*each).Item().number == number;
}));
if(iter == pReliableMessagesSend.cend()){
//throw std::invalid_argument("Reliable ack: no reliable transmission with this number waiting for an ack!");
return;
}
const denRealMessage::Ref message(*iter);
switch(code){
case denProtocol::ReliableAck::success:
message->Item().state = denRealMessage::State::done;
pRemoveSendReliablesDone();
break;
case denProtocol::ReliableAck::failed:
if(pLogger){
pLogger->Log(denLogger::LogSeverity::debug, "Connection: Reliable ACK failed, resend");
}
message->Item().elapsedResend = 0.0f;
pSocket->SendDatagram(message->Item().message->Item(), pRealRemoteAddress);
break;
}
}
void denConnection::pProcessReliableLinkState(denMessageReader &reader){
if(pConnectionState != ConnectionState::connected){
//throw std::invalid_argument("Link state: not connected.");
return;
}
const int number = reader.ReadUShort();
bool validNumber;
if( number < pReliableNumberRecv ){
validNumber = number < (pReliableNumberRecv + pReliableWindowSize) % 65535;
}else{
validNumber = number < pReliableNumberRecv + pReliableWindowSize;
}
if( ! validNumber ){
//throw std::invalid_argument("Link state: invalid sequence number.");
return;
}
const denMessage::Ref ackMessage(denMessage::Pool().Get());
{
denMessageWriter ackWriter(ackMessage->Item());
ackWriter.WriteByte((uint8_t)denProtocol::CommandCodes::reliableAck);
ackWriter.WriteUShort((uint16_t)number);
ackWriter.WriteByte((uint8_t)denProtocol::ReliableAck::success);
}
pSocket->SendDatagram(ackMessage->Item(), pRealRemoteAddress);
if(number == pReliableNumberRecv){
pProcessLinkState(reader);
pReliableNumberRecv = (pReliableNumberRecv + 1) % 65535;
pProcessQueuedMessages();
}else{
pAddReliableReceive(denProtocol::CommandCodes::reliableLinkState, number, reader);
}
}
void denConnection::pProcessLinkUp(denMessageReader &reader){
if(pConnectionState != ConnectionState::connected){
//throw std::invalid_argument("Reliable ack: not connected.");
return;
}
const int identifier = reader.ReadUShort();
StateLinks::const_iterator iterLink(std::find_if(pStateLinks.cbegin(),
pStateLinks.cend(), [&](const denStateLink::Ref &each){
return each->GetIdentifier() == identifier;
}));
if(iterLink == pStateLinks.cend()){
//throw std::invalid_argument("up link with identifier absent");
return;
}
if((*iterLink)->GetLinkState() != denStateLink::State::listening){
//throw std::invalid_argument("up link with identifier absent or not listening");
return;
}
(*iterLink)->SetLinkState(denStateLink::State::up);
}
void denConnection::pProcessLinkDown(denMessageReader &reader){
if(pConnectionState != ConnectionState::connected){
//throw std::invalid_argument("Reliable ack: not connected.");
return;
}
const int identifier = reader.ReadUShort();
StateLinks::const_iterator iterLink(std::find_if(pStateLinks.cbegin(),
pStateLinks.cend(), [&](const denStateLink::Ref &each){
return each->GetIdentifier() == identifier;
}));
if(iterLink == pStateLinks.cend()){
//throw std::invalid_argument("down link with identifier absent");
return;
}
if((*iterLink)->GetLinkState() != denStateLink::State::up){
//throw std::invalid_argument("down link with identifier not up");
return;
}
(*iterLink)->SetLinkState(denStateLink::State::down);
}
void denConnection::pProcessLinkState(denMessageReader &reader){
const int identifier = reader.ReadUShort();
const bool readOnly = reader.ReadByte() == 1; // flags: 0x1=readOnly
StateLinks::const_iterator iterLink(std::find_if(pStateLinks.cbegin(),
pStateLinks.cend(), [&](const denStateLink::Ref &each){
return each->GetIdentifier() == identifier;
}));
if(iterLink != pStateLinks.cend() && (*iterLink)->GetLinkState() != denStateLink::State::down){
//throw std::invalid_argument("Link state: link with this identifier already exists.");
return;
}
// create linked network state
denMessage::Ref message(denMessage::Pool().Get());
message->Item().SetLength(reader.ReadUShort());
reader.Read(message->Item());
const denState::Ref state(CreateState(message, readOnly));
denProtocol::CommandCodes code = denProtocol::CommandCodes::linkDown;
if(state){
if(!state->LinkReadAndVerifyAllValues(reader)){
//throw std::invalid_argument("Link state does not match the state provided.");
return;
}
if(iterLink != pStateLinks.cend()){
//throw std::invalid_argument("Link state existing already.");
return;
}
const denStateLink::Ref link(std::make_shared<denStateLink>(*this, *state));
link->SetIdentifier(identifier);
pStateLinks.push_back(link);
state->pLinks.push_back(link);
link->SetLinkState(denStateLink::State::up);
code = denProtocol::CommandCodes::linkUp;
}
message = denMessage::Pool().Get();
{
denMessageWriter writer(message->Item());
writer.WriteByte((uint8_t)code);
writer.WriteUShort((uint16_t)identifier);
}
pSocket->SendDatagram(message->Item(), pRealRemoteAddress);
}
void denConnection::pProcessLinkUpdate(denMessageReader &reader){
if(pConnectionState != ConnectionState::connected){
//throw std::invalid_argument("Reliable ack: not connected.");
return;
}
const int count = reader.ReadByte();
int i;
for(i=0; i<count; i++){
const int identifier = reader.ReadUShort();
StateLinks::const_iterator iterLink(std::find_if(pStateLinks.cbegin(),
pStateLinks.cend(), [&](const denStateLink::Ref &each){
return each->GetIdentifier() == identifier;
}));
if(iterLink == pStateLinks.cend()){
//throw std::invalid_argument("invalid link identifier");
return;
}
if((*iterLink)->GetLinkState() != denStateLink::State::up){
//throw std::invalid_argument("invalid link identifier");
return;
}
denState * const state = (*iterLink)->GetState();
if(!state){
//throw std::invalid_argument("state link droppped");
return;
}
state->LinkReadValues(reader, *iterLink->get());
}
}
void denConnection::pAddReliableReceive(denProtocol::CommandCodes type, int number, denMessageReader &reader){
denRealMessage::Ref message(denRealMessage::Pool().Get());
message->Item().message->Item().SetLength(reader.GetLength() - reader.GetPosition());
reader.Read(message->Item().message->Item());
message->Item().type = type;
message->Item().number = number;
message->Item().state = denRealMessage::State::done;
pReliableMessagesRecv.push_back(message);
}
void denConnection::pRemoveSendReliablesDone(){
bool anyRemoved = false;
while(!pReliableMessagesSend.empty()){
if(pReliableMessagesSend.front()->Item().state != denRealMessage::State::done){
break;
}
pReliableMessagesSend.pop_front();
pReliableNumberSend = (pReliableNumberSend + 1) % 65535;
anyRemoved = true;
}
if(anyRemoved){
pSendPendingReliables();
}
}
void denConnection::pSendPendingReliables(){
Messages::const_iterator iter;
int sendCount = 0;
for(iter = pReliableMessagesSend.cbegin(); iter != pReliableMessagesSend.cend(); iter++){
if((*iter)->Item().state != denRealMessage::State::pending){
continue;
}
pSocket->SendDatagram((*iter)->Item().message->Item(), pRealRemoteAddress);
(*iter)->Item().state = denRealMessage::State::send;
(*iter)->Item().elapsedResend = 0.0f;
(*iter)->Item().elapsedTimeout = 0.0f;
if(++sendCount == pReliableWindowSize){
break;
}
}
}
|
use crate::{
component_container::ComponentContainer,
query::ComponentContainerTrait,
system::{Borrow, BorrowType, SystemRunState},
Component, Ref, RefMut,
};
use parking_lot::{
MappedRwLockReadGuard, MappedRwLockWriteGuard, RwLockReadGuard, RwLockWriteGuard,
};
use std::any::TypeId;
/// The type parameter for a [`Query`](crate::Query)
pub trait QueryParameter {
/// The lock returned from [`QueryParameter::lock`]
type ComponentContainerLock<'a>;
/// The component container that is used to get [`Component`]s from
type ComponentContainer<'a>: ComponentContainerTrait<'a>;
/// Locks any needed state, the first step to creating a [`Query`](crate::Query)
fn lock<'a>(state: &SystemRunState<'a>) -> Self::ComponentContainerLock<'a>;
/// Constructs the component container from the locked state, the final state to creating a [`Query`](crate::Query)
fn construct<'a>(
lock: &'a mut Self::ComponentContainerLock<'_>,
) -> Self::ComponentContainer<'a>;
/// Returns an iterator over all the [`Component`] types that will be locked
fn get_component_types() -> impl Iterator<Item = Borrow>;
}
impl<C> QueryParameter for Ref<'_, C>
where
C: Component,
{
type ComponentContainerLock<'a> = Option<MappedRwLockReadGuard<'a, ComponentContainer<C>>>;
type ComponentContainer<'a> = Option<&'a ComponentContainer<C>>;
fn lock<'a>(state: &SystemRunState<'a>) -> Self::ComponentContainerLock<'a> {
Some(RwLockReadGuard::map(
state
.components
.get(&TypeId::of::<C>())?
.try_read()
.expect("the lock should always be available"),
|components| components.downcast_ref::<C>(),
))
}
fn construct<'a>(
lock: &'a mut Self::ComponentContainerLock<'_>,
) -> Self::ComponentContainer<'a> {
Some(lock.as_mut()?)
}
fn get_component_types() -> impl Iterator<Item = Borrow> {
std::iter::once(Borrow {
id: TypeId::of::<C>(),
name: std::any::type_name::<C>(),
borrow_type: BorrowType::Immutable,
})
}
}
impl<C> QueryParameter for RefMut<'_, C>
where
C: Component,
{
type ComponentContainerLock<'a> = Option<MappedRwLockWriteGuard<'a, ComponentContainer<C>>>;
type ComponentContainer<'a> = Option<&'a mut ComponentContainer<C>>;
fn lock<'a>(state: &SystemRunState<'a>) -> Self::ComponentContainerLock<'a> {
Some(RwLockWriteGuard::map(
state
.components
.get(&TypeId::of::<C>())?
.try_write()
.expect("the lock should always be available"),
|components| components.downcast_mut::<C>(),
))
}
fn construct<'a>(
lock: &'a mut Self::ComponentContainerLock<'_>,
) -> Self::ComponentContainer<'a> {
Some(lock.as_mut()?)
}
fn get_component_types() -> impl Iterator<Item = Borrow> {
std::iter::once(Borrow {
id: TypeId::of::<C>(),
name: std::any::type_name::<C>(),
borrow_type: BorrowType::Mutable,
})
}
}
pub struct OptionalComponentContainer<T>(pub(crate) T);
impl<P> QueryParameter for Option<P>
where
P: QueryParameter,
{
type ComponentContainerLock<'a> = P::ComponentContainerLock<'a>;
type ComponentContainer<'a> = OptionalComponentContainer<P::ComponentContainer<'a>>;
fn lock<'a>(state: &SystemRunState<'a>) -> Self::ComponentContainerLock<'a> {
P::lock(state)
}
fn construct<'a>(
lock: &'a mut Self::ComponentContainerLock<'_>,
) -> Self::ComponentContainer<'a> {
OptionalComponentContainer(P::construct(lock))
}
fn get_component_types() -> impl Iterator<Item = Borrow> {
P::get_component_types()
}
}
macro_rules! query_parameter_tuple {
($($param:ident),*) => {
impl<$($param),*> QueryParameter for ($($param,)*)
where
$($param: QueryParameter,)*
{
type ComponentContainerLock<'a> = ($($param::ComponentContainerLock<'a>,)*);
type ComponentContainer<'a> = ($($param::ComponentContainer<'a>,)*);
#[allow(clippy::unused_unit)]
fn lock<'a>(state: &SystemRunState<'a>) -> Self::ComponentContainerLock<'a> {
_ = state;
($($param::lock(state),)*)
}
#[allow(clippy::unused_unit)]
fn construct<'this>(state: &'this mut Self::ComponentContainerLock<'_>) -> Self::ComponentContainer<'this> {
#[allow(non_snake_case)]
let ($($param,)*) = state;
($($param::construct($param),)*)
}
fn get_component_types() -> impl Iterator<Item = Borrow> {
std::iter::empty()
$(
.chain($param::get_component_types())
)*
}
}
};
}
query_parameter_tuple!();
query_parameter_tuple!(A);
query_parameter_tuple!(A, B);
query_parameter_tuple!(A, B, C);
query_parameter_tuple!(A, B, C, D);
query_parameter_tuple!(A, B, C, D, E);
query_parameter_tuple!(A, B, C, D, E, F);
query_parameter_tuple!(A, B, C, D, E, F, G);
query_parameter_tuple!(A, B, C, D, E, F, G, H);
query_parameter_tuple!(A, B, C, D, E, F, G, H, I);
query_parameter_tuple!(A, B, C, D, E, F, G, H, I, J);
query_parameter_tuple!(A, B, C, D, E, F, G, H, I, J, K);
query_parameter_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
query_parameter_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
query_parameter_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
query_parameter_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
query_parameter_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
|
#!/usr/bin/python3
"""class representing a student"""
class Student:
"""a class student"""
def __init__(self, first_name, last_name, age):
"""initialization of the attributes
Args:
first_name (str): first name of student
last_name (str): last name of student
age (int): age of student
"""
self.first_name = first_name
self.last_name = last_name
self.age= age
def to_json(self):
"""gets the dictonary representation ofstudent"""
return self.__dict__
|
import path from 'path'
import process from 'process';
import fs from 'fs'
import { Storage, Bucket } from '@google-cloud/storage';
import { SHA256 } from 'crypto-js'
import { Encryptor } from './Encryptor'
import type { EncryptedObject } from './Encryptor'
import type { ValidStoredData } from './StoredDataValidator';
import { Log } from './Log';
export class DataStorage {
storage: Storage
bucket: Bucket
constructor(
private privateKey: string,
bucketName = process.env.BUCKET || 'adapterjs-encrypted-user-data',
public persistantStorageDir = path.join(__dirname, '..', 'cache', 'database')
) {
if (!fs.existsSync(persistantStorageDir)){
Log.debug('Creating local data storage caching directory: ' + persistantStorageDir)
fs.mkdirSync(persistantStorageDir, { recursive: true })
}
if (!process.env.GCS_PROJECT_ID)
throw Error("Setup Error: The 'GCS_PROJECT_ID' environment variable has not been set.")
if (!process.env.GCS_CLIENT_EMAIL)
throw Error("Setup Error: The 'GCS_CLIENT_EMAIL' environment variable has not been set.")
if (!process.env.GCS_PRIVATE_KEY)
throw Error("Setup Error: The 'GCS_PRIVATE_KEY' environment variable has not been set.")
this.storage = new Storage({
projectId: process.env.GCS_PROJECT_ID,
credentials: {
client_email: process.env.GCS_CLIENT_EMAIL,
private_key: process.env.GCS_PRIVATE_KEY.replace(/\\n/g, '\n')
}
})
this.bucket = this.storage.bucket(bucketName)
}
async retrieveData(contractAddress: string, ref: string): Promise<ValidStoredData> {
const filename = SHA256(contractAddress + ref).toString() + '.json'
const filepath = path.join(this.persistantStorageDir, filename)
Log.debug('Attemping to fetch from local data storage caching directory: ' + filepath)
// Check to see if file has been previously downloaded and stored in cache
if (!fs.existsSync(filepath)) {
try {
await this.bucket.file(filename).download({ destination: filepath })
} catch (untypedError) {
const error = untypedError as Error
throw Error(`Unable to fetch stored data: ${error.message}`)
}
}
const encryptedObj = JSON.parse(fs.readFileSync(filepath, {encoding: 'utf8'})) as EncryptedObject
const storedData = Encryptor.decrypt(this.privateKey, contractAddress, ref, encryptedObj)
return storedData
}
}
|
<template id="main">
<v-ons-page>
<page1/>
<page2/>
<v-ons-toolbar>
<div class="center">{{ titles }}</div>
</v-ons-toolbar>
<v-ons-tabbar swipeable position="auto"
:tabs="tabs"
:visible="true"
:index.sync="activeIndex"
>
</v-ons-tabbar>
</v-ons-page>
</template>
<div id="app"></div>
<script>
import Page1 from './components/Page1.vue'
import Page2 from './components/Page2.vue'
export default {
name: 'app',
data() {
return {
titles: 'Fatmaster',
activeIndex: 0,
tabs: [
{
// icon: this.md() ? null : 'ion-home',
label: 'Home',
page: Page1,
props: {
myProp: 'This is a page prop!'
},
key: "homePage"
},
{
// icon: this.md() ? null : 'ion-ios-bell',
label: 'Page 2',
page: Page2,
badge: 7,
key: "newsPage"
},
]
}
},
components: {
Page1,
Page2
},
methods: {
md() {
return this.$ons.platform.isAndroid();
}
},
computed: {
title() {
return this.tabs[this.activeIndex].label;
}
}
}
</script>
|
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ListMedicoComponent } from './views/SistemaMedico/list-medico/list-medico.component';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from "@angular/forms";
import { MatButtonModule } from "@angular/material/button";
import { MatToolbarModule } from "@angular/material/toolbar";
import { MatSidenavModule } from "@angular/material/sidenav";
import { MatListModule } from "@angular/material/list";
import { MatCardModule } from "@angular/material/card";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatInputModule } from "@angular/material/input";
import { MatTableModule } from "@angular/material/table";
import { MatSelectModule } from "@angular/material/select";
import { MatGridListModule } from "@angular/material/grid-list";
import { MatMenuModule } from "@angular/material/menu";
import { MatIconModule } from "@angular/material/icon";
import { LayoutModule } from "@angular/cdk/layout";
import { MatSnackBarModule } from "@angular/material/snack-bar";
import { CreateMedicoComponent } from './views/SistemaMedico/create-medico/create-medico.component';
@NgModule({
declarations: [
AppComponent,
ListMedicoComponent,
CreateMedicoComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
HttpClientModule,
FormsModule,
MatButtonModule,
MatToolbarModule,
MatSidenavModule,
MatListModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatTableModule,
MatSelectModule,
MatGridListModule,
MatMenuModule,
MatIconModule,
LayoutModule,
MatSnackBarModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
|
# TestEndExpr.jl
A package for the sake of testing the `test_end_expr` functionality of `ReTestItems.runtests`.
We want to emulate a situation where correct usage of a package requires users to uphold a certain invariant.
In this very simplified example, `Page` objects must be pinned via `pin!` when in use, and subsequently unpinned via `unpin!` when no longer in use; there must be an equal number of `pin!` and `unpin!` calls in order to avoid a memory leak.
We want to be able to write potentially very many `@testitem`s which test all sorts of functionality that use `Page`s under the hood.
But we also want to test that every such usage correctly upholds the invariant, i.e. no `Page` is left "pinned" at the end of the `@testitem`.
We could do that by manually adding something like `@test no_pages_pinned()` as the last line of every `@testitem`, but we might not want to rely on test authors remembering to do this.
So instead, we want to use `test_end_expr` to declare a block of code like `@test no_pages_pinned()` to automatically run at the end of every `@testitem`.
In the tests of this package, we define test-items that **pass** when run without such a `test_end_expr`, but at least one of the test-items **fails** when run with a `test_end_expr` testing that no pages are left pinned.
|
package com.rbts.hrms.candidateonboarding.repository;
import com.rbts.hrms.candidateonboarding.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Spring Data JPA repository for the Employee entity.
*/
@SuppressWarnings("unused")
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
@Query("select e from Employee e where e.emailId = ?1")
Employee findByEmail(String email);
@Query("select e from Employee e where e.contactNo = ?1")
Employee findBycontactNo(String contactNo);
@Query("select e from Employee e where e.designation = ?1")
List<Employee> findByDesignation(String designation);
@Query("select e from Employee e where e.empId = ?1")
Employee findByEmpId(String empid);
@Query("select e from Employee e where e.id = ?1")
Employee getById(Long id);
@Query("select e from Employee e order by e.fullName asc")
List<Employee> findAllData();
}
|
import os
from PIL import Image
import numpy as np
def load_image(path):
""" Load image from path. Return a numpy array """
image = Image.open(path)
return np.asarray(image) / 255
def initialize_K_centroids(X, K):
""" Choose K points from X at random """
m = len(X)
return X[np.random.choice(m, K, replace=False), :]
def find_closest_centroids(X, centroids):
m = len(X)
c = np.zeros(m)
for i in range(m):
# Find distances
distances = np.linalg.norm(X[i] - centroids, axis=1)
# Assign closest cluster to c[i]
c[i] = np.argmin(distances)
return c
def compute_means(X, idx, K):
_, n = X.shape
centroids = np.zeros((K, n))
for k in range(K):
examples = X[np.where(idx == k)]
mean = [np.mean(column) for column in examples.T]
centroids[k] = mean
return centroids
def find_k_means(X, K, max_iters=10):
centroids = initialize_K_centroids(X, K)
previous_centroids = centroids
for _ in range(max_iters):
idx = find_closest_centroids(X, centroids)
centroids = compute_means(X, idx, K)
if (previous_centroids==centroids).all():
# The centroids aren't moving anymore.
return centroids
else:
previous_centroids = centroids
return centroids, idx
def compress_and_save_image(input_image, quality=40):
try:
# Load the image
image = load_image(input_image)
w, h, d = image.shape
# Get the feature matrix X
X = image.reshape((w * h, d))
K = quality # the number of colors in the image
# Get colors
colors, _ = find_k_means(X, K, max_iters=20)
# Indexes for color for each pixel
idx = find_closest_centroids(X, colors)
# Reconstruct the image
idx = np.array(idx, dtype=np.uint8)
X_reconstructed = np.array(colors[idx, :] * 255, dtype=np.uint8).reshape((w, h, d))
compressed_image = Image.fromarray(X_reconstructed)
# Save reconstructed image to disk
output_path = 'compressed_image.jpg' # You can specify a different output path
compressed_image.save(output_path)
return output_path
except Exception as e:
return str(e)
|
import { IUsersGateway } from 'domain/interfaces';
import { ApiRepository, PrimeRepository, CacheRepository } from '../repositories';
import { UserMap } from '../mappers';
import { IUserData, IUserFields } from 'domain/entities';
export class UsersGateway implements IUsersGateway {
constructor(
public cache: CacheRepository,
public api: ApiRepository,
public prime: PrimeRepository,
public userMap: UserMap
) {}
async getAccount(): Promise<IUserData | undefined> {
const response = await this.prime.users.me<IUserFields>();
if (!response?.data) return;
const userResponse = await this.api.users.get(response?.data.id);
if (userResponse?.data && userResponse?.data.length > 0) {
return this.userMap.toData(response?.data, userResponse.data[0]);
} else {
return this.userMap.toData(response?.data);
}
}
}
|
---
title: ToggleButton
---
# ToggleButton
A two-state button that can be either on or off.
```tsx preview
<Column gap="sm" cross="center">
<ToggleButton variant="flat">Toggle</ToggleButton>
</Column>
```
## Stateful
```tsx preview
() => {
const [bold, setBold] = React.useState(false);
return (
<ToggleButton
pressed={bold}
onPressedChange={setBold}
size="sm"
aria-label={bold ? 'Turn off bold' : 'Turn on bold'}
>
<Icon as={BsTypeBold} />
</ToggleButton>
);
};
```
|
package mk.finki.emt.feedreader.sharedkernel.domain.events.subscriptions;
import lombok.Getter;
import mk.finki.emt.feedreader.sharedkernel.domain.config.TopicHolder;
import mk.finki.emt.feedreader.sharedkernel.domain.events.DomainEvent;
/**
* The event container published when the user unsubscribed from a feed
* it contains all the data needed when the listener intercepts the event
*/
@Getter
public class UserUnsubscribed extends DomainEvent {
private String feedSourceId;
public UserUnsubscribed(String feedSourceId) {
super(TopicHolder.TOPIC_USER_UNSUBSCRIBED_FROM_FEED);
this.feedSourceId = feedSourceId;
}
public UserUnsubscribed() {
super(TopicHolder.TOPIC_USER_UNSUBSCRIBED_FROM_FEED);
}
}
|
<!DOCTYPE html>
<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">
<link rel="stylesheet" href="css/main.css">
<title>Document</title>
</head>
<body>
<main>
<button @click="mostrarExito = true">Exito</button>
<button @click="mostrarError = true">Error</button>
<button @click="mostrarAdvertencia = true">Advertencia</button>
<alerta @ocultar="mostrarExito = false" v-show="mostrarExito" tipo="alerta--exito" posicion="alerta--arriba-derecha">
<template slot="header">
Todo ok :)
</template>
<template>Este es el nuevo contenido de la alerta :)</template>
<template slot="footer">
Puedes continuar con normalidad
</template>
</alerta>
<alerta @ocultar="mostrarError = false" v-show="mostrarError" tipo="alerta--error" posicion="alerta--arriba-izquierda">
<template slot="header">
Error fatal
</template>
<template>El mundo está por imposionar</template>
<template slot="footer">
RIP
</template>
</alerta>
<alerta @ocultar="mostrarAdvertencia = false" v-show="mostrarAdvertencia" tipo="alerta--advertencia" posicion="alerta--abajo-izquierda">
<template slot="header">
Atención
</template>
<template>Este es el nuevo contenido de la alerta :)</template>
<template slot="footer">
Puedes continuar con normalidad
</template>
</alerta>
<pre>{{ $data }}</pre>
</main>
<!-- Templates -->
<template id="alertaTemplate">
<section class="alerta" :class="[tipo, posicion]">
<header class="alerta__header">
<a href="#" @click="ocultarWidget">Cerrar</a>
<slot name="header">
Hola
</slot>
</header>
<div class="alerta__contenido">
<slot>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas,
at? Fugit tempore.
</slot>
</div>
<footer class="alerta__footer">
<slot name="footer">
este es el texto del footer
</slot>
</footer>
</section>
</template>
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script> -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
|
@extends('layouts.bungadavi')
@section('body')
<div class="content container-fluid">
<!-- Page Header -->
<div class="page-header">
<div class="row">
<div class="col">
<h3 class="page-title">{{ $title ?? '' }}</h3>
<ul class="breadcrumb">
@foreach ($breadcrumb as $key => $br)
<li class="breadcrumb-item">{{ $br }}</li>
@endforeach
</ul>
</div>
</div>
</div>
<!-- /Page Header -->
@include('commons.message')
<!-- /Page Header -->
@if ($data == null)
{!! Form::open(['route' => 'bungadavi.subcategory.store', 'method' => 'POST', 'files' => true]) !!}
@else
{!! Form::model($data, ['route' => ['bungadavi.subcategory.update', ['subcategory' => $data->id]], 'method' => 'PUT','files' => true]) !!}
@endif
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-body">
<div class="form-group">
<h4 class="card-title mb-0">{{ $subtitle ?? '' }}</h4>
<hr>
</div>
<div class="form-group row pb-4">
<label class="col-form-label col-sm-12 col-md-2">Category <span class="text-danger">*</span></label>
<div class="col-sm-12 col-md-10">
{!! Form::select('category_id',$category, null,['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group row pb-4">
<label class="col-form-label col-sm-12 col-md-2">Name <span class="text-danger">*</span></label>
<div class="col-sm-12 col-md-10">
{!! Form::text('name', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group row pb-4">
<label class="col-form-label col-sm-12 col-md-2">English Name<span class="text-danger">*</span></label>
<div class="col-sm-12 col-md-10">
{!! Form::text('name_en', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group row pb-4">
<label class="col-form-label col-sm-12 col-md-2">Priority <span class="text-danger">*</span></label>
<div class="col-sm-12 col-md-10">
{!! Form::number('priority', null, ['class' => 'form-control']) !!}
</div>
</div>
@if ($data == null)
<div class="form-group row pb-4">
<label class="col-form-label col-sm-12 col-md-2">Photo <span class="text-danger">*</span></label>
<div class="col-sm-12 col-md-10">
{!! Form::file('photo', ["accept" => "image/*"]) !!}
</div>
</div>
@else
<div class="form-group row pb-4">
<label class="col-form-label col-sm-12 col-md-2">Photo <span class="text-danger">*</span></label>
<div class="col-sm-12 col-md-10">
<img src="{{ asset('storage/'.$data->photo) }}" height="200px" width="250" style="margin-bottom: 2rem">
<br>
{!! Form::file('photo', ["accept" => "image/*"]) !!}
</div>
</div>
@endif
<div class="form-group row pb-4">
<label class="col-form-label col-sm-12 col-md-2">Is Active <span class="text-danger">*</span></label>
<div class="col-sm-12 col-md-10">
{!! Form::select('is_active', array('1' => 'Yes', '0' => 'No'),null,['class' => 'form-control'] );!!}
</div>
</div>
</div>
<div class="card-footer">
<div class="form-group">
<a href="{{ route('bungadavi.subcategory.index') }}" class="btn btn-secondary">Back</a>
{!! Form::reset('Reset', ['class' => 'btn btn-danger']) !!}
{!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
</div>
</div>
</div>
</div>
</div>
{!! Form::close() !!}
</div>
@endsection
@push('js')
@endpush
|
---
title: TLS Termination / Passthrough
type: how-to
purpose: |
How to do TLS Termination and TLS Passthrough with KIC and Kong Gateway
---
## Gateway API
The Gateway API supports both [TLS termination](
https://gateway-api.sigs.k8s.io/guides/migrating-from-ingress/#tls-termination) and TLS passthrough. TLS handling is configured via a combination of a Gateway's `listeners[].tls.mode` and the attached route type:
- `Passthrough` mode listeners inspect the TLS stream hostname via server name indication and pass the TLS stream unaltered upstream. These listeners do not use certificate configuration. They only accept `TLSRoutes`.
- `Terminate` mode listeners decrypt the TLS stream and inspect the request it wraps before passing it upstream. They require certificate [Secret reference](https://gateway-api.sigs.k8s.io/reference/spec/#gateway.networking.k8s.io/v1.SecretObjectReference) in the `listeners[].tls.[]certificateRefs` field. They accept `HTTPRoutes`, `TCPRoutes`, and `GRPCRoutes`.
To terminate TLS, create a `Gateway` with a listener with `.tls.mode: "Terminate"`, create a [TLS Secret](https://kubernetes.io/docs/concepts/configuration/secret/#tls-secrets) and add it to the listener `.tls.certificateRefs` array, and then create one of the supported route types with matching criteria that will bind it to the listener.
For `HTTPRoute` or `GRPCRoute`, the route's `hostname` must match the listener hostname. For `TCPRoute` the route's `port` must match the listener `port`.
## Ingress
The Ingress API supports TLS temination using the `.spec.tls` field. To terminate TLS with the Ingress API, provide `.spec.tls.secretName` that contains a TLS certificate and a list of `.spec.tls.hosts` to match in your Ingress definition.
## Examples
### TLS Termination
{% assign gwapi_version = "v1" %}
{% if_version lte:2.12.x %}
{% assign gwapi_version = "v1beta1" %}
{% endif_version %}
{% navtabs %}
{% navtab Gateway API %}
1. Create a `Gateway` resource.
```yaml
apiVersion: gateway.networking.k8s.io/{{ gwapi_version }}
kind: Gateway
metadata:
name: example-gateway
spec:
gatewayClassName: kong
listeners:
- name: https
port: 443
protocol: HTTPS
hostname: "demo.example.com"
tls:
mode: Passthrough
```
2. Bind a `HTTPRoute` to the `Gateway`.
```yaml
apiVersion: gateway.networking.k8s.io/{{ gwapi_version }}
kind: HTTPRoute
metadata:
name: demo-example
spec:
parentRefs:
- name: kong
sectionName: https
hostnames:
- demo.example.com
rules:
- matches:
- path:
type: PathPrefix
value: /echo
backendRefs:
- name: echo
port: 1027
```
{{ site.base_gateway }} will terminate TLS traffic before sending the request upstream.
{% endnavtab %}
{% navtab Ingress %}
1. Specify a `secretName` and list of `hosts` in `.spec.tls`.
```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: demo-example-com
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
ingressClassName: kong
tls:
- secretName: demo-example-com
hosts:
- demo.example.com
rules:
- host: demo.example.com
http:
paths:
- path: /
pathType: ImplementationSpecific
backend:
service:
name: echo
port:
number: 80
```
The results will look like this:
```text
ingress.extensions/demo-example-com configured
```
{% endnavtab %}
{% endnavtabs %}
### TLS Passthrough
{% navtabs %}
{% navtab Gateway API %}
1. Create a `Gateway` resource.
```yaml
apiVersion: gateway.networking.k8s.io/{{ gwapi_version }}
kind: Gateway
metadata:
name: example-gateway
spec:
gatewayClassName: kong
listeners:
- name: https
port: 443
protocol: HTTPS
hostname: "demo.example.com"
tls:
mode: Passthrough
certificateRefs:
- kind: Secret
name: example-com
```
2. Bind a `TLSRoute` to the `Gateway`.
```yaml
apiVersion: gateway.networking.k8s.io/v1alpha2
kind: TLSRoute
metadata:
name: demo-example-passthrough
spec:
parentRefs:
- name: kong
sectionName: https
hostnames:
- demo.example.com
rules:
- backendRefs:
- name: tlsecho
port: 1989
```
You cannot use any `matches` rules on a `TLSRoute` as the TLS traffic has not been decrypted.
{{ site.base_gateway }} will **not** terminate TLS traffic before sending the request upstream.
{% endnavtab %}
{% navtab Ingress %}
{:.important}
> The Ingress API does not support TLS passthrough
{% endnavtab %}
{% endnavtabs %}
|
import { getMonth, getYear } from "date-fns";
export class SearchPanelFilter {
searchPanel = null;
constructor(searchPanel) {
this.searchPanel = searchPanel;
}
getFormData() {
const formDataSchema = {
destinations: [],
dates: [],
ports: [],
adults: 0,
children: 0,
infants: 0,
};
const formData = new FormData(this.searchPanel.searchForm);
// Get all destindation
formDataSchema.destinations = formData.getAll('destinations').slice(0);
// Get all ports
formDataSchema.ports = formData.getAll('ports').slice(0);
// Get all dates
const activeDates = this.searchPanel.searchForm.querySelectorAll('button[data-date][data-active]');
formDataSchema.adults = parseInt(document.querySelector('[data-counter][name=adult]').value);
formDataSchema.children = parseInt(document.querySelector('[data-counter][name=children]').value);
formDataSchema.infants = parseInt(document.querySelector('[data-counter][name=infants]').value);
if (activeDates.length) {
activeDates.forEach(date => {
formDataSchema.dates.push(date.getAttribute('data-date'));
})
}
return formDataSchema;
}
filterData(filterKey = null) {
const formData = this.getFormData();
const filtered = {
destinations: {},
ports: {},
dates: {}
};
let filteredDestinations = [...this.searchPanel.availableDestinations.keys()];
let filteredPorts = [...this.searchPanel.availablePorts.keys()];
let filteredDates = [...this.searchPanel.availableDates];
//
let filteredVoyages = [];
let filteredFormParams = {
destinations: new Set(),
ports: new Set(),
dates: new Set()
};
const correctDest = this.searchPanel.allVoyages.filter(({ pkg }) => {
const portCode = pkg.location.from.code;
const date = `${getYear(pkg.vacation.from)}-${getMonth(pkg.vacation.from) + 1}`;
let isCorrect = true;
if (formData.ports.length) {
isCorrect = formData.ports.includes(portCode);
}
if (formData.dates.length) {
isCorrect = formData.dates.includes(date);
}
return isCorrect;
})
const wrongDates = this.searchPanel.allVoyages.filter(({ pkg }) => {
const destinations = pkg.destinations;
const portCode = pkg.location.from.code;
let isCorrect = false;
if (formData.ports.length) {
isCorrect = !formData.ports.includes(portCode);
}
if (formData.destinations.length) {
isCorrect = !destinations.some(dest => formData.destinations.includes(dest.key));
}
return isCorrect;
})
const wrongPorts = this.searchPanel.allVoyages.filter(({ pkg }) => {
const destinations = pkg.destinations;
const date = `${getYear(pkg.vacation.from)}-${getMonth(pkg.vacation.from) + 1}`;
let isCorrect = false;
if (formData.dates.length) {
isCorrect = !formData.ports.includes(portCode);
}
if (formData.destinations.length) {
isCorrect = !formData.dates.includes(date);
}
return isCorrect;
})
filteredVoyages = this.searchPanel.allVoyages.filter(({ pkg }) => {
const destinations = pkg.destinations;
const portCode = pkg.location.from.code;
const date = `${getYear(pkg.vacation.from)}-${getMonth(pkg.vacation.from) + 1}`;
let correctDest = true;
if (formData.destinations.length) {
correctDest = destinations.some(dest => formData.destinations.includes(dest.key));
}
let correctPort = true;
if (formData.ports.length) {
correctPort = formData.ports.includes(portCode);
}
let correctDate = true;
if (formData.dates.length) {
correctDate = formData.dates.includes(date);
}
return correctDest && correctPort && correctDate;
})
filteredVoyages.forEach(({ pkg }) => {
const destinations = pkg.destinations;
const portCode = pkg.location.from.code;
const date = `${getYear(pkg.vacation.from)}-${getMonth(pkg.vacation.from) + 1}`;
destinations.forEach(dest => filteredFormParams.destinations.add(dest.key));
filteredFormParams.ports.add(portCode);
filteredFormParams.dates.add(date);
})
return {
destinations: [...filteredFormParams.destinations],
ports: [...filteredFormParams.ports],
dates: [...filteredFormParams.dates]
}
this.searchPanel.allVoyages.forEach(({ pkg }) => {
const date = `${getYear(pkg.vacation.from)}-${getMonth(pkg.vacation.from) + 1}`;
const port = pkg.location.from.code;
// Destinations
pkg.destinations.forEach(destination => {
if (!filtered.destinations[destination.key]) {
filtered.destinations[destination.key] = {};
filtered.destinations[destination.key].ports = new Set();
filtered.destinations[destination.key].dates = new Set();
}
filtered.destinations[destination.key].ports.add(port);
filtered.destinations[destination.key].dates.add(date);
})
// Ports
if (!filtered.ports[port]) {
filtered.ports[port] = {};
filtered.ports[port].destinations = new Set();
filtered.ports[port].dates = new Set();
}
pkg.destinations.forEach(destination => filtered.ports[port].destinations.add(destination.key));
filtered.ports[port].dates.add(date);
// Dates
if (!filtered.dates[date]) {
filtered.dates[date] = {};
filtered.dates[date].destinations = new Set();
filtered.dates[date].ports = new Set();
}
pkg.destinations.forEach(destination => filtered.dates[date].destinations.add(destination.key));
filtered.dates[date].ports.add(port);
})
if (formData.destinations.length) {
Object.keys(filtered.ports).forEach(key => {
if (![...filtered.ports[key].destinations].some(destination => formData.destinations.includes(destination))) {
filteredPorts = filteredPorts.filter(port => port !== key);
}
})
Object.keys(filtered.dates).forEach(key => {
if (![...filtered.dates[key].destinations].some(destination => formData.destinations.includes(destination))) {
filteredDates = filteredDates.filter(date => date !== key);
}
})
}
if (formData.ports.length) {
Object.keys(filtered.destinations).forEach(key => {
if (![...filtered.destinations[key].ports].some(port => formData.ports.includes(port))) {
filteredDestinations = filteredDestinations.filter(destination => destination !== key);
}
})
Object.keys(filtered.dates).forEach(key => {
if (![...filtered.dates[key].ports].some(port => formData.ports.includes(port))) {
filteredDates = filteredDates.filter(date => date !== key);
}
})
}
if (formData.dates.length) {
Object.keys(filtered.destinations).forEach(key => {
if (![...filtered.destinations[key].dates].some(date => formData.dates.includes(date))) {
filteredDestinations = filteredDestinations.filter(destination => destination !== key);
}
})
Object.keys(filtered.ports).forEach(key => {
if (![...filtered.ports[key].dates].some(date => formData.dates.includes(date))) {
filteredPorts = filteredPorts.filter(port => port !== key);
}
})
}
return {
destinations: filteredDestinations,
ports: filteredPorts,
dates: filteredDates
};
}
htmlChange(filterData, filterKey = null) {
const destinationsInputs = this.searchPanel.searchForm.querySelectorAll('input[name="destinations"]');
const portsInputs = this.searchPanel.searchForm.querySelectorAll('input[name="ports"]');
const monthInputs = this.searchPanel.searchForm.querySelectorAll('[data-date]');
if (destinationsInputs.length && filterKey !== 'destinations') {
destinationsInputs.forEach(destinationInput => {
const destinationVal = destinationInput.value;
const parent = destinationInput.closest('[data-search-text-parent]');
if (!filterData.destinations.includes(destinationVal)) {
destinationInput.checked = false;
if (parent) {
parent.setAttribute('data-hidden', '');
}
} else {
parent.removeAttribute('data-hidden');
}
})
}
if (portsInputs.length && filterKey !== 'ports') {
portsInputs.forEach(portInput => {
const portVal = portInput.value;
const parent = portInput.closest('[data-search-text-parent]');
if (!filterData.ports.includes(portVal)) {
portInput.checked = false;
if (parent) {
parent.setAttribute('data-hidden', '');
}
} else {
parent.removeAttribute('data-hidden');
}
})
}
if (monthInputs.length && filterKey !== 'dates') {
monthInputs.forEach(monthItem => {
const dateVal = monthItem.getAttribute('data-date');
if (!filterData.dates.includes(dateVal)) {
monthItem.removeAttribute('data-active');
monthItem.setAttribute('data-disable', '');
} else {
monthItem.removeAttribute('data-disable');
}
})
}
}
process(filterKey = null) {
const filterData = this.filterData(filterKey);
this.htmlChange(filterData, filterKey);
}
}
|
<!doctype html>
<html lang="en">
<head>
<title>Coffee Blend</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS v5.2.1 -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
<link rel="stylesheet" href="./CSS/reset.css">
<link rel="stylesheet" href="./CSS/layout.css">
<link rel="stylesheet" href="./CSS/style.css">
<link rel="stylesheet" href="./CSS/responsive.css">
</head>
<body>
<header>
<nav class="navbar navbar-expand-lg navbar-dark ">
<div class="logo">
<img class="logo-img" src="./Assets/Logo/Coffee Blend 2.png" alt="Coffee Blend" >
</div>
<div class="navbar-div">
<ul class="navbar-nav">
<li class="nav-item">
<a href="#">Home</a>
</li>
<li class="nav-item">
<a href="#">Menu</a>
</li>
<li class="nav-item">
<a href="#">Service</a>
</li>
<li class="nav-item">
<a href="#">Blog</a>
</li>
<li class="nav-item">
<a href="#">About</a>
</li>
<li class="nav-item">
<a href="#">Shop</a>
</li>
<li class="nav-item">
<a href="#">Contact</a>
</li>
<li class="nav-item">
<a href="#">Cart</a>
</li>
<li class="nav-item">
<a href="#">Account</a>
</li>
</ul>
</div>
</nav>
</header>
<main>
<div id="carouselExampleFade" class="carousel slide carousel-fade" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active " data-bs-interval="3000">
<img src="./Assets/Img/Carousel/bg-1.png" class="d-block w-100" alt="..."
style="height: 700px; object-fit: cover; background-position: center;">
<div class="overlay"></div>
<div class="content">
<div class="container">
<div class="row slider-text justify-content-center align-items-center"
data-scrollax-parent="True">
<div class="col-md-8 col-sm-12 text-center">
<span class="subheading">Welcome</span>
<h2 class="">The Best Coffee Testing Experience</h2>
<p class="">A small river named Duden flows by their place and supplies it with the
necessary
regelialia.</p>
<p><a href="#" class="btn btn-primary p-3 px-xl-4 py-xl-3">Order Now</a><a href="#"
class="btn btn-white btn-outline-white p-3 px-xl-4 py-xl-3">View Menu</a>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="carousel-item" data-bs-interval="3000">
<img src="./Assets/Img/Carousel/bg_2.png" class="d-block w-100" alt="..."
style="height: 700px; object-fit: cover; background-position: center;">
<div class="overlay"></div>
<div class="content">
<div class="container">
<div class="row slider-text justify-content-center align-items-center"
data-scrollax-parent="True">
<div class="col-md-8 col-sm-12 text-center">
<span class="subheading">Welcome</span>
<h2 class="">Amazing Taste & Beautiful Place</h2>
<p class="">A small river named Duden flows by their place and supplies it with the
necessary
regelialia.</p>
<p><a href="#" class="btn btn-primary p-3 px-xl-4 py-xl-3">Order Now</a><a href="#"
class="btn btn-white btn-outline-white p-3 px-xl-4 py-xl-3">View Menu</a>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="carousel-item" data-bs-interval="3000">
<img src="./Assets/Img/Carousel/bg_3.png" class="d-block w-100" alt="..."
style="height: 700px; object-fit: cover;background-position: center;">
<div class="overlay"></div>
<div class="container">
<div class="row slider-text justify-content-center align-items-center"
data-scrollax-parent="True">
<div class="col-md-8 col-sm-12 text-center">
<span class="subheading">Welcome</span>
<h2 class="">Creamy Hot and Ready to Serve</h2>
<p class="">A small river named Duden flows by their place and supplies it with the
necessary
regelialia.</p>
<p><a href="#" class="btn btn-primary p-3 px-xl-4 py-xl-3">Order Now</a><a href="#"
class="btn btn-white btn-outline-white p-3 px-xl-4 py-xl-3">View Menu</a>
</p>
</div>
</div>
</div>
</div>
</div>
<!-- <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleFade"
data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleFade"
data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button> -->
</main>
<footer>
<!-- place footer here -->
</footer>
<!-- Bootstrap JavaScript Libraries -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"
integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
integrity="sha384-7VPbUDkoPSGFnVtYi0QogXtr74QeVeeIs99Qfg5YCF+TidwNdjvaKZX19NZ/e6oz" crossorigin="anonymous">
</script>
<script src="./JS/app.js"></script>
</body>
</html>
|
USE `sakila`;
/* 1. Selecciona todos los nombres de las películas sin que aparezcan duplicados.*/
SELECT DISTINCT `title`
FROM `film`;
/* 2. Muestra los nombres de todas las películas que tengan una clasificación de "PG-13".*/
SELECT `title`
FROM `film`
WHERE `rating` = "PG-13";
/* 3. Encuentra el título y la descripción de todas las películas que contengan la palabra "amazing" en su descripción.*/
SELECT `title`, `description`
FROM `film`
WHERE `description`LIKE '%amazing%';
/* 4. Encuentra el título de todas las películas que tengan una duración mayor a 120 minutos.*/
SELECT `title`
FROM `film`
WHERE `length` > 120; -- La tabla film tiene el tiempo ya en minutos por lo que no hay que convertirlo ni nada.
/* 5. Recupera los nombres de todos los actores.*/
SELECT `first_name`, `last_name`
FROM `actor`;
SELECT `first_name` -- Así solo nos devolverá el nombre de los actores
FROM `actor`;
/* 6. Encuentra el nombre y apellido de los actores que tengan "Gibson" en su apellido.*/
SELECT `first_name`, `last_name`
FROM `actor`
WHERE `last_name` = 'Gibson';
SELECT `first_name`, `last_name`
FROM `actor`
WHERE `last_name` LIKE '%Gibson%';
-- He probado ambas opciones por si alguno tenía un apellido compuesto con 'Gibson'. No lo hay. Solo hay un actor con dicho apellido.
/* 7. Encuentra los nombres de los actores que tengan un actor_id entre 10 y 20.*/
SELECT `first_name`, `last_name`
FROM `actor`
WHERE `actor_id` BETWEEN 10 AND 20;
SELECT `first_name` -- Así solo nos devolvería el nombre de los actores
FROM `actor`
WHERE `actor_id` BETWEEN 10 AND 20;
/* 8. Encuentra el título de las películas en la tabla film que no sean ni "R" ni "PG-13" en cuanto a su clasificación.*/
SELECT `title`
FROM `film`
WHERE `rating` <> "PG-13" AND `rating` <> "R";
/* 9. Encuentra la cantidad total de películas en cada clasificación de la tabla film y muestra la clasificación junto con el recuento.*/
SELECT COUNT(`title`) AS `cantidad_peliculas_por_clasificacion`, `rating`
FROM `film`
GROUP BY `rating`;
/* 10. Encuentra la cantidad total de películas alquiladas por cada cliente y muestra el ID del cliente, su nombre y apellido junto con la cantidad
de películas alquiladas.
- Tabla rental: rental_id, customer_id
- Tabla customer: customer_id, first_name, last_name*/
SELECT `c`.`customer_id`, `first_name`, `last_name`, COUNT(`rental_id`) AS `numero_peliculas_alquiladas`
FROM `rental` AS `r`
INNER JOIN `customer` AS `c`
ON `c`.`customer_id` = `r`.`customer_id`
GROUP BY `r`.`customer_id`;
/* 11. Encuentra la cantidad total de películas alquiladas por categoría y muestra el nombre de la categoría junto con el recuento de alquileres.
- Tabla rental: rental_id, inventory_id
- Tabla inventory: inventory_id, film_id
- Tabla film: film_id
- Tabla film_category: film_id, category_id
- Tabla category: category_id, name*/
SELECT COUNT(`r`.`rental_id`) AS `cantidad_peliculas_categoria`, `cat`.`name`
FROM `rental` AS `r`
INNER JOIN `inventory` AS `i`
ON `r`.`inventory_id` = `i`.`inventory_id`
INNER JOIN `film` AS `f`
ON `i`.`film_id` = `f`.`film_id`
INNER JOIN `film_category` AS `fcat`
ON `f`.`film_id` = `fcat`.`film_id`
INNER JOIN `category` AS `cat`
ON `fcat`.`category_id` = `cat`.`category_id`
GROUP BY `cat`.`name`;
/* 12. Encuentra el promedio de duración de las películas para cada clasificación de la tabla film y muestra la clasificación junto con el promedio de duración.*/
SELECT AVG(`f`.`length`) AS `duración_media_peliculas_clasificacion`, `rating`
FROM `film` AS `f`
GROUP BY `rating`;
/* 13. Encuentra el nombre y apellido de los actores que aparecen en la película con title "Indian Love".
- Tabla actor: actor_id, first_name, last_name
- Tabla film_actor: actor_id, film_id
- Tabla film: film_id, title = "Indian Love"*/
SELECT `first_name`, `last_name`
FROM `actor` AS `a`
INNER JOIN `film_actor` AS `fac`
ON `a`.`actor_id` = `fac`.`actor_id`
INNER JOIN `film` AS `f`
ON `fac`.`film_id` = `f`.`film_id`
WHERE `title` = "Indian Love";
/* 14. Muestra el título de todas las películas que contengan la palabra "dog" o "cat" en su descripción.*/
SELECT `title`
FROM `film`
WHERE LOWER(`description`) LIKE '% dog %' OR LOWER(`description`) LIKE '% cat %' OR -- palabras en medio de texto
LOWER(`description`) LIKE 'dog %' OR LOWER(`description`) LIKE 'cat %' OR -- primera palabra
LOWER(`description`) LIKE '% dog' OR LOWER(`description`) LIKE '% cat'; -- última palabra
/* 15. Hay algún actor que no aparecen en ninguna película en la tabla film_actor.*/
SELECT `a`.`first_name`, `a`.`last_name`
FROM `actor` AS `a`
LEFT JOIN `film_actor` AS `fac`
ON `fac`.`actor_id` = `a`.`actor_id`
GROUP BY `a`.`actor_id`, `fac`.`actor_id`
HAVING COUNT(`fac`.`actor_id`) = 0; -- No hay ningún actor que no aparezca en ambas tablas.
/* 16. Encuentra el título de todas las películas que fueron lanzadas entre el año 2005 y 2010.*/
SELECT `title`
FROM `film`
WHERE `release_year` between 2005 and 2010;
/* 17. Encuentra el título de todas las películas que son de la misma categoría que "Family".
- Tabla film: title, film_id
- Tabla film_category: film_id, category_id
- Tabla category: category_id, name*/
SELECT `title`
FROM `film` AS `f`
INNER JOIN `film_category` AS `fcat`
ON `f`.`film_id` = `fcat`.`film_id`
INNER JOIN `category` AS `cat`
ON `fcat`.`category_id` = `cat`.`category_id`
WHERE `cat`.`name` = "Family";
/* 18. Muestra el nombre y apellido de los actores que aparecen en más de 10 películas.
- Tabla actor: actor_id, first_name, last_name
- Tabla film_actor: actor_id, COUNT film_id > 10*/
SELECT `first_name`, `last_name`
FROM `actor` AS `a`
INNER JOIN `film_actor` AS `fac`
ON `a`.`actor_id` = `fac`.`actor_id`
GROUP BY `a`.`actor_id`
HAVING COUNT(`film_id`) > 10;
/* 19. Encuentra el título de todas las películas que son "R" y tienen una duración mayor a 2 horas en la tabla film.*/
SELECT `title`
FROM `film`
WHERE `rating` = "R" AND `length` > (2*60); -- Convertimos 2 horas en minutos
/* 20. Encuentra las categorías de películas que tienen un promedio de duración superior a 120 minutos y muestra el nombre de la categoría junto con el promedio de
duración.
- Tabla film: title, film_id
- Tabla film_category: film_id, category_id
- Tabla category: category_id, name*/
SELECT `cat`.`name`, AVG(`f`.`length`)
FROM `film` AS `f`
INNER JOIN `film_category` AS `fcat`
ON `f`.`film_id` = `fcat`.`film_id`
INNER JOIN `category` AS `cat`
ON `fcat`.`category_id` = `cat`.`category_id`
GROUP BY `cat`.`name`
HAVING AVG(`f`.`length`) > 120; -- Son: Drama, Foreign, Games, Sports
/* 21. Encuentra los actores que han actuado en al menos 5 películas y muestra el nombre del actor junto con la cantidad de películas en las que han actuado.*/
SELECT `first_name`, COUNT(`film_id`) AS `numero_peliculas_del_actor` -- Yo incluiría el apellido pero para ceñirme al enunciado solo pongo el nombre
FROM `actor` AS `a`
INNER JOIN `film_actor` AS `fac`
ON `a`.`actor_id` = `fac`.`actor_id`
GROUP BY `first_name`, `last_name`
HAVING COUNT(`film_id`) > 5; -- En esta base de datos todos los actores han actuado en más de 5 películas, por lo que esta query nos los devuelve a todos.
/* 22. Encuentra el título de todas las películas que fueron alquiladas por más de 5 días.
Utiliza una subconsulta para encontrar los rental_ids con una duración superior a 5 días y luego selecciona las películas correspondientes.
- Tabla rental: rental_date, return_date, rental_id, inventory_id
- Tabla inventory: film_id, inventory_id
- Tabla film: film_id, title*/
SELECT COUNT(`rental_id`), `return_date`
FROM `rental`
GROUP BY `return_date`
HAVING `return_date` IS NULL; -- Tenemos varias filas sin valor en la fecha de devolución. Como puede ser debido a una falta de dato, no los vamos a tener en cuenta
SELECT `f`.`title`
FROM `film` AS `f`
INNER JOIN `inventory` AS `i`
ON `f`.`film_id` = `i`.`film_id`
INNER JOIN (SELECT `rental_id`, `inventory_id` -- Aquí sacamos los rental_id como nos pide el título aunque realmente no los utilizo después ya que uno por el inventory_id
FROM `rental`
WHERE DATEDIFF(`return_date`, `rental_date`) > 5) AS `alquiler_mas_de_5dias` /*Había puesto "AND DATEDIFF(return_date, rental_date) IS NOT NULL" pero me he dado cuenta de que es redundante*/
ON `alquiler_mas_de_5dias`.`inventory_id` = `i`.`inventory_id`
GROUP BY `f`.`title`;
/* 23. Encuentra el nombre y apellido de los actores que no han actuado en ninguna película de la categoría "Horror". Utiliza una subconsulta para encontrar los
actores que han actuado en películas de la categoría "Horror" y luego exclúyelos de la lista de actores.
- actor: actor_id,first_name, last_name
- film_actor: actor_id, film_id
- film: film_id
- film_category: film_id, category_id
- category: category_id, name = 'Horror'*/
SELECT `first_name`, `last_name`
FROM `actor` AS `a`
LEFT JOIN `film_actor` AS `fac`
ON `a`.`actor_id` = `fac`.`actor_id`
LEFT JOIN `film` AS `f`
ON `fac`.`film_id` = `f`.`film_id`
LEFT JOIN `film_category` AS `fcat`
ON `f`.`film_id` = `fcat`.`film_id`
LEFT JOIN `category` AS `cat`
ON `fcat`.`category_id` = `cat`.`category_id`
WHERE `a`.`actor_id` NOT IN (SELECT DISTINCT `a`.`actor_id`
FROM `actor` AS `a`
INNER JOIN `film_actor` AS `fac`
ON `a`.`actor_id` = `fac`.`actor_id`
INNER JOIN `film` AS `f`
ON `fac`.`film_id` = `f`.`film_id`
INNER JOIN `film_category` AS `fcat`
ON `f`.`film_id` = `fcat`.`film_id`
INNER JOIN `category` AS `cat`
ON `fcat`.`category_id` = `cat`.`category_id`
WHERE `cat`.`name` = 'Horror')
GROUP BY `a`.`actor_id`;
/* 24. BONUS: Encuentra el título de las películas que son comedias y tienen una duración mayor a 180 minutos en la tabla film.
- film: film_id, title
- film_category: film_id, category_id
- category: category_id, name = 'Horror'*/
SELECT `f`.`title`
FROM `film` AS `f`
INNER JOIN `film_category` AS `fcat`
ON `f`.`film_id` = `fcat`.`film_id`
INNER JOIN `category` AS `cat`
ON `fcat`.`category_id` = `cat`.`category_id`
WHERE `cat`.`category_id` = (SELECT `category_id`
FROM `category`
WHERE LOWER(`name`) = 'comedy')
AND `length` > 180;
/* 25. BONUS: Encuentra todos los actores que han actuado juntos en al menos una película. La consulta debe mostrar el nombre y apellido de
los actores y el número de películas en las que han actuado juntos.
- actor: actor_id, first_name, last_name
- film_actor: actor_id, film_id*/
SELECT CONCAT(`a1`.`first_name`, " ", `a1`.`last_name`) AS `actor1`,
CONCAT(`a2`.`first_name`, " ", `a2`.`last_name`) AS `actor2`,
COUNT(DISTINCT `fac1`.`film_id`) AS `numero_peliculas_juntos`
FROM `film_actor` AS `fac1`
INNER JOIN `actor` AS `a1`
ON `fac1`.`actor_id` = `a1`.`actor_id`
INNER JOIN `film_actor` AS `fac2`
ON `fac1`.`film_id` = `fac2`.`film_id` AND `fac1`.`actor_id` < `fac2`.`actor_id` -- Ponemos mayor para que solo se le cuente una vez a cada uno
INNER JOIN `actor` AS `a2`
ON `fac2`.`actor_id` = `a2`.`actor_id`
GROUP BY `a1`.`actor_id`, `a2`.`actor_id`
HAVING `numero_peliculas_juntos` >= 1;
|
<script setup lang="ts">
import { onMounted, ref, watch, PropType, defineEmits } from 'vue'
import { SeriesVideoDetail } from '../lib/seriesVideoDetail'
import { LogFileDataHelper } from '../lib/logFileDataHelper'
import { MaskRenderer } from '../lib/maskRenderer'
import { VideoOptions } from '../lib/videoOptions'
const props = defineProps({
videoOptions: Object as PropType<VideoOptions>,
seriesVideoDetails: Array as PropType<SeriesVideoDetail[]>,
logFileDataHelper: Object as PropType<LogFileDataHelper>,
})
const canvas = ref<HTMLCanvasElement | null>(null)
const context = ref<CanvasRenderingContext2D | null>(null)
let maskRenderer: MaskRenderer | null = null
onMounted(() => {
context.value = canvas.value!.getContext("2d")
maskRenderer = new MaskRenderer(
props.logFileDataHelper!,
props.seriesVideoDetails!,
context.value!,
props.videoOptions!
)
maskRenderer.initialize()
draw()
})
const draw = () => {
let size = maskRenderer!.calculateSize()
canvas.value!.style.width = size.width + 'px'
canvas.value!.style.height = size.height + 'px'
const scaleFactor = props.videoOptions!.resolution.scaleFactor
canvas.value!.width = size.width * scaleFactor
canvas.value!.height = size.height * scaleFactor
context.value!.scale(scaleFactor, scaleFactor)
maskRenderer?.draw()
}
const saveMask = () => {
let dt = canvas.value!.toDataURL('image/png');
let link = document.createElement("a")
link.download = "elv_mask.png";
link.href = dt
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
watch(
() => props.videoOptions,
(newValue, oldValue) => {
maskRenderer?.initialize()
draw()
},
{ deep: true }
)
watch(
() => props.seriesVideoDetails,
(newValue, oldValue) => {
maskRenderer?.initialize()
draw()
},
{ deep: true }
)
watch(
() => props.logFileDataHelper?._logFileData,
(newValue, oldValue) => {
maskRenderer?.initialize()
draw()
}
)
defineExpose({
saveMask,
})
</script>
<template>
<div>
<canvas width="300" height="300" ref="canvas" id="canvas"></canvas>
</div>
</template>
<style scoped>
</style>
|
<ui:composition template="/WEB-INF/template/layout2.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui" >
<ui:param name="title" value="Usuarios"/>
<ui:define name="content">
<section class="about" id="about">
<h:form>
<p:toolbar>
<p:toolbarGroup >
<p:commandButton value="Nuevo" action="#{usuarios.insertar()}" icon="pi pi-plus" styleClass="ui-button-success">
<p:resetInput target=""/>
</p:commandButton>
</p:toolbarGroup>
<!--<p:toolbarGroup align="right">
<p:fileUpload mode="simple" skinSimple="true" label="Import" chooseIcon="pi pi-download"/>
<p:commandButton value="Export" icon="pi pi-upload" styleClass="ui-button-help" ajax="false">
<p:dataExporter type="pdf" target="dt-products" fileName="products"/>
</p:commandButton>
</p:toolbarGroup>-->
</p:toolbar>
<br></br>
<div class="card">
<h3>Usuarios</h3>
<p:dataTable var="lis" value="#{usuarios.usuarioSel()}" reflow="true" rows="5" paginator="true">
<p:column headerText="DNI" style="text-align: center;">
<h:outputText value="#{lis.dni}"/>
</p:column>
<p:column headerText="Nombre" style="text-align: center;">
<h:outputText value="#{lis.nombre} #{lis.apellido}"/>
</p:column>
<p:column headerText="Correo" style="text-align: center;">
<h:outputText value="#{lis.correo}"/>
</p:column>
<p:column headerText="Tipo" style="text-align: center;">
<h:outputText value="#{lis.tipo}"/>
</p:column>
<p:column headerText="Nro Celular" style="text-align: center;">
<h:outputText value="#{lis.numero}"/>
</p:column>
<p:column headerText="Modificar" style="text-align: center;">
<p:commandButton icon="pi pi-pencil" action="#{usuarios.usuarioGet(lis.id)}"
styleClass="edit-button rounded-button ui-button-success" >
</p:commandButton>
</p:column>
<p:column style="text-align: center;">
<f:facet name="header" >
<h:commandButton value="Eliminar" id="delete" action="delete"
styleClass="btn-delete" onclick="usuarioDel();">
</h:commandButton>
</f:facet>
<input class="form-check-input" type="checkbox" value="${lis.id}" name="id_del"
id="flexCheckDefault" />
</p:column>
</p:dataTable>
<script src="../../resources/js/usuario.js"></script>
</div>
</h:form>
</section>
</ui:define>
</ui:composition>
|
using LGameFramework.GameBase.Culling;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
namespace LGameFramework.GameCore
{
/// <summary>
/// 轨道相机
/// </summary>
public class GMOrbitCamera : FrameworkModule
{
/// <summary>
/// 焦点
/// </summary>
[SerializeField]
private Transform m_Focus = default;
public Transform Focus
{
get
{
return m_Focus;
}
set
{
m_Focus = value;
m_FocusPoint = value.position;
}
}
/// <summary>
/// 锁定
/// </summary>
private Transform m_Lockon = null;
public Transform Lockon { get { return m_Lockon; } }
/// <summary>
/// 与焦点的距离
/// </summary>
[SerializeField]
private float m_Distance = 5f;
public float Distance { get { return m_Distance; } }
/// <summary>
/// 焦点的缓动半径
/// </summary>
[SerializeField]
private float m_FocusRadius = 1f;
/// <summary>
/// 焦点居中系数
/// </summary>
[SerializeField]
private float m_FocusCentering = 0.5f;
/// <summary>
/// 相机旋转速度
/// </summary>
[SerializeField]
private float m_RotationSpeed = 90f;
/// <summary>
/// 约束角度
/// </summary>
[SerializeField]
private float m_MinVerticalAngle = -30f, m_MaxVerticalAngle = 60f;
/// <summary>
/// 对齐平滑范围
/// </summary>
[SerializeField]
private float m_AlignSmoothRange = 45f;
/// <summary>
/// 自动对齐
/// </summary>
[SerializeField]
private float m_AlignDelay = 5f;
/// <summary>
/// 锁定时的平滑时间
/// </summary>
[SerializeField]
private float m_LockonSmooth = 300f;
/// <summary>
/// 相机遮挡检测的层级
/// </summary>
[SerializeField]
private LayerMask m_ObstructionMask;
/// <summary>
/// 最后一次收到旋转发生时间
/// </summary>
private float m_LastManualRotationTime;
/// <summary>
/// 焦点对象的现在/以前的位置
/// </summary>
private Vector3 m_FocusPoint, m_PreviousFocusPoint;
/// <summary>
/// 摄像机轨道角
/// </summary>
private Vector2 m_OrbitAngles = new Vector2(45f, 0f);
/// <summary>
/// 规则相机
/// </summary>
private Camera m_RegularCamera;
public Camera RegularCamera { get { return m_RegularCamera; } }
/// <summary>
/// 对象裁切组
/// </summary>
private ObjectCullingGroup m_ObjectCullingGroup;
public ObjectCullingGroup ObjectCullingGroup { get { return m_ObjectCullingGroup; } }
/// <summary>
/// 失活输入
/// </summary>
private bool m_DisableInput;
public bool DisableInput { get { return m_DisableInput; } set { m_DisableInput = value; } }
[SerializeField]
private bool m_InvertYAxis = true;
[SerializeField]
private bool m_InvertXAxis;
public Vector2 inputDelta;
[SerializeField]
private float m_LockonHeight;
[SerializeField]
protected float m_LockonRadius = 10f;
[SerializeField]
protected LayerMask m_LockonLayer;
public override int Priority => 999;
private PostProcessLayer m_PostProcessLayer;
private Vector3 CameraHalfExtends
{
get
{
Vector3 halfExtends;
halfExtends.y = m_RegularCamera.nearClipPlane * Mathf.Tan(0.5f * Mathf.Deg2Rad * m_RegularCamera.fieldOfView);
halfExtends.x = halfExtends.y * m_RegularCamera.aspect;
halfExtends.z = 0f;
return halfExtends;
}
}
public override void OnInit()
{
GameObject.TryAddComponent<AudioListener>();
GameObject.tag = "MainCamera";
m_RegularCamera = GameObject.TryAddComponent<Camera>();
Transform.localRotation = Quaternion.Euler(m_OrbitAngles);
var postProcess = AssetUtility.LoadAsset<PostProcessResources>("PostProcessResources.asset");
if (postProcess != null)
{
m_PostProcessLayer = GameObject.TryAddComponent<PostProcessLayer>();
m_PostProcessLayer.Init(postProcess);
m_PostProcessLayer.antialiasingMode = PostProcessLayer.Antialiasing.SubpixelMorphologicalAntialiasing;
m_PostProcessLayer.volumeLayer = 1;
m_PostProcessLayer.volumeTrigger = Transform;
}
m_DisableInput = false;
m_ObjectCullingGroup = new ObjectCullingGroup();
m_ObjectCullingGroup.TargetCamera = m_RegularCamera;
//Cursor.lockState = CursorLockMode.Locked;
}
public override void LateUpdate(float deltaTime, float unscaleDeltaTime)
{
if (m_Focus == null) return;
UpdateFocusPoint();
Quaternion lookRotation;
if (LockonRotation() || ManualRotation() || AutoMaticRotation())
{
ConstrainAngles();
lookRotation = Quaternion.Euler(m_OrbitAngles);
}
else
lookRotation = Transform.localRotation;
Vector3 lookDirection = lookRotation * Vector3.forward;
Vector3 lookPosition = m_FocusPoint - lookDirection * m_Distance;
Vector3 rectOffset = lookDirection * m_RegularCamera.nearClipPlane;
Vector3 rectPosition = lookPosition + rectOffset;
Vector3 castFrom = m_Focus.position;
Vector3 castLine = rectPosition - castFrom;
float castDistance = castLine.magnitude;
Vector3 castDirection = castLine / castDistance;
if (Physics.BoxCast(castFrom, CameraHalfExtends, castDirection,
out RaycastHit hit, lookRotation, castDistance, m_ObstructionMask))
{
rectPosition = castFrom + castDirection * hit.distance;
lookPosition = rectPosition - rectOffset;
}
Transform.SetPositionAndRotation(lookPosition, lookRotation);
}
public override void OnDestroy()
{
base.OnDestroy();
m_ObjectCullingGroup.Dispose();
}
/// <summary>
/// 更新焦点对象的位置
/// </summary>
private void UpdateFocusPoint()
{
m_PreviousFocusPoint = m_FocusPoint;
Vector3 targetPoint = m_Focus.position;
if (m_FocusRadius > 0f)
{
float distance = Vector3.Distance(targetPoint, m_FocusPoint);
float t = 1f;
if (distance > 0.01f && m_FocusCentering > 0f)
{
t = Mathf.Pow(1f - m_FocusCentering, Time.deltaTime);
}
//与上次相比 焦点的位移大于缓动半径才进行设值
if (distance > m_FocusRadius)
{
t = Mathf.Min(t, m_FocusRadius / distance);
}
m_FocusPoint = Vector3.Lerp(targetPoint, m_FocusPoint, t);
}
else
m_FocusPoint = targetPoint;
}
/// <summary>
/// 控制相机旋转
/// </summary>
private bool ManualRotation()
{
if (Lockon != null || m_DisableInput)
return false;
//输入误差
const float e = 0.001f;
if (inputDelta.x < -e || inputDelta.x > e || inputDelta.y < -e || inputDelta.y > e)
{
m_OrbitAngles += m_RotationSpeed * Time.deltaTime * inputDelta;
inputDelta = Vector2.zero;
m_LastManualRotationTime = Time.unscaledTime;
return true;
}
return false;
}
/// <summary>
/// 锁定相机旋转
/// </summary>
private bool LockonRotation()
{
if (Lockon == null)
return false;
Vector3 target = Lockon.position - m_Focus.position + Vector3.up * m_LockonHeight;
m_OrbitAngles = Quaternion.LookRotation(target).eulerAngles;
m_OrbitAngles.x = 10f;
return true;
}
/// <summary>
/// 角度限制
/// </summary>
private void ConstrainAngles()
{
m_OrbitAngles.x = Mathf.Clamp(m_OrbitAngles.x, m_MinVerticalAngle, m_MaxVerticalAngle);
if (m_OrbitAngles.y < 0f)
{
m_OrbitAngles.y += 360f;
}
else if (m_OrbitAngles.y >= 360f)
{
m_OrbitAngles.y -= 360f;
}
}
/// <summary>
/// 自动对齐
/// </summary>
/// <returns></returns>
private bool AutoMaticRotation()
{
if (Time.unscaledTime - m_LastManualRotationTime < m_AlignDelay)
{
return false;
}
Vector2 movement = new Vector2(m_FocusPoint.x - m_PreviousFocusPoint.x, m_FocusPoint.z - m_PreviousFocusPoint.z);
float movementDeltaSqr = movement.sqrMagnitude;
if (movementDeltaSqr < 0.0001f)
return false;
float headingAngle = GetAngle(movement / Mathf.Sqrt(movementDeltaSqr));
float deltaAbs = Mathf.Abs(Mathf.DeltaAngle(m_OrbitAngles.y, headingAngle));
float rotationChange = m_RotationSpeed * Mathf.Min(Time.deltaTime, movementDeltaSqr);
if (deltaAbs < m_AlignSmoothRange)
rotationChange *= deltaAbs / m_AlignSmoothRange;
else if (180f - deltaAbs < m_AlignSmoothRange)
rotationChange *= (180f - deltaAbs) / m_AlignSmoothRange;
m_OrbitAngles.y = Mathf.MoveTowardsAngle(m_OrbitAngles.y, headingAngle, rotationChange);
return true;
}
private float GetAngle(Vector2 direction)
{
float angle = Mathf.Acos(direction.y) * Mathf.Rad2Deg;
return direction.x < 0f ? 360f - angle : angle;
}
public void GetAxisInput(Vector2 input)
{
if (m_InvertYAxis)
input.y = -input.y;
if (m_InvertXAxis)
input.x = -input.x;
inputDelta.Set(input.y, input.x);
}
public void GetAxisScroll(float delta)
{
m_Distance += delta;
if (m_Distance < 2f)
m_Distance = 2f;
if (m_Distance > 8f)
m_Distance = 8f;
int id = -1;
if (id == -1) return;
}
/// <summary>
/// 检测锁定目标
/// </summary>
//public void CalculateLockon(bool value)
//{
// if (value && m_lockon == null)
// m_lockon = focus.ObtainNearestTarget(m_lockonRadius, m_lockonLayer, focus.root);
// else if (!value)
// m_lockon = null;
//}
}
}
|
import os
import traceback
import gym
import numpy as np
import sys
from src.Misc.environment_util import setup_env, setup_spaces, reset_env, step_env
from src.Misc.logger import Logger
from src.Misc.plotting import Plotter
from src.Agents.a2c_mult_ag import A2C_Multiple_Agents as A2C_Multiple_Agents
from src.Misc.memory import Memory
from src.Misc.util import to_tensor, intermediate_weight_save
import torch
from src.Misc.network import PPOActor, PPOCritic
"""
This document is based on the original main file.
Therefore, it was originally made by all who made the main file
The adaption is made by the persons stated here.
author(s): Moritz T.
"""
def main(params, params_json):
"""
Setup of the experiment from params.json. This main is adapted to work with a2c_multi_ag (for more info see
description in a2c_multi_ag)
Note: This class has nothing to do with the env mode "multi". It is designed for env mode "single" and creates
multiple agents and envs on that env mode.
author(s): Moritz T.
"""
if params.a2c_mult_ag_use_custom_master_update_frequency and params.train_mode == "max_steps":
raise Exception("Custom update frequency and max_steps do not work together! "
"Turn of custom update frequency or use train_mode 'episode'")
# setup environments for individual agents
if params.unity_env:
envs = [setup_env(params, i) for i in range(params.nr_agents)]
else:
envs = [gym.make(params.env) for _ in range(params.nr_agents)]
# setup observation and action shapes
setup_spaces(envs[0], params)
# create logging tools and directory as specified in the params
log = Logger(params, params_json)
plot = Plotter(params)
# create runners to run episodes
runners = [Runner(envs[i], log, plot, params, i) for i in range(params.nr_agents)]
# perform experiment
try:
run_experiment(params, envs, runners)
except:
for env in envs:
env.close()
traceback.print_exc()
try:
sys.exit(0)
except SystemExit:
os._exit(0)
class Runner:
"""
Runner to run episodes.
author(s): Moritz T.
"""
def __init__(self, env, log, plot, params, id=0):
self.id = id
self.params = params
self.env = env
self.state = None
self.multi_done = []
self.done = True
self.steps = 0
self.loss = 0
self.loss_critic = 0
self.loss_actor = 0
self.episode_reward = 0
self.episode_rewards = []
self.log = log
self.plot = plot
self.first_run = True
def reset(self):
"""
Resets environment.
author(s): Arnold Unterauer, Moritz T.
"""
self.episode_reward = 0
self.done = False
self.state = reset_env(self.params, self.env)
self.multi_done = np.zeros(len(self.state), dtype=int)
self.log.on_episode_start()
def run(self, agent, memory):
"""
Perform runs in the environment.
author(s): Arnold Unterauer, Moritz T.
:param agent: learning agent (a2c or ppo)
:param memory: memory, experience storage
"""
self.steps = 0
# before the very first run the environment needs to be reset
# afterwards it will be reset after done=True
if self.first_run or self.params.env_mode == "multi":
self.reset()
self.first_run = False
while self.steps < self.params.horizon or self.params.train_mode == "episode":
# perform one step
self.run_step(agent, memory)
self.steps += 1
if self.done:
self.end_episode(agent)
self.reset()
if self.params.episode >= self.params.training_episodes or \
self.params.train_mode == "episode" or self.params.train_mode == "episode_horizon":
break
if (self.params.episode >= self.params.warmup_epi and self.params.episode % self.params.update_period == 0) \
or (self.params.train_mode == "max_steps" and self.params.algorithm == "a2c_mult_ag"):
# append last next state value to memory and process episode memory
memory.memory.append((to_tensor(self.state, self.params.device), None, None, None,
to_tensor(agent.act(self.state)[2], self.params.device), None))
memory.process_memory()
# train agent
self.loss, self.loss_critic, self.loss_actor = agent.update(memory)
if self.params.env_mode == "multi" and not self.done and self.params.episode < self.params.training_episodes:
self.end_episode(agent)
def run_step(self, agent, memory):
"""
Perform one step in the environment and saves experience into memory.
author(s): Arnold Unterauer, Moritz T.
:param agent: learning agent (a2c or ppo)
:param memory: memory, experience storage
"""
if self.params.render and self.params.nr_episode % self.params.render_frequency == 0:
self.env.render()
action, log_p, value = agent.act(to_tensor(self.state))
next_state, reward, done, info, self.done, self.multi_done = step_env(self.params, self.multi_done, self.env, action)
memory.add((self.state, action, reward, log_p, value, done))
self.state = next_state
self.episode_reward += np.mean(reward)
def end_episode(self, agent):
"""
Log and plot at the end of the episode.
author(s): Moritz T.
:param agent: learning agent (a2c or ppo)
"""
if self.params.algorithm == "a2c_mult_ag":
if self.id == self.params.nr_agents - 1:
self.params.episode += 1
else:
self.params.episode += 1
self.episode_rewards.append(self.episode_reward)
self.plot.occasionally_plot(self.params.episode, self.episode_rewards)
self.log.on_episode_finish(self.episode_reward, self.loss_critic, self.loss_actor, self.loss,
agent.exploration_value, self.params.episode, self.steps, self.episode_rewards,
agent)
intermediate_weight_save(self.params, self.log.log_dir, self.params.episode, agent)
def run_experiment(params, envs, runners):
"""
Initialize agents and perform experiment.
author(s): Moritz T.
:param params: params
:param envs: environments
:param runners: Runners to perform the actual episodes
"""
# setup agent
# each agent can have own memory if desired by user
memories = [Memory(params) for _ in range(params.nr_agents)]
# alternatively all agents can use the same memory
memory = Memory(params)
# uses the A2C Network for each individual agent
actor = PPOActor(params)
critic = PPOCritic(params)
actor_optimizer = torch.optim.Adam(actor.parameters(), lr=params.actor_alpha)
critic_optimizer = torch.optim.Adam(critic.parameters(), lr=params.critic_alpha)
# create multiple a2c agents
agents = [A2C_Multiple_Agents(params, actor, critic, actor_optimizer, critic_optimizer, i) for i in
range(params.nr_agents)]
# load agent weights not supported for a2c_mult_ag yet
# if params.load_weights:
# path = os.path.join(os.getcwd(), "logs", params.weights_dir, "")
# agent.load_weights(path, params.weights_episode)
# initialize log on experiment start
for runner in runners:
runner.log.on_experiment_start()
# run episodes
while True:
for i, runner in enumerate(runners):
# check which memory mode is wished
if params.a2c_mult_ag_shared_memory:
a2c_mult_ag_memory = memory
else:
a2c_mult_ag_memory = memories[i]
#run the experiment
runner.run(agents[i], a2c_mult_ag_memory)
# After each run it is checked if the agents nets should be updated
if params.episode % params.a2c_mult_ag_master_adaption_frequency == 0 and params.episode > params.a2c_mult_ag_delayed_start_at:
# in evolution mode the net of the best agent is chosen to be the new net for all other agents
if params.evolution_mode:
best_agent = [0, 0]
for i, runner in enumerate(runners):
mean_reward = np.mean(runner.episode_rewards[-params.a2c_mult_ag_master_adaption_frequency:])
if mean_reward > best_agent[1]:
best_agent[0] = i
best_agent[1] = mean_reward
best_actor, best_critic = agents[best_agent[0]].get_net()
for agent in agents:
# adapt nets of agents
if params.evolution_mode:
agent.adapt_to_net(best_actor, best_critic)
elif params.a2c_mult_ag_use_custom_master_update_frequency:
# there is also the option to adapt the nets to a master net which
# gets updates from all the agents over time
agent.adapt_net_to_master()
if params.evolution_mode:
print(f"\nAdapted agents nets to agent {best_agent[0]} "
f"which had highest mean reward of {best_agent[1]} "
f"in the last {params.a2c_mult_ag_master_adaption_frequency} episodes")
elif params.a2c_mult_ag_use_custom_master_update_frequency:
print("Adapted agents nets to master net")
if params.episode >= params.training_episodes:
break
# closing log on experiment end
for i, runner in enumerate(runners):
runner.log.on_experiment_finish(runner.episode_rewards, agents[i])
# plot rewards for first runner only
if params.plot:
runners[0].plot.plot_experiment(params.training_episodes, runner.episode_rewards)
# shutdown environment
for env in envs:
env.close()
if __name__ == '__main__':
main()
|
import React from "react";
import { Route, Routes } from "react-router-dom";
import "./App.css";
import { GlobalStyles } from "./global.style.js";
import About from "./screens/About/About";
import CulturalEvents from "./screens/CulturalEvents/CulturalEvents";
import CulturalEventData from "./screens/EventData/CulturalEventData";
import TechnicalEventData from "./screens/EventData/TechnicalEventData";
import Home from "./screens/Home/Home";
import TechnicalEvents from "./screens/TechnicalEvents/TechnicalEvents";
function App() {
return (
<>
<GlobalStyles />
<Routes>
<Route path="/" element={<Home />} />
<Route exact path="/about" element={<About />} />
<Route exact path="/culturalEvents" element={<CulturalEvents />} />
<Route exact path="/technicalEvents" element={<TechnicalEvents />} />
<Route exact path="/culturalEvents/:type/:eventName" element={<CulturalEventData />} />
<Route exact path="/technicalEvents/:type/:eventName" element={<TechnicalEventData />} />
</Routes>
</>
);
}
export default App;
|
package com.be4tech.b4carecollect.service;
import com.be4tech.b4carecollect.domain.*; // for static metamodels
import com.be4tech.b4carecollect.domain.ActiveMinutes;
import com.be4tech.b4carecollect.repository.ActiveMinutesRepository;
import com.be4tech.b4carecollect.service.criteria.ActiveMinutesCriteria;
import java.util.List;
import javax.persistence.criteria.JoinType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.jhipster.service.QueryService;
/**
* Service for executing complex queries for {@link ActiveMinutes} entities in the database.
* The main input is a {@link ActiveMinutesCriteria} which gets converted to {@link Specification},
* in a way that all the filters must apply.
* It returns a {@link List} of {@link ActiveMinutes} or a {@link Page} of {@link ActiveMinutes} which fulfills the criteria.
*/
@Service
@Transactional(readOnly = true)
public class ActiveMinutesQueryService extends QueryService<ActiveMinutes> {
private final Logger log = LoggerFactory.getLogger(ActiveMinutesQueryService.class);
private final ActiveMinutesRepository activeMinutesRepository;
public ActiveMinutesQueryService(ActiveMinutesRepository activeMinutesRepository) {
this.activeMinutesRepository = activeMinutesRepository;
}
/**
* Return a {@link List} of {@link ActiveMinutes} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public List<ActiveMinutes> findByCriteria(ActiveMinutesCriteria criteria) {
log.debug("find by criteria : {}", criteria);
final Specification<ActiveMinutes> specification = createSpecification(criteria);
return activeMinutesRepository.findAll(specification);
}
/**
* Return a {@link Page} of {@link ActiveMinutes} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @param page The page, which should be returned.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public Page<ActiveMinutes> findByCriteria(ActiveMinutesCriteria criteria, Pageable page) {
log.debug("find by criteria : {}, page: {}", criteria, page);
final Specification<ActiveMinutes> specification = createSpecification(criteria);
return activeMinutesRepository.findAll(specification, page);
}
/**
* Return the number of matching entities in the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the number of matching entities.
*/
@Transactional(readOnly = true)
public long countByCriteria(ActiveMinutesCriteria criteria) {
log.debug("count by criteria : {}", criteria);
final Specification<ActiveMinutes> specification = createSpecification(criteria);
return activeMinutesRepository.count(specification);
}
/**
* Function to convert {@link ActiveMinutesCriteria} to a {@link Specification}
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching {@link Specification} of the entity.
*/
protected Specification<ActiveMinutes> createSpecification(ActiveMinutesCriteria criteria) {
Specification<ActiveMinutes> specification = Specification.where(null);
if (criteria != null) {
// This has to be called first, because the distinct method returns null
if (criteria.getDistinct() != null) {
specification = specification.and(distinct(criteria.getDistinct()));
}
if (criteria.getId() != null) {
specification = specification.and(buildSpecification(criteria.getId(), ActiveMinutes_.id));
}
if (criteria.getUsuarioId() != null) {
specification = specification.and(buildStringSpecification(criteria.getUsuarioId(), ActiveMinutes_.usuarioId));
}
if (criteria.getEmpresaId() != null) {
specification = specification.and(buildStringSpecification(criteria.getEmpresaId(), ActiveMinutes_.empresaId));
}
if (criteria.getCalorias() != null) {
specification = specification.and(buildRangeSpecification(criteria.getCalorias(), ActiveMinutes_.calorias));
}
if (criteria.getStartTime() != null) {
specification = specification.and(buildRangeSpecification(criteria.getStartTime(), ActiveMinutes_.startTime));
}
if (criteria.getEndTime() != null) {
specification = specification.and(buildRangeSpecification(criteria.getEndTime(), ActiveMinutes_.endTime));
}
}
return specification;
}
}
|
import '../pizzahit/botones.dart';
import '../pizzahit/temas.dart';
import '../pizzahit/utils.dart';
import '../pizzahit/widgets.dart';
import 'hawaiana.dart';
import 'menu.dart';
import 'pastor.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class MexicanaWidget extends StatefulWidget {
const MexicanaWidget({Key key}) : super(key: key);
@override
_MexicanaWidgetState createState() => _MexicanaWidgetState();
}
class _MexicanaWidgetState extends State<MexicanaWidget> {
final scaffoldKey = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
backgroundColor: Color(0xFFF1F4F8),
body: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: double.infinity,
height: 120,
decoration: BoxDecoration(
color: Color(0xACFF0000),
),
child: Stack(
children: [
Align(
alignment:
AlignmentDirectional(-0.01, -0.28),
child: Image.asset(
'assets/images/0c569e586888f719c5a826d8efdc00a6.png',
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
Align(
alignment:
AlignmentDirectional(-0.92, 0.66),
child: Card(
clipBehavior:
Clip.antiAliasWithSaveLayer,
color: Color(0x00F5F5F5),
child: botones(
borderColor: Colors.transparent,
borderRadius: 30,
borderWidth: 1,
buttonSize: 60,
icon: Icon(
Icons.arrow_back,
color: Colors.black,
size: 30,
),
onPressed: () async {
Navigator.pop(context);
},
),
),
),
Align(
alignment:
AlignmentDirectional(0.95, 0.66),
child: Card(
clipBehavior:
Clip.antiAliasWithSaveLayer,
color: Color(0x00F5F5F5),
child: botones(
borderColor: Colors.transparent,
borderRadius: 30,
borderWidth: 1,
buttonSize: 60,
icon: Icon(
Icons.local_pizza,
color: Colors.black,
size: 30,
),
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
MenuWidget(),
),
);
},
),
),
),
],
),
),
Padding(
padding: EdgeInsetsDirectional.fromSTEB(
16, 8, 16, 0),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: EdgeInsetsDirectional.fromSTEB(
0, 4, 0, 4),
child: Text(
'Mexicana',
style: temaspizza.of(context)
.title1
.override(
fontFamily: 'Outfit',
),
),
),
],
),
),
],
),
),
],
),
),
],
),
),
Container(
width: double.infinity,
height: 150,
decoration: BoxDecoration(
color: Color(0x00EEEEEE),
),
child: Stack(
children: [
Image.asset(
'assets/images/Mexicana.png',
width: 500,
height: 300,
fit: BoxFit.cover,
),
],
),
),
Container(
width: double.infinity,
height: 300,
decoration: BoxDecoration(
color: Color(0x00EEEEEE),
),
child: Stack(
children: [
Align(
alignment: AlignmentDirectional(0, 0),
child: Container(
width: double.infinity,
height: 200,
decoration: BoxDecoration(
color: Color(0x00EEEEEE),
),
child: Stack(
children: [
Align(
alignment: AlignmentDirectional(0, 0.44),
child: Wrap(
spacing: 8,
runSpacing: 8,
alignment: WrapAlignment.start,
crossAxisAlignment: WrapCrossAlignment.start,
direction: Axis.horizontal,
runAlignment: WrapAlignment.start,
verticalDirection: VerticalDirection.down,
clipBehavior: Clip.none,
children: [
InkWell(
onTap: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MexicanaWidget(),
),
);
},
child: Card(
clipBehavior: Clip.antiAliasWithSaveLayer,
color: Color(0xFFF5F5F5),
child: Image.asset(
'assets/images/Mexicana.png',
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
),
InkWell(
onTap: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HawaianaWidget(),
),
);
},
child: Card(
clipBehavior: Clip.antiAliasWithSaveLayer,
color: Color(0xFFF5F5F5),
child: Image.asset(
'assets/images/Hawaiana.png',
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
),
InkWell(
onTap: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PastorWidget(),
),
);
},
child: Card(
clipBehavior: Clip.antiAliasWithSaveLayer,
color: Color(0xFFF5F5F5),
child: Image.asset(
'assets/images/Pastor.png',
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
),
],
),
),
],
),
),
),
Stack(
children: [
Align(
alignment: AlignmentDirectional(-0.92, -0.91),
child: Text(
'Ingredientes',
style: temaspizza.of(context).title3,
),
),
Align(
alignment: AlignmentDirectional(-0.9, -0.72),
child: Text(
'Chorizo, pico de gallo, \njalapeño y tocino.',
style:
temaspizza.of(context).bodyText1.override(
fontFamily: 'Lexend Deca',
color: Colors.black,
),
),
),
Align(
alignment: AlignmentDirectional(0.79, -0.87),
child: FFButtonWidget(
onPressed: () {
print('Button pressed ...');
},
text: 'Comprar',
options: opciones(
width: 130,
height: 40,
color: Color(0xFFF9EF39),
textStyle:
temaspizza.of(context).subtitle2.override(
fontFamily: 'Lexend Deca',
color: Colors.black,
),
elevation: 5,
borderSide: BorderSide(
color: Colors.transparent,
width: 0,
),
borderRadius: 0,
),
),
),
],
),
],
),
),
],
),
),
);
}
}
|
const express = require('express');
const multer = require('multer');
const RoomModel = require('../models/room-model.js')
const router = express.Router();
const myUploader = multer(
// 1 argument -> a settings object
{
dest: __dirname + '/../public/uploads/'
} //
// destination (where to put uploaded files)
);
router.get('/rooms/new', (req, res, next) => {
// redirect to the log in page if NOT logged in
if (req.user === undefined) {
req.flash('securityError', 'Log in to add a room.');
res.redirect('/login');
return;
}
res.render('room-views/room-form.ejs');
});
//<form method="post" action="/rooms">
router.post(
'/rooms',
myUploader.single('roomPhoto'),
// |
// <input name="roomPhoto" type="file">
(req, res, next) => {
if (req.user === undefined) {
req.flash('securityError', 'Log in to add a room.');
res.redirect('/login');
return;
}
// muler creates "req.file" with all the uploaded file information
console.log( 'req.file (created by multer) ------------- ');
console.log( req.file );
const theRoom = new RoomModel({
name: req.body.roomName,
photoUrl: '/uploads/' + req.file.filename,
//'req.file.filename' is automatically
// generated name for the uploaded file
desc: req.body.roomDesc,
owner: req.user._id
}); //
// Logged in user's ID from passport
//(passport defines "req.user")
theRoom.save((err) => {
if (err) {
next(err);
return;
}
req.flash('roomFeedback', 'Room added');
res.redirect('/');
});
}); // close ///rooms
router.get('/my-rooms', (req, res, next) => {
if (req.user === undefined) {
req.flash('securityError', 'Log in to add a room.');
res.redirect('/login');
return;
}
// find all the ROOMS whose owner is the logged in user
RoomModel.find(
{ owner: req.user._id },
(err, myRooms) => {
if (err) {
next(err);
return;
}
res.locals.securityFeedback = req.flash('securityError');
res.locals.updateFeedback = req.flash('updateSuccess');
res.locals.listOfRooms = myRooms;
res.render('room-views/user-rooms.ejs');
}
);
}); // close GET /my-rooms
router.get('/rooms/:roomId/edit', (req, res, next) => {
if (req.user === undefined) {
req.flash('securityError', 'Log in to edit your rooms.');
res.redirect('/login');
return;
}
RoomModel.findById(
req.params.roomId,
(err, roomFromDb) => {
if(err) {
next(err);
return;
}
//redirect if you don't own this room
console.log(req.user);
if (roomFromDb.owner.toString() !== req.user._id.toString()) {
req.flash('securityError', 'You can only eit your rooms.');
res.redirect('/my-rooms');
return;
}
res.locals.roomInfo = roomFromDb;
res.render('room-views/room-edit.ejs');
}
); //close RoomModel.findById( ...)
}); // close GET /rooms/:roomId/edit
router.post('/rooms/:roomId',
myUploader.single('roomPhoto'),
// if (req.user === undefined) {
// req.flash('securityError', 'Log in to add a room.');
// res.redirect('/login');
// return;
// }
(req, res, next) => {
RoomModel.findById(
req.params.roomId,
(err, roomFromDb) => {
if (err) {
next(err);
return;
}
if (roomFromDb.owner.toString() !== req.user._id.toString()) {
req.flash('securityError', 'You can only eit your rooms.');
res.redirect('/my-rooms');
return;
}
// "req.file" will be undefined if the user doesn't upload anythig
// update "photoUrl" only if the user
roomFromDb.name = req.body.roomName;
roomFromDb.desc = req.body.roomDesc;
if (req.file) {
roomFromDb.photoUrl = '/uploads/' + req.file.filename;
}
roomFromDb.save((err) => {
if(err) {
next(err);
return;
}
req.flash('updateSuccess', 'Room update Succesful.');
res.redirect('/my-rooms');
}); // close roomFromDb.save((err)...)
}
); // close RoomModel.findById
}); // close POST /rooms/:roomId
module.exports = router;
|
import React, { useEffect, useRef } from 'react';
import classes from './Cockpit.css';
import AuthContext from '../../context/auth-context';
const cockpit = (props) => {
const toggleBtnRef = useRef(null);
useEffect(() => {
console.log('[useEffect] cockpit.js');
// setTimeout(() => {
// alert("Saved Output");
// }, 1000);
toggleBtnRef.current.click();
return () => {
console.log('[Cockpit.js] cleanup work in useEffect');
}
}, []);
useEffect(() => {
console.log('[]');
})
const assignedClasses = [];
let btnClass = '';
if (
props.showPerson) {
btnClass = classes.Red;
}
if (
props.personsLength <= 2) {
assignedClasses.push(classes.red);
}
if (
props.personsLength <= 1) {
assignedClasses.push(classes.bold);
}
return (
<div className={classes.Cockpit}>
<h1>{
props.title}</h1>
<p className={assignedClasses.join(' ')}>This is really working!</p>
<button
ref={toggleBtnRef}
className={btnClass}
onClick={
props.clicked}>Some Event</button>
<AuthContext.Consumer>
{context => <button onClick={context.login}>Log In</button>}
</AuthContext.Consumer>
</div>
);
}
export default React.memo(cockpit);
|
# Проект 0. Угадай число
## Оглавление
[1. Описание проекта](.README.md#Описание-проекта)
[2. Какой кейс решаем?](.README.md#Какой-кейс-решаем)
[3. Краткая информация о данных](.README.md#Краткая-информация-о-данных)
[4. Этапы работы над проектом](.README.md#Этапы-работы-над-проектом)
[5. Результат](.README.md#Результат)
[6. Выводы](.README.md#Выводы)
### Описание проекта
Угадать загаданное компьютером число за минимальное число попыток.
:arrow_up:[к оглавлению](_)
### Какой кейс решаем?
Нужно написать программу, которая угадывает число за минимальное количество попыток
**Условия соревнования:**
- Компьютер загадывает целое число от 0 до 100, и нам его нужно угадать. Под «угадать», подразумевается «написать программу, которая угадывает число».
- Алгоритм учитывает информацию о том, больше ли случайное число или меньше нужного нам.
**Метрика качества**
Результаты оцениваются по среднему количеству попыток при 1000 повторений
**Что практикуем**
Учимся писать хороший код на python
### Краткая информация о данных
Исходный список чисел получается при помощи функцию ```np.random.randint(1, 101, size=(10000))```
:arrow_up:[к оглавлению](.README.md#Оглавление)
### Этапы работы над проектом
- Сначала написал функцию, которая пытается только при помощи перебора рандомных чисел из заданного диапазона угадать искомое число.
- Затем написал функцию, которая проверяет, больше или меньше рандомное число, чем искомое, в зависимости от этого сдвигает границы диапазона для получения рандомного числа
- После был применен метод бинарного поиска без использования случайных чисел
:arrow_up:[к оглавлению](.README.md#Оглавление)
### Результаты:
В результате удалось достичь точности угадывания в среднем за 9 попыток за 1000 повторений.
Бинарный поиск без использования случайных чисел в данной задаче дает результат в среднем в 5 попыток за 1000 повторений
:arrow_up:[к оглавлению](.README.md#Оглавление)
### Выводы:
Поставленная задача была выполнена, среднее количество попыток меньше 20.
Условия соревнования соблюдены.
:arrow_up:[к оглавлению](.README.md#Оглавление)
Если информация по этому проекту покажется вам интересной или полезной, то я буду очень вам благодарен, если отметите репозиторий и профиль ⭐️⭐️⭐️-дами
|
// Book objects to be stored in an array
const myLibrary = [];
function Book(title, author, nPages, readStatus="not read yet"){
this.title = title;
this.author = author
this.nPages = nPages;
this.readStatus = readStatus
this.info = function(){
return `${title} by ${author}, ${nPages} pages, ${readStatus}`;
}
this.changeStatus = function(status){
this.readStatus = status;
}
}
function addBookToLibrary(Book){
myLibrary.push(Book);
};
const theHobbit = new Book("The Hobbit", "J.R.R Tolkien", 295)
const fellowship = new Book("The Fellowship of the Ring", "J.R.R Tolkien", 215)
const twoTowers = new Book("The Two Towers", "J.R.R Tolkien", 125)
const returnOfKing = new Book("Return of the King", "J.R.R Tolkien", 495)
addBookToLibrary(theHobbit);
addBookToLibrary(fellowship);
addBookToLibrary(twoTowers);
addBookToLibrary(returnOfKing);
returnOfKing.changeStatus('now');
// returnOfKing.readStatus = "read"
for (let i = 0 ; i<myLibrary.length; i++){
// console.log(myLibrary[i].readStatus);
console.log(myLibrary[i].title);
}
|
package study17;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
public class FileClassRun {
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\kosmo\\eclipse-workspace\\javastudy\\src\\study17\\files";
File dir = new File(path);
if(!dir.exists()) { //파일이 존재하는지 확인하는 기능 .exists
dir.mkdir();
}
System.out.println(dir.exists());
File file = new File(path+"\\TestFile.txt");
if(!file.exists()) {
file.createNewFile();
}
System.out.println(file.exists());
File file2 = new File("C:\\Users\\kosmo\\eclipse-workspace\\javastudy\\src\\study17\\files\\TestFile.txt");
File file3 = new File("C:/Users/kosmo/eclipse-workspace/javastudy/src/study17/files/TestFile.txt");
File file4 = new File("C:" + File.separator + "Users" + File.separator + "kosmo" + File.separator + "eclipse-workspace"
+ File.separator + "javastudy" + File.separator + "src" + File.separator + "study17" + File.separator + "files"
+ File.separator + "TestFile.txt");
System.out.println(file2.exists() + " " + file2.getAbsolutePath());
System.out.println(file3.exists() + " " + file3.getAbsolutePath());
System.out.println(file4.exists() + " " + file4.getAbsolutePath());
System.out.println("user.dir");
File file5 = new File("src/study17/files/TestFile.txt");
File file6 = new File("src/study17/files/temp/TestFile.txt");
System.out.println(file5.exists() + " " + file5.getAbsolutePath());
System.out.println(file6.exists() + " " + file6.getAbsolutePath());
System.out.println(dir.getName() + " " + dir.isDirectory() + " " + dir.getParent()); //getName = 파일 이름 isDirectory 폴더인지 확인 getParent 위치
System.out.println(file.getName() + " " + file.isFile() + " " + file.getParent()); //getName = 파일 이름 isFile 파일인지 확인 getParent 위치
File dir2 = new File(path + "\\temp");
System.out.println(dir2.mkdir());
File[] files = dir.listFiles();
for(File file7 : files) {
System.out.println(file7.getName() + " " + (file7.isFile()?">파일 : ":"디렉토리"));
}
Charset cs = Charset.forName("UTF-8");
Charset cs2 = Charset.defaultCharset();
System.out.println(cs2);
System.out.println(Charset.isSupported("EUC-KR"));
byte[] arr1 = "재승".getBytes();
byte[] arr2 = "현명".getBytes(Charset.defaultCharset());
byte[] arr3 = "종호".getBytes(Charset.forName("MS949"));
byte[] arr4 = "만수".getBytes("UTF-8");
System.out.println(arr1.length);
System.out.println(arr2.length);
System.out.println(arr3.length);
System.out.println(arr4.length);
String str1 = new String(arr1);
String str2 = new String(arr2,Charset.defaultCharset());
String str3 = new String(arr3,Charset.forName("MS949"));
String str4 = new String(arr4,"UTF-8");
String str5 = new String(arr3,"UTF-8");
String str6 = new String(arr4,Charset.forName("MS949"));
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
System.out.println(str6);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.alanayala.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author programacion
*/
@Entity
@Table(name = "detallefactura")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Detallefactura.findAll", query = "SELECT d FROM Detallefactura d")
, @NamedQuery(name = "Detallefactura.findByIddetallefactura", query = "SELECT d FROM Detallefactura d WHERE d.iddetallefactura = :iddetallefactura")
, @NamedQuery(name = "Detallefactura.findByPlato", query = "SELECT d FROM Detallefactura d WHERE d.plato = :plato")
, @NamedQuery(name = "Detallefactura.findByPrecio", query = "SELECT d FROM Detallefactura d WHERE d.precio = :precio")
, @NamedQuery(name = "Detallefactura.findByCantidad", query = "SELECT d FROM Detallefactura d WHERE d.cantidad = :cantidad")
, @NamedQuery(name = "Detallefactura.findByTotalventa", query = "SELECT d FROM Detallefactura d WHERE d.totalventa = :totalventa")})
public class Detallefactura implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "iddetallefactura")
private Integer iddetallefactura;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 45)
@Column(name = "plato")
private String plato;
@Basic(optional = false)
@NotNull
@Column(name = "precio")
private double precio;
@Basic(optional = false)
@NotNull
@Column(name = "cantidad")
private int cantidad;
@Basic(optional = false)
@NotNull
@Column(name = "totalventa")
private double totalventa;
@JoinColumn(name = "idcocinero", referencedColumnName = "idcocinero")
@ManyToOne(optional = false)
private Cocinero idcocinero;
@JoinColumn(name = "idfactura", referencedColumnName = "idfactura")
@ManyToOne(optional = false)
private Factura idfactura;
public Detallefactura() {
}
public Detallefactura(Integer iddetallefactura) {
this.iddetallefactura = iddetallefactura;
}
public Detallefactura(Integer iddetallefactura, String plato, double precio, int cantidad, double totalventa) {
this.iddetallefactura = iddetallefactura;
this.plato = plato;
this.precio = precio;
this.cantidad = cantidad;
this.totalventa = totalventa;
}
public Integer getIddetallefactura() {
return iddetallefactura;
}
public void setIddetallefactura(Integer iddetallefactura) {
this.iddetallefactura = iddetallefactura;
}
public String getPlato() {
return plato;
}
public void setPlato(String plato) {
this.plato = plato;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public double getTotalventa() {
return totalventa;
}
public void setTotalventa(double totalventa) {
this.totalventa = totalventa;
}
public Cocinero getIdcocinero() {
return idcocinero;
}
public void setIdcocinero(Cocinero idcocinero) {
this.idcocinero = idcocinero;
}
public Factura getIdfactura() {
return idfactura;
}
public void setIdfactura(Factura idfactura) {
this.idfactura = idfactura;
}
@Override
public int hashCode() {
int hash = 0;
hash += (iddetallefactura != null ? iddetallefactura.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Detallefactura)) {
return false;
}
Detallefactura other = (Detallefactura) object;
if ((this.iddetallefactura == null && other.iddetallefactura != null) || (this.iddetallefactura != null && !this.iddetallefactura.equals(other.iddetallefactura))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.alanayala.entities.Detallefactura[ iddetallefactura=" + iddetallefactura + " ]";
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="shortcut icon" href="../images/bank-banking-finance-icon_112235.ico" type="image/x-icon">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
<link rel="stylesheet" href="../styles/accountsPrueba.css" />
<title>Accounts Page || MindHub Brothers</title>
</head>
<body>
<div id="app" v-cloak>
<header>
<a class="navbar-brand" href="#"><img src="../images/bank.png" alt="Logo" class="logo p-2"></a>
<nav class="navbar navbar-expand-lg text-center">
<div class="container-fluid d-flex gap-5 justify-content-center">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse " id="navbarNav">
<ul class="navbar-nav d-flex gap-5">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Accounts</a>
</li>
<li class="nav-item">
<a class="nav-link" href="./cards.html">Cards</a>
</li>
<li class="nav-item">
<a class="nav-link" href="./loan-aplication.html">Loans</a>
</li>
<li class="nav-item">
<a class="nav-link" href="./transfer.html">Transactions</a>
</li> <li class="nav-item">
<a class="nav-link" href="#">{{clients.firstName}} {{clients.lastName}}</a>
</li>
</ul>
</div>
</div>
</nav>
<button class="Btn" @click.prevent="logOut">
<div class="sign"><svg viewBox="0 0 512 512"><path d="M377.9 105.9L500.7 228.7c7.2 7.2 11.3 17.1 11.3 27.3s-4.1 20.1-11.3 27.3L377.9 406.1c-6.4 6.4-15 9.9-24 9.9c-18.7 0-33.9-15.2-33.9-33.9l0-62.1-128 0c-17.7 0-32-14.3-32-32l0-64c0-17.7 14.3-32 32-32l128 0 0-62.1c0-18.7 15.2-33.9 33.9-33.9c9 0 17.6 3.6 24 9.9zM160 96L96 96c-17.7 0-32 14.3-32 32l0 256c0 17.7 14.3 32 32 32l64 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-64 0c-53 0-96-43-96-96L0 128C0 75 43 32 96 32l64 0c17.7 0 32 14.3 32 32s-14.3 32-32 32z"></path></svg></div>
<div class="text">Logout</div>
</button>
</header>
<main>
<h1 class="text-center">Accounts Resume</h1>
<div class="grid">
<template v-if="accounts.length > 0" v-for="(account,index) of accounts">
<div id="card">
<div id="content">
<p id="heading">Account Number: <span>{{account.number}}</span></p>
<p id="para">Creation Date: <span>{{account.creationDate}}</span></p>
<p id="para"> Balance: <span>${{account.balance.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}</span></p>
<p id="para">Type: <span>{{account.type}}</span></p>
<a :href="'./account.html?id=' + account.id" class="btn">More Details</a>
</div>
</div>
</template>
<article v-if="accounts.length < 3" class="d-flex flex-column align-items-center">
<h3 class="text-center text-white fs-5">Do you want to add accounts?</h3>
<button type="button" @click.prevent="showOption" class="btn gg">ADD ACCOUNTS</button>
<div class="" v-if="show">
<div class="d-flex gap-2">
<label class="d-flex gap-1"><input type="radio" name="Saving" id="Savings" value="SAVINGS" v-model="type">Saving</label>
<label class="d-flex gap-1"><input type="radio" name="Saving" id="Savings" value="CURRENT" v-model="type">Current</label>
</div>
<button class="btn gg " @click.prevent="createAccount">Create Account</button>
</div>
</article>
</div>
<section class="d-flex flex-column">
<h2>Loans Resume</h2>
<template v-if="loans.length>0" >
<table id="table">
<thead>
<tr class="">
<th>Name</th>
<th>Amount</th>
<th>Payments</th>
</tr>
</thead>
<tbody>
<template v-for="(loan,index) of loans">
<tr class="">
<td>{{loan.loan}}</td>
<td>{{loan.amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ".").replace(".",",")}}</td>
<td>{{loan.payments}}</td>
</tr>
</template>
</tbody>
</template>
</table>
<p v-else>No Loans</p></p>
</section>
</main>
<footer class="footer d-flex align-items-center justify-content-around fs-2 ">
<div class="d-flex align-items-center justify-content-center gap-3">
<i class="bi bi-bank2 fs-5 text-white"></i>
<span class="text-white fs-5"> Mind Hub Brothers © </span>
</div>
<div class="d-flex gap-5 flex-wrap ">
<a href="tel:+3743614796" class="d-flex gap-2 text-white fs-5"><i
class="bi bi-telephone-inbound-fill "></i>Call</a>
<a href="mailto:[email protected]" class="d-flex gap-2 text-white fs-5"><i
class="bi bi-envelope-at"></i>Email</a>
</div>
</footer>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.all.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script type="module" src="../scripts/accounts.js"></script>
</html>
|
import { usersRepository } from "../data-access/repositories/user-repository"
import { groupRepository } from "../data-access/repositories/group-repository"
import usersMock from "./user-mocks.json"
import groupsMock from "./group-mocks.json"
import * as http from 'http'
import request, { SuperTest } from "supertest"
import express, { Application } from "express"
import server from "../index"
import { getValidGroup, getValidUser, validToken } from "./mock"
const port: number | string = process.env.PORT_TESTING || 5000
const appMock: Application = express();
const users = [...usersMock]
const groups = [...groupsMock]
jest.mock("../data-access/repositories/user-repository")
jest.mock("../data-access/repositories/group-repository")
describe("User routes", () => {
let agent: SuperTest<any>
let srv: http.Server
const seedUserData = getValidUser()
let seedUser: any
beforeEach((done) => {
srv = server.listen(4000, () => {
agent = request(server)
});
usersRepository.addUser(seedUserData).then((user) => {
seedUser = user
done()
})
})
afterEach((done) => {
srv && srv.close(done)
})
it("GET: /user - return all existed users correctly", async () => {
const existedUsersAmount = users.filter((user) => !user.isDeleted).length;
const res = await request(appMock)
.get("/user")
expect(res.body).toBe(existedUsersAmount);
});
it("GET: /user/:id - return correct user by id", async () => {
const id = "338883ee-19d6-40b4-9766-32b4f726d2aa";
const res = await request(srv)
.get(`/user/${id}`)
.set("Authorization", validToken);
expect(res.status).toBe(200);
expect(res.body.id).toEqual(id);
})
it("POST: /user - create user correctly", async () => {
const usersAmount = users.length;
const res = await request(srv)
.post("/user")
.send({ login: "TestUser", password: "testPassw0rd", age: 40 })
.set("Authorization", validToken)
expect(res.status).toBe(201);
expect(res.body.login).toEqual("TestUser");
expect(res.body).toHaveProperty("id");
expect(users.length).toEqual(usersAmount + 1);
})
it("POST: /user - handle bad request correctly", async () => {
const usersAmount = users.length;
const res = await request(srv)
.post("/user")
.send({ name: "TestUser", age: 40 })
.set("Authorization", validToken)
expect(res.status).toBe(400);
expect(users.length).toEqual(usersAmount);
})
it("PUT: /user/:id - update user correctly", async () => {
const id = "338883ee-19d6-40b4-9766-32b4f726d2aa";
const res = await request(srv)
.put(`/user/${id}`)
.send({ login: "Four", password: "password4", age: 44 })
.set("Authorization", validToken)
expect(res.status).toBe(200);
expect(res.body.age).toEqual(44);
})
it("DELETE: /user/:id - delete user correctly", async () => {
const id = "338883ee-19d6-40b4-9766-32b4f726d2aa";
const res = await request(srv)
.delete(`/user/${id}`)
.set("Authorization", validToken)
expect(res.status).toBe(200);
expect(res.text).toEqual("Deleted");
})
})
describe("Group routes", () => {
let agent: SuperTest<any>;
let srv: http.Server;
const seedGroupData = getValidGroup();
let seedGroup: any;
beforeEach((done) => {
srv = server.listen(4000, () => {
agent = request(server);
});
groupRepository.createGroup(seedGroupData).then((group) => {
seedGroup = group;
done();
});
});
afterEach((done) => {
srv && srv.close(done);
});
it("GET: /group - return groups correctly", async () => {
const groupsAmount = groups.length;
const res = await request(srv)
.get("/group")
.set("Authorization", validToken);
expect(res.status).toBe(200);
expect(res.body.length).toBe(groupsAmount);
});
it("GET: /group/:id - return correct group by id", async () => {
const id = "7f50b154-963a-452d-b857-1605013aab5f";
const res = await request(srv)
.get(`/group/${id}`)
.set("Authorization", validToken);
expect(res.status).toBe(200);
expect(res.body.id).toEqual(id);
});
it("GET: /group/:id - not return non-existed group", async () => {
const notExistedGroupId = "0ee75a1c-8fee-4e52-a44c-a234a3ffa93d";
const res = await request(srv)
.get(`/user/${notExistedGroupId}`)
.set("Authorization", validToken);
expect(res.status).toBe(404);
expect(res.text).toEqual("Not Found");
});
it("POST: /group - create group correctly", async () => {
const groupsAmount = groups.length;
const res = await request(srv)
.post("/group")
.send({ name: "TestGroup", permissions: ["READ"] })
.set("Authorization", validToken)
expect(res.status).toBe(201);
expect(res.body.name).toEqual("TestGroup");
expect(res.body).toHaveProperty("id");
expect(groups.length).toEqual(groupsAmount + 1);
});
it("POST: /group - handle bad request correctly", async () => {
const groupsAmount = groups.length;
const res = await request(srv)
.post("/group")
.send({ name: "TestGroup", permissions: ["INCORRECT_VALUE"] })
.set("Authorization", validToken)
expect(res.status).toBe(400);
expect(groups.length).toEqual(groupsAmount);
});
it("PUT: /group/:id - update group correctly", async () => {
const id = "e7fe5cff-0de8-4f26-92f6-1c32fd6c25d7";
const res = await request(srv)
.put(`/group/${id}`)
.send({ name: "EditedGroup", permissions: ["READ", "WRITE", "DELETE"] })
.set("Authorization", validToken)
expect(res.status).toBe(200);
expect(res.body.name).toEqual("EditedGroup");
});
it("DELETE: /group/:id - delete group correctly", async () => {
const groupsAmount = groups.length;
const id = "e7fe5cff-0de8-4f26-92f6-1c32fd6c25d7";
const res = await request(srv)
.delete(`/group/${id}`)
.set("Authorization", validToken)
expect(res.status).toBe(200);
expect(res.text).toEqual("Deleted");
expect(groups.length).toEqual(groupsAmount - 1);
});
});
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
import { Student } from './student';
import { Observable, of } from 'rxjs';
import { LogService } from './log.service';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class StudentService {
private studentsUrl = 'api/students';
constructor(
private logService: LogService,
private http: HttpClient) { }
private log(message: string) {
this.logService.add(`StudentService: ${message}`);
}
getStudents(): Observable<Student[]> {
return this.http.get<Student[]>(this.studentsUrl)
.pipe(
tap(_ => this.log('fetched students')),
catchError(this.handleError<Student[]>('getStudents', []))
);
}
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
getStudent(id: number): Observable<Student> {
const url = `${this.studentsUrl}/${id}`;
return this.http.get<Student>(url).pipe(
tap(_ => this.log(`fetched student id=${id}`)),
catchError(this.handleError<Student>(`get Student id=${id}`))
);
}
updateStudent (student: Student): Observable<any> {
return this.http.put(this.studentsUrl, student, httpOptions).pipe(
tap(_ => this.log(`updated student id=${student.id}`)),
catchError(this.handleError<any>('updateStudent'))
);
}
addStudent (student: Student): Observable<Student> {
return this.http.post<Student>(this.studentsUrl, student, httpOptions).pipe(
tap((s: Student) => this.log(`added student id=${s.id}`)),
catchError(this.handleError<Student>('addStudent'))
);
}
deleteStudent (student: Student): Observable<Student> {
const url = `${this.studentsUrl}/${student.id}`;
return this.http.delete<Student>(url, httpOptions).pipe(
tap(_ => this.log(`deleted student id=${student.id}`)),
catchError(this.handleError<Student>('deleteStudent'))
);
}
searchStudents(term: string): Observable<Student[]> {
if (!term.trim()) {
// if not search term, return empty student array.
return of([]);
}
return this.http.get<Student[]>(`${this.studentsUrl}/?name=${term}`).pipe(
tap(_ => this.log(`found students matching "${term}"`)),
catchError(this.handleError<Student[]>('searchStudents', []))
);
}
}
|
from abc import ABC, abstractclassmethod
import cv2
from datetime import datetime
from factories.AlertFactory import AlertDict, AlertEnum
from PyQt5.QtCore import pyqtSignal
import multiprocessing as mp
import queue
import yaml
from cameraFunc import YoloCamera, CombinedCamera, TestCamera
with open('config.yml', 'r') as stream:
config = yaml.load(stream, Loader=yaml.FullLoader)
class ICameraProcess(ABC):
@abstractclassmethod
def runCamera(self):
return NotImplemented
@abstractclassmethod
def setRecorder(self):
return NotImplemented
@abstractclassmethod
def recordFrame(self):
return NotImplemented
@abstractclassmethod
def getFrame(self):
return NotImplemented
@abstractclassmethod
def endCamera(self):
return NotImplemented
class BasicCameraProccess(ICameraProcess):
def __init__(
self, camera_id: str, ImageSignal: pyqtSignal, AlertSignal: pyqtSignal, StatusSignal: pyqtSignal) -> None:
super().__init__()
self.camera = object
self.ImageSignal = ImageSignal
self.AlertSignal = AlertSignal
self.StatusSignal = StatusSignal
self.camera_id = camera_id
self.video_index = 0
self.command = mp.Value('i', 0)
self.status = mp.Value('i', 0)
self.alert = mp.Value('i', 99)
self.queue = mp.Queue(4)
def runCamera(self):
self.proccess = mp.Process(target=self.camera, args=(
self.queue, self.command, self.alert, self.camera_id, self.status,))
self.command.value = 1
self.proccess.start()
self.setRecorder()
def setRecorder(self):
self.t1 = datetime.now()
self.t2 = self.t1
fileName = f"videos/cam_{self.camera_id}_{self.video_index}.avi"
video_code = cv2.VideoWriter_fourcc(*'XVID')
frameRate = 20
resolution = (config["MainImage_Width"], config["MainImage_Height"])
self.videoOutput = cv2.VideoWriter(fileName, video_code, frameRate, resolution)
def recordFrame(self, frame):
self.videoOutput.write(frame)
self.t2 = datetime.now()
if (self.t2 - self.t1).seconds >= int(config["Record_Seconds"]):
self.videoOutput.release()
self.video_index += 1
# 每30分鐘洗白重來
self.video_index = self.video_index % int(config["Record_Total"])
self.setRecorder()
def getStatus(self):
self.StatusSignal.emit(self.status.value)
def getFrame(self):
try:
frame = self.queue.get_nowait()
self.recordFrame(frame)
self.ImageSignal.emit(frame)
return frame
except queue.Empty or queue.Full:
pass
def getAlert(self):
if self.alert.value == int(AlertEnum.NoAlert):
return
self.AlertSignal.emit(AlertEnum(self.alert.value))
self.alert.value = int(AlertEnum.NoAlert)
def endCamera(self):
self.command.value = 0
self.videoOutput.release()
self.StatusSignal.emit(0)
# while not self.queue.empty:
# self.queue.get_nowait()
# print("cleaning")
# self.queue.close()
# print("closed")
self.proccess.terminate()
class TestCameraProcess(BasicCameraProccess):
def __init__(
self, camera_id: str, ImageSignal: pyqtSignal, AlertSignal: pyqtSignal, StatusSignal: pyqtSignal) -> None:
super().__init__(camera_id, ImageSignal, AlertSignal, StatusSignal)
self.camera = TestCamera.runCamera
def setRecorder(self):
self.t1 = datetime.now()
self.t2 = self.t1
fileName = f"videos/cam_{self.camera_id}_{self.video_index}.avi"
video_code = cv2.VideoWriter_fourcc(*'XVID')
frameRate = 20
resolution = (640, 480) # 解析度不同
self.videoOutput = cv2.VideoWriter(fileName, video_code, frameRate, resolution)
class CombinedCameraProcess(BasicCameraProccess):
def __init__(
self, camera_id: str, ImageSignal: pyqtSignal, AlertSignal: pyqtSignal, StatusSignal: pyqtSignal) -> None:
super().__init__(camera_id, ImageSignal, AlertSignal, StatusSignal)
self.camera = CombinedCamera.runCamera
class YoloCameraProcess(BasicCameraProccess):
def __init__(
self, camera_id: str, ImageSignal: pyqtSignal, AlertSignal: pyqtSignal, StatusSignal: pyqtSignal) -> None:
super().__init__(camera_id, ImageSignal, AlertSignal, StatusSignal)
self.camera = YoloCamera.runCamera
|
## topological sorting
Key points:
this is a general appraoch to solve DAG problems, we can use both BFS and DFS to solve it
### BFS (Kahn's algorithm)
1. initialize a list to represents the indegree of each node
2. preserve a queue to store the nodes with 0 indegree, in python we can simply use a list to simulate a queue
3. pop the node from the queue, and add it to the result list, then decrease the indegree of its neighbors by 1
4. while queue is not empty, we repeat 3 until the queue is empty
5. if the result list is not equal to the number of nodes (or not all value in indegree list is empty) then there is a cycle in the graph, else we can simply return the result list
|
import express from "express";
const router = express.Router();
import service from "../services/servicePatients";
import toNewPatient from "../utils/utils_toNewPatient";
import toNewEntry from "../utils/utils_toNewEntry";
router.get("/", (_req, res) => {
console.log("Fetching all patients");
const data = service.getPatientsNoSSN();
res.send(data);
});
router.get("/:id", (req, res) => {
console.log("Getting a patient by id:", req.params.id);
const data = service.getSpecificPatient(req.params.id);
if (data === null)
res.status(404).send(req.params.id + " doesnt match any patients´ id");
else
res.send(data);
});
router.post("/", (req, res) => {
try {
console.log("A new patient was added:", req.body);
const newPatient = toNewPatient(req.body);
const addedPatient = service.addPatient(newPatient);
res.json(addedPatient);
} catch (e: unknown) {
let errorMessage = "Error: ";
if (e instanceof Error)
errorMessage += e.message;
res.status(400).send(errorMessage);
}
});
router.post("/:id/entries", (req, res) => {
try {
console.log("Adding a new entry for Patient:", req.params.id, req.body);
const newEntry = toNewEntry(req.body);
const patientWithNewEntry = service.addEntrytoPatient(req.params.id, newEntry);
res.json(patientWithNewEntry);
} catch (e: unknown) {
let errorMessage = "Error: ";
if (e instanceof Error)
errorMessage += e.message;
res.status(400).send(errorMessage);
}
});
export default router;
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/**
* @title IController
* @author @InsureDAO
* @dev Defines the basic interface for an InsureDAO Controller.
* @notice Controller invests market deposited tokens on behalf of Vault contract.
* This contract gets utilized a vault assets then invests these assets via
* Strategy contract. To Avoid unnecessary complexity, sometimes the controller
* includes the functionality of a strategy.
*/
interface IController {
/**
* @notice Utilizes a vault fund to strategies, which invest fund to
* various protocols. Vault fund is utilized up to maxManagingRatio
* determined by the owner.
* @dev You **should move all pulled fund to strategies** in this function
* to avoid unnecessary complexity of asset management.
* Controller exists to route vault fund to strategies safely.
*/
function adjustFund() external;
/**
* @notice Returns utilized fund to a vault. If the amount exceeds all
* assets the controller manages, transaction should be reverted.
* @param _amount the amount to be returned to a vault
*/
function returnFund(uint256 _amount) external;
/**
* @notice Returns all assets this controller manages. Value is denominated
* in USDC token amount. (e.g. If the controller utilizes 100 USDC
* for strategies, valueAll() returns 100,000,000(100 * 1e6)) .
*/
function managingFund() external view returns (uint256);
/**
* @notice The proportion of a vault fund to be utilized. 1e6 regarded as 100%.
*/
function maxManagingRatio() external view returns (uint256);
/**
* @notice Changes maxManagingRatio which
* @param _ratio maxManagingRatio to be set. See maxManagingRatio() for more detail
*/
function setMaxManagingRatio(uint256 _ratio) external;
/**
* @notice Returns the proportion of a vault fund managed by the controller.
*/
function currentManagingRatio() external view returns (uint256);
/**
* @notice Moves managing asset to new controller. Only vault should call
* this method for safety.
* @param _to the destination of migration. this address should be a
* controller address as this method expected call immigrate() internally.
*/
function emigrate(address _to) external;
/**
* @notice Receives the asset from old controller. New controller should call this method.
* @param _from The address that fund received from. the address should be a controller address.
*/
function immigrate(address _from) external;
/**
* @notice Sends managing fund to any address. This method should be called in case that
* managing fund cannot be moved by the controller (e.g. A protocol contract is
* temporary unavailable so the controller cannot withdraw managing fund directly,
* where emergencyExit() should move to the right to take reward like aUSDC on Aave).
* @param _to The address that fund will be sent.
*/
function emergencyExit(address _to) external;
}
error RatioOutOfRange();
error ExceedManagingRatio();
error AlreadyInUse();
error AaveSupplyCapExceeded();
error InsufficientManagingFund();
error InsufficientRewardToWithdraw();
error NoRewardClaimable();
error MigrateToSelf();
error SameAddressUsed();
|
/* eslint no-use-before-define: 0 */
import { lazy, Suspense, useEffect } from 'react';
import { Outlet, Navigate, useRoutes, useNavigate } from 'react-router-dom';
import { useAuth } from 'src/useAuth/auth';
import ServicePage from 'src/pages/services';
import DashboardLayout from 'src/layouts/dashboard';
import UserPage from 'src/pages/user';
export const IndexPage = lazy(() => import('src/pages/app'));
export const BlogPage = lazy(() => import('src/pages/blog'));
export const CategoryPage = lazy(() => import('src/pages/category'));
export const LoginPage = lazy(() => import('src/pages/login'));
export const ProductsPage = lazy(() => import('src/pages/products'));
export const Page404 = lazy(() => import('src/pages/page-not-found'));
export default function Router() {
const { token } = useAuth();
const navigate = useNavigate();
useEffect(() => {
if (!token) {
navigate('/login')
}
}, [token])
const publicRoutes = [
{
path: 'login',
element: <LoginPage />,
},
{
path: '404',
element: <Page404 />,
},
{
path: '*',
element: <Navigate to="/404" />,
},
];
const privateRoutes = [
{
element: (
<DashboardLayout>
<Suspense fallback={<div>Loading...</div>}>
<Outlet />
</Suspense>
</DashboardLayout>
),
children: [
{ element: <IndexPage />, index: true },
{ path: 'services', element: <ServicePage /> },
{ path: 'products', element: <ProductsPage /> },
{ path: 'blog', element: <BlogPage /> },
{ path: 'category', element: <CategoryPage /> },
{ path: 'user', element: <UserPage /> },
],
}
];
const routes = useRoutes(token ? privateRoutes : publicRoutes);
return routes;
}
|
import React from 'react';
import './App.css';
import Home from './pages/home/Home';
import Footer from './components/footer/Footer';
import { Routes, Route } from 'react-router-dom';
import SearchPage from './pages/searchpage/SearchPage';
import PageNotFound from './pages/pagenotfound/PageNotFound';
import Login from './pages/auth/Login';
import Signup from './pages/auth/SignUp';
function App() {
return (
<div className="App">
<Routes>
<Route path="/" element={<Home />} />
<Route path='/Search' element={<SearchPage/>}/>
<Route path="/search/:_id" element={<SearchPage/>} />
<Route path="*" element={<PageNotFound/>} />
<Route path='/login' element={<Login/>} />
<Route path='/signup' element={<Signup/>} />
</Routes>
<Footer/>
</div>
);
}
export default App;
|
'jibba jabba - Physics Challenge Sep 2013
'Pendulum motion - 1st attempt
'x = cos(a) * r + offsetX y = sin(a) * r + offsetY. Offset is the origin
InitGW()
pendulumLength = 200 'radius of arc
bobRadius = 30
centreBobX = GraphicsWindow.Width / 2 - bobRadius
centreBobY = GraphicsWindow.Height / 2 - bobRadius
posBobX = centreBobX
posBobY = centreBobY + pendulumLength
displacementRangeForBobY = 80 'range of vertical displacement
dY = 0.5
quadrant = 1
dA = 0.5
angle = 90
bob = Shapes.AddEllipse(bobRadius * 2, bobRadius * 2)
Shapes.Move(bob, posBobX, posBobY)
While "true"
total_dA = total_dA + dA
total_dY = total_dY + dY
If Math.Abs(total_dY) = displacementRangeForBobY Or total_dY = 0 Then 'or <0
dY = -dY
dA = -dA
EndIf
If total_dY = 0 Then
quadrant = -quadrant
EndIf
angle = angle - dA ' Bouncing problem
posBobY = posBobY - dY
radians = Math.GetRadians(angle)
posBobX = quadrant * Math.Cos(radians) * pendulumLength + centreBobX '*-1 swings the other quadrant
Shapes.Move(bob, posBobX, posBobY)
Program.Delay(5)
EndWhile
Sub InitGW
gw = 900
gh = 600
GraphicsWindow.Width = gw
GraphicsWindow.Height = gh
GraphicsWindow.Left = (Desktop.Width - GraphicsWindow.Width) / 2
GraphicsWindow.Top = 5
GraphicsWindow.PenWidth = 0
EndSub
|
<?php
use App\Http\Controllers\SampahController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('beranda');
});
Route::get('/jeniSampah', function () {
return view('user.sampah');
})->name('jenisSampah');
Route::group(['middleware' => ['auth', 'isAdmin']], function () {
Route::get('/dashboards', function () {
return view('admin.dashboard');
})->name('dashboards');
Route::resource('sampahs', SampahController::class);
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
|
<template>
<form-wizard color="rgba(var(--vs-primary), 1)" :start-index.sync="step" :hideButtons="true" :title="null" :subtitle="null" ref="wizardproc" @on-complete="formSubmitted">
<tab-content v-if="procurment" title="اطلاعات خریداری" class="mb-5">
<vs-row vs-w="12" class="mb-1">
<vs-row vs-w="12">
<vs-divider>اطلاعات خریداری</vs-divider>
</vs-row>
<vs-row vs-w="12">
<vs-col :key="i" v-for="(field, i) in display_fields" vs-type="flex" vs-justify="right" vs-align="right" vs-lg="4" vs-sm="6" vs-xs="12">
<h6 class="mb-5 mt-3 ml-2">
<strong class="mr-4">
{{ (typeof field === 'object') ? $t(field[0]) : $t(field) }}:
</strong>
<small class="mb-5" v-if="(typeof field !== 'object')">{{ procurment[field] }}</small>
<small class="mb-5" v-if="(typeof field === 'object')">
<span :key="i" v-for="(sub, i) in field[1]"> {{ procurment[field[0]][sub] }} </span>
</small>
</h6>
</vs-col>
</vs-row>
</vs-row>
</tab-content>
<tab-content v-if="procurment" title="اطلاعات مالی" class="mb-5">
<vs-row vs-w="12" class="mb-1">
<vs-row vs-w="12">
<vs-divider>اطلاعات خریداری</vs-divider>
</vs-row>
<vs-row vs-w="12">
<vs-col :key="i" v-for="(field, i) in display_fields" vs-type="flex" vs-justify="right" vs-align="right" vs-lg="4" vs-sm="6" vs-xs="12">
<h6 class="mb-5 mt-3 ml-2">
<strong class="mr-4">
{{ (typeof field === 'object') ? $t(field[0]) : $t(field) }}:
</strong>
<small class="mb-5" v-if="(typeof field !== 'object')">{{ procurment[field] }}</small>
<small class="mb-5" v-if="(typeof field === 'object')">
<span :key="i" v-for="(sub, i) in field[1]"> {{ procurment[field[0]][sub] }} </span>
</small>
</h6>
</vs-col>
</vs-row>
</vs-row>
<vs-row vs-w="12" class="mb-1">
<vs-row vs-w="12">
<vs-divider>اطلاعات مالی</vs-divider>
</vs-row>
<vs-table :data="procurment.stock" class="w-full">
<template slot="thead">
<vs-th>جنس / محصول</vs-th>
<vs-th>مقدار</vs-th>
<vs-th>قیمت فی واحد</vs-th>
<vs-th>قیمت مجموعی</vs-th>
</template>
<template slot-scope="{data}">
<vs-tr v-for="(tr, i) in data" :key="i">
<vs-td :data="tr.item_id">
<p> {{ (tr.item_id && tr.item_id.type) ? tr.item_id.type.type : '' }} {{ tr.item_id.name }} </p>
</vs-td>
<vs-td :data="tr.increment_equiv">
{{tr.increment_equiv}} {{ tr.item_id.uom_equiv_id.title }}
</vs-td>
<vs-td :data="tr.unit_price">
{{tr.unit_price | NumThreeDigit}} <small style="color:#42b983;"><b>افغانی </b></small>
</vs-td>
<vs-td :data="tr.total_price">
{{tr.total_price | NumThreeDigit}} <small style="color:#42b983;"><b>افغانی </b></small>
</vs-td>
</vs-tr>
</template>
</vs-table>
</vs-row>
</tab-content>
<tab-content v-if="procurment" title="تصفیه حسابات" class="mb-5">
<vs-row vs-w="12" class="mb-1">
<vs-row vs-w="12">
<vs-divider>اطلاعات خریداری</vs-divider>
</vs-row>
<vs-row vs-w="12">
<vs-col :key="i" v-for="(field, i) in display_fields" vs-type="flex" vs-justify="right" vs-align="right" vs-lg="4" vs-sm="6" vs-xs="12">
<h6 class="mb-5 mt-3 ml-2">
<strong class="mr-4">
{{ (typeof field === 'object') ? $t(field[0]) : $t(field) }}:
</strong>
<small class="mb-5" v-if="(typeof field !== 'object')">{{ procurment[field] }}</small>
<small class="mb-5" v-if="(typeof field === 'object')">
<span :key="i" v-for="(sub, i) in field[1]"> {{ procurment[field[0]][sub] }} </span>
</small>
</h6>
</vs-col>
</vs-row>
</vs-row>
<vs-row vs-w="12" class="mb-1">
<vs-divider>تصفیه حسابات</vs-divider>
<vs-row>
<vs-col vs-type="flex" vs-justify="center" vs-align="center" vs-lg="6" vs-sm="6" vs-xs="12">
<div class="w-full pt-2 mr-3">
<!-- TITLE -->
<label for=""><small>مصارف انتقال</small></label>
<vx-input-group class="number-rtl">
<template slot="prepend">
<div class="prepend-text bg-primary">
<span>AFN</span>
</div>
</template>
<vs-input autocomplete="off" v-model="costForm.service_cost" type="number" v-validate="'required'" name="deposit" />
</vx-input-group>
<span class="absolute text-danger alerttext">{{
errors.first("s1Form.deposit")}}</span>
</div>
</vs-col>
<vs-col vs-type="flex" vs-justify="center" vs-align="center" vs-lg="6" vs-sm="6" vs-xs="12">
<div class="w-full pt-2 lg:ml-3 md:ml-0 mr-3">
<label for=""><small>قیمت مجموعی</small></label>
<vx-input-group class="number-rtl">
<template slot="prepend">
<div class="prepend-text bg-primary">
<span>AFN</span>
</div>
</template>
<vs-input autocomplete="off" v-model="costForm.total_price" type="number" v-validate="'required'" name="tax" />
</vx-input-group>
<span class="absolute text-danger alerttext">{{
errors.first("s1Form.tax")
}}</span>
</div>
</vs-col>
</vs-row>
</vs-row>
</tab-content>
<tab-content v-if="procurment" title="تاییدی" class="mb-5">
<vs-row vs-w="12" class="mb-1">
<vs-row vs-w="12">
<vs-divider>اطلاعات خریداری</vs-divider>
</vs-row>
<vs-row vs-w="12">
<vs-col :key="i" v-for="(field, i) in display_fields" vs-type="flex" vs-justify="right" vs-align="right" vs-lg="4" vs-sm="6" vs-xs="12">
<h6 class="mb-5 mt-3 ml-2">
<strong class="mr-4">
{{ (typeof field === 'object') ? $t(field[0]) : $t(field) }}:
</strong>
<small class="mb-5" v-if="(typeof field !== 'object')">{{ procurment[field] }}</small>
<small class="mb-5" v-if="(typeof field === 'object')">
<span :key="i" v-for="(sub, i) in field[1]"> {{ procurment[field[0]][sub] }} </span>
</small>
</h6>
</vs-col>
</vs-row>
<vs-row vs-w="12">
<vs-divider>تاییدی</vs-divider>
</vs-row>
<vs-col class="pl-5 my-3">
<vs-checkbox v-model="is_confirmed" color="success" class="float-left" size="large">
<strong>تمام اطلاعات درج شده توسط مدیر سیستم تایید میگردد.</strong>
</vs-checkbox>
</vs-col>
</vs-row>
</tab-content>
<div :key="com_key" v-bind:class="{ 'float-right': step == 0 }" class="flex space-between mt-2" v-if="$refs.wizardproc">
<vs-button v-if="step > 0" @click="$refs.wizardproc.prevTab">قبلی</vs-button>
<div class="flex">
<vs-button v-if="!$refs.wizardproc.isLastStep && step == 2" color="success" @click.prevent="submitServiceCost" style="float: left;margin-top: 2px;" class="mx-2">ثبت</vs-button>
<vs-button v-if="$refs.wizardproc.isLastStep" color="success" @click.prevent="submitConfirmation" class="mx-2">ثبت</vs-button>
<vs-button v-if="!$refs.wizardproc.isLastStep" @click="$refs.wizardproc.nextTab">بعدی</vs-button>
<vs-button v-if="$refs.wizardproc.isLastStep" @click="popupModalActive = false, sale = [], $refs.wizardproc.hideButtons = true">بستن صفحه</vs-button>
</div>
</div>
</form-wizard>
</template>
<script>
import {
FormWizard,
TabContent
} from 'vue-form-wizard'
import 'vue-form-wizard/dist/vue-form-wizard.min.css'
export default {
data() {
return {
is_confirmed: false,
com_key: 0,
user_permissions: localStorage.getItem('user_permissions'),
step: 0,
procurment: null,
costForm: new Form({
total_price: 0,
service_cost: 0,
old_total_price: 0,
}),
display_fields: [
'serial_no',
'description',
'date_time',
['vendor', ['name']],
['user', ['firstName', 'lastName']],
],
}
},
created() {},
components: {
FormWizard,
TabContent
},
watch: {
'costForm.service_cost'() {
let x = parseFloat(this.costForm.service_cost);
x = (x) ? x : 0;
this.costForm.total_price = parseFloat(this.costForm.old_total_price) + x;
}
},
methods: {
submitServiceCost() {
this.costForm
.post(`/api/purchase_service_cost/${this.procurment.id}`)
.then((data) => {
swal.fire(
'موفق!',
'معلومات موفقانه ثبت شد!',
'success'
)
})
.catch(() => {
swal.fire(
'ناموفق !',
'لطفا معلومات را بررسی کنید!',
'error'
)
});
},
submitConfirmation() {
this.axios
.post(`/api/sale_info_confirmation/purchase/${this.procurment.id}`, {
confirmed: this.is_confirmed,
})
.then((data) => {
swal.fire(
'موفق!',
'معلومات موفقانه ثبت شد!',
'success'
)
})
.catch(() => {
swal.fire(
'ناموفق !',
'لطفا معلومات را بررسی کنید!',
'error'
)
});
},
getTransaction(id) {
if (id) {
this.$Progress.start()
this.axios.get('/api/procurments/' + id)
.then((response) => {
this.procurment = response.data;
const appLoading = document.getElementById("loading-bg");
if (appLoading) {
appLoading.style.display = "none";
}
this.costForm.service_cost = this.procurment.fr_service;
this.costForm.old_total_price = parseFloat(this.procurment.fr.credit) - parseFloat(this.procurment.fr_service);
this.costForm.total_price = this.procurment.fr.credit;
this.$Progress.set(100)
this.com_key += 1;
})
}
},
formSubmitted() {
this.$emit('closesteps');
},
setWizardStepProc(index) {
this.step = index;
this.$refs.wizardproc.activateAll();
this.$refs.wizardproc.navigateToTab(index - 1);
// this.$refs.wizard.navigateToTab(2);
},
}
}
</script>
|
## Study
# 12장. 타입스크립트 프로젝트 관리
> 타입스크립트 프로젝트에서 유용하게 활용할 수 있는 개념과 팁 알아보기
```html
<details>
<summary>목차</summary>
<ul markdown="1">
<li>
<a href="#121-앰비언트-타입-활용하기">12.1 앰비언트 타입 활용하기</a>
</li>
<li>
<a href="#122-스크립트와-설정-파일-활용하기"
>12.2 스크립트와 설정 파일 활용하기</a
>
</li>
<li>
<a href="#123-타입스크립트-마이그레이션"
>12.3 타입스크립트 마이그레이션</a
>
</li>
<li><a href="#124-모노레포">12.4 모노레포</a></li>
</ul>
</details>
<br />
```
## 12.1 앰비언트 타입 활용하기
### (1) 앰비언트 타입 선언
타입스크립트 타입 선언은 .ts .tsx 확장자를 가진 파일에서 할 수도 있지만 **.d.ts** 확장자를 가진 파일에서도 선언할 수 있다.
**앰비언트 타입 선언**
.d.ts 확장자를 가진 파일에서는 **타입 선언만** 할 수 있고 값은 표현할 수 없다. 값을 포함하는 일반적인 선언과 구별하기 위해 **.d.ts 파일에서 하는 타입 선언**을 **앰비언트(ambient) 타입 선언**이라고 부른다.
앰비언트 타입 선언으로는 값을 직접 정의할 수 없기 때문에 **대신 `declare` 키워드를 사용해 어딘가에 값이 존재한다는 사실을 알린다.** 단순히 존재 여부만 알려주기 때문에 컴파일 대상은 아니다.
**대표적인 앰비언트 타입 선언 활용 사례**
타입스크립트는 기본적으로 .ts와 .js파일만 이해하기 때문에 다른 파일 형식은 인식하지 못해 모듈로 가져오려하면 에러가 발생한다. 이런 경우에 `declare` 키워드를 사용하여 특정 형식을 모듈로 선언할 수 있다.
```
declare module "*.png" {
const src: string;
export default src;
}
```
> 👉 declare 키워드는 이미 존재하지만 타입스크립트가 알지 못하는 부분을 컴파일러에 '이러한 것이 존재해'라고 알려주는 역할을 한다.
**자바스크립트로 작성된 라이브러리**
자바스크립트로 작성된 npm 라이브러리는 타입 선언이 존재하지 않기 때문에 any로 추론될 것이다. 때문에 만일 tsconfig.json에서 any를 사용하지 못하게 설정했다면 프로젝트가 빌드되지 않을 것이다.
이런 경우에 자바스크립트 라이브러리 내부 함수와 변수의 타입을 앰비언트 타입으로 선언하면 타입스크립트는 자동으로 .d.ts 파일을 검색하여 타입 검사를 진행하게 되므로 문제없이 컴파일 된다. VSCode와 같은 에디터도 .d.ts 파일을 해석해 코드를 작성할 때 유용한 타입 힌트를 제공한다.
예시로 @types/react를 설치하면 node_modules/@types/react에 index.d.ts와 global.d.ts가 설치된다. 이러한 파일에는 리액트의 컴포넌트와 훅에 대한 타입이 정의되어 있다.
> 👉 앰비언트 타입 선언은 타입스크립트에게 '자바스크립트 코드 안에는 이러한 정보들이 있어'라고 알려주는 도구이다.
**자바스크립트 어딘가에 전역 변수가 정의되어 있음을 타입스크립트에 알릴 때**
타입스크립트로 직접 구현하지 않았지만 실제 자바스크립트 어딘가에 전역 변수가 정의되어 있는 상황을 타입스크립트에 알릴 때 앰비언트 타입 선언을 사용한다.
예를 들어 웹뷰를 개발할 때 네이티브 앱과의 통신을 위한 인터페이스를 네이티브 앱이 Window 객체에 추가하는 경우가 많다. 이러한 전역 객체인 Window에 변수나 함수를 추가하면 타입스크립트에서 직접 구현하지 않았더라도 실제 런타임 환경에서 해당 변수를 사용할 수 있다.
```
declare global {
interface Window {
devideId: string | undefined;
appVersion: string;
}
}
// 전역 객체인 Window의 타입을 지정해 해당 속성이 정의되어 있음을 알림
```
### (2) 앰비언트 타입 선언 시 주의점
**타입스크립트로 만드는 라이브러리에는 불필요**
tsconfig.json의 declaration을 true로 설정하면 타입스크립트 컴파일러가 .d.ts 파일을 자동으로 생성해주기 때문에 수동으로 작성할 필요가 없다. 따라서 타입스크립트로 라이브러리를 개발할 때는 앰비언트 타입 선언을 사용할 필요가 없다.
**전역으로 타입을 정의하여 사용할 때 주의해야 할 점**
- 서로 다른 라이브러리에서 동일한 이름의 앰비언트 타입 선언을 하지 않도록 주의한다.
- 충돌이 발생하면 어떤 타입 선언이 적용될지 알기 어렵다.
- 충돌이 발생하면 의도한 대로 동작하지 않을 수 있다.
- 나중에 앰비언트 타입 선언을 변경할 때 어려움을 겪을 수 있다.
- 명시적인 import나 export가 없기 때문에 코드의 의존성 관계가 명확하지 않기 때문이다.
### (3) 앰비언트 타입 선언을 잘못 사용했을 때의 문제점
앰비언트 변수는 .ts 파일 내부에서는 잘 선언하지 않는다. 왜냐하면 앰비언트 타입은 명시적인 import나 export 없이도 코드 전역에서 사용할 수 있는데 의존성 관계는 보이지 않아, 변경에 의한 영향 범위를 파악하기 어렵기 때문이다.
.d.ts 파일이 아닌 .ts .tsx 파일 내에서 앰비언트 타입 선언을 하기 위해서 `declare` 키워드를 사용한다.
```tsx
// src/index.tsx : 최상위 파일
import React from "react";
import ReactDOM from "react-dom";
import App from "App";
// Window 전역 객체의 확장 표시
delcare global {
interface Window {
Example: string;
}
}
const SomeComponent = () => {
return <div>앰비언트 타입 선언은 .tsx 파일에서도 가능</div>;
};
```
위처럼 선언된 앰비언트 타입은 아래와 같이 다른 곳에서 import 없이 사용할 수 있다.
```tsx
// src/test.tsx
window.Example; // 타입 에러 없음
```
이렇듯 앰비언트 변수 선언은 어느 곳에서나 영향을 줄 수 있기 때문에 **일반 타입 선언과 섞이게 되면 앰비언트 선언이 어떤 파일에 포함되어 있는지 파악하기 어려워진다**는 문제를 갖는다. 위는 그나마 src/index.tsx라는 최상위 파일에서 앰비언트 변수 선언을 했기 때문에 파악하기 쉬운 예시다. 만일 작은 컴포넌트에서 앰비언트 변수 선언이 이루어졌었다면 찾기 어려워진다.
일종의 개발자 간 약속으로 **앰비언트 타입 선언은 .d.ts 파일 내에서** 하도록 한다. 타입 선언 위치가 명확해야 가독성이 높아지고 유지보수도 편하게 할 수 있다.
### (4) 앰비언트 타입 활용하기
타입스크립트 컴파일러에 타입 정보를 알려주는 `declare` 키워드를 더 효과적으로 활용할 수 있는 방법을 살펴보자.
**타입을 정의하여 임포트 없이 전역으로 공유**
.d.ts 파일에서의 앰비언트 타입 선언은 전역 변수와 같은 역할을 한다. 따라서 앰비언트 타입을 선언하면 모든 코드 내에서 임포트하지 않고 사용할 수 있다.
예를 들어 유용한 유틸리티 타입을 작성했다면, 앰비언트 타입으로 유틸리티 타입을 선언해 모든 코드에서 해당 타입을 사용하도록 할 수 있다. 마치 내장 타입 유틸리티 함수를 사용하는 것과 같은 모양새다.
```
// src/index.d.ts
type Optional<T extends object, K extends keyof T = keyof T> = Omit<T, K> &
Partial<Pick<T, K>>;
```
```
// src/components.ts
type Props = { name: string; age: number; visible: boolean };
type OptionalProps = Optional<Props>; // Expect: { name?: string; age?: number; visible?: boolean };
```
**declare type 활용하기**
보편적으로 많이 사용하는 커스텀 유틸리티 타입을 declare type으로 선언하여 사용할 수 있다. 아래 예시처럼 Nullable 타입을 선언해서 어디에서든 쉽게 사용할 수 있다.
```tsx
declare type Nullable<T> = T | null;
const name: Nullable<string> = "woowa";
```
**declare module 활용하기**
CSS-in-JS 라이브러리 중 하나인 styled-components는 기존의 폰트 크기, 색상 등을 객체로 관리한다. 이렇게 정의된 theme의 인터페이스 타입을 확장하여 theme 타입이 자동으로 완성되도록 하는 기능을 지원하고 있다.
```
const fontSizes = {
xl: "30px",
/* ... */
};
const theme = {
fontSizes,
/* ... */
};
declare module "styled-components" {
type Theme = typeof theme; // 정의된 theme에서 스타일 값을 가져옴
export interface DefaultTheme extends Theme {} // 기존 인터페이스 타입과 통합하여 theme 타입을 자동 완성
}
```
이외에도 로컬 이미지나 SVG같이 외부로 노출되어 있지 않은 파일을 모듈로 인식하여 사용할 수 있게끔 만들 수 있다.
```
declare module "*.gif" {
const src: string;
export default src;
}
```
**declare namespace 활용하기**
Node.js 환경에서 .env 파일을 사용할 때, `declare namespace`를 활용하여 process.env로 설정값을 손쉽게 불러오고 환경변수의 자동 완성 기능을 쓸 수 있다.
```
// .env
API_URL = "localhost:8000";
declare namespace NodeJS {
interface ProcessEnv {
readonly API_URL: string;
}
}
console.log(process.env.API_URL);
// namespace를 활용하여 process.env 타입을 보강해주지 않은 경우는 as 단언 사용
// console.log(process.env.API_URL as string);
```
**declare global 활용하기**
`declare global` 키워드는 전역 변수를 선언할 때 사용한다.
```
declare global {
interface Window {
newProperty: string;
}
}
```
예를 들어 위처럼 전역 변수인 Window 객체에 newProperty 속성을 추가한 것과 같은 동작 구현이 가능하다. 대표적으로 네이티브 앱과의 통신을 위한 인터페이스를 Window 객체에 추가할 때 앰비언트 타입 선언을 활용할 수 있다.
아래는 iOS 웹뷰에서 자바스크립트로 네이티브 함수를 호출하기 위한 함수를 정의한 것으로, 함수를 호출할 때 자동 완성 기능을 활용해 실수를 줄일 수 있다.
```
declare global {
interface Window {
webkit?: {
messageHandlers?: Record<
string,
{ postMessage?: (parameter: string) => void }
>;
};
}
}
// window.webkit?. 까지 입력 시 messageHandler? 가 자동 완성됨
```
### (5) declare와 번들러의 시너지
```
const color = {
white: "#ffffff",
black: "#000000",
} as const;
type ColorSet = typeof color;
declare global {
const _color: ColorSet;
}
```
위와 같이 전역에 `_color`라는 변수가 존재함을 타입스크립트 컴파일러에 알리면 해당 객체를 활용할 수 있다.
```
const white = _color["white"];
```
하지만 타입스크립트 에러는 발생하지 않지만, 아직 `ColorSet` 타입을 가지고 있는 `_color` 객체의 실제 데이터가 존재하지 않아 코드 실행 시 기대하는 동작과 다르게 동작할 수 있다.
이를 해결하기 위한 방법 중 하나가 **번들 시점에 번들러릍 통해서 해당 데이터를 주입하는 것**이다. `declare global`로 전역 변수를 선언하는 과정과 번들러를 통해 데이터를 주입하는 절차를 함께 활용하면 시너지를 낼 수 있다.
아래는 롤업(rollup) 번들러의 inject 모듈로 데이터를 주입하는 예시이다. inject 모듈은 import문의 경로를 분석하여 데이터를 가져오는 역할을 한다.
```
프로젝트 레포 구조
┣ 📂node_modules
┣ 📜data.ts --------------- 색상 정의
┣ 📜index.ts
┣ 📜package-lock.json
┣ 📜package.json
┣ 📜rollup.config.js
┗ 📜type.ts --------------- 타입 정의
```
```
// data.ts : 색상 정의
export const color = {
white: "#ffffff",
black: "#000000",
} as const;
```
```
// type.ts : 타입 정의
improt { color } from "./data";
type ColorSet = typeof color;
declare global { // declare global로 전역 변수 _color가 존재함을 알림
const _color: ColorSet;
}
```
```
// index.ts
console.log(_color["white"]);
```
```
// rollup.config.js
import inject from "@rollup/plugin-inject";
import typescript from "@rollup/plugin-typescript";
export default [
{
input: "index.ts",
output: [
{
dir: "lib",
format: "esm",
},
],
plugins: [typescript(), inject({ _color: ["./data", "color"] })],
// inject 모듈을 사용하여 _color에 해당되는 데이터를 삽입
},
];
```
위 설정을 통해 번들러를 통해 만들어진 결과물을 실행하면 `#ffffff`가 정상적으로 출력된다.
## 12.2 스크립트와 설정 파일 활용하기
### (1) 스크립트 활용하기
**실시간으로 타입 검사하기**
기본적으로 에디터가 타입 에러를 감지해주지만 컴퓨터 성능이 떨어지거나 프로젝트 규모가 커지면 이 속도가 느려진다. 에디터에서는 에러가 없다고 확인했지만 husky를 통해 타입 에러를 발견하기도 한다. 이런 경우에 아래 스크립트를 사용해 실시간 에러를 확인할 수 있다.
```bash
$ yarn tsc --noEmit --incremental -w
# noEmit: 자바스크립트로 된 출력 파일을 생성하지 않음
# incremental: 증분 컴파일(변경 사항이 있는 부분만 컴파일)을 활성화하여 컴파일 시간을 단축시킴
# w: 변경사항 모니터링
```
해당 스크립트를 통해 파일이 변경될 때마다 tsc를 실행. 어디에서 타입 에러가 발생했는지를 실시간 추적할 수 있다.
+) npm에서 사용하는 방법 ([ChatGPT](https://chat.openai.com/share/f2d99f9a-80a0-45f0-9bb7-0e9713922665))
package.json에서 명령어로 스크립트를 추가한 뒤 사용한다.
```
// package.json
{
"scripts": {
"type-check": "tsc --noEmit --incremental -w"
}
}
```
```bash
$ npm run type-check
```
**타입 커버리지 확인하기**
프로젝트의 모든 부분이 타입스크립트 통제하에 돌아가고 있는지를 정량적으로 판단하기 위해 아래 스크립트를 사용할 수 있다.
```bash
$ npx type-coverage --detail
```
확인 결과로 타입으로 지정되어있는 변수의 퍼센트를 보여주는데 남은 퍼센트는 any로 선언되어 있다는 의미이다. (ex. 87% => 13%는 any)
타입스크립트로 마이그레이션 중인 프로젝트나 레거시 코드가 많은 프로젝트를 다룰 때 더 나은 코드로 리팩토링을 위한 지표로 사용할 수 있다.
### (2) 설정 파일 활용하기
**타입스크립트 컴파일 속도 높이기**
tsconfig의 incremental 속성을 true로 설정하면 **증분 컴파일(변경 사항이 있는 부분만 컴파일)** 이 활성화된다. 이로써 모든 대상을 컴파일하지 않아도 되므로 컴파일 타임을 줄일 수 있다.
```
// tsconfig.json
{
"compilerOptions": {
"incremental": true
}
}
```
tsconfig 설정 또는 스크립트 사용 가능하다.
```bash
$ yarn tsc --noEmit --incremental -diagnostics
# noEmit: 자바스크립트로 된 출력 파일을 생성하지 않음
# incremental: 증분 컴파일 활성화하여 컴파일 시간을 단축시킴
# diagnostics: 디버깅을 위한 진단 정보 출력
```
### (3) 에디터 활용하기
에디터에서 종종 정의된 타입이 있는 객체인데도 import되지 않거나 자동 완성 기능이 동작하지 않는데, 이 경우 타입스크립트 서버를 재실행하면 된다.
- VSCode: 명령어 팔레트 열고 `Restart TS server`
- VSCode 명령어 팔레트 열기
- Mac) <kbd>Command</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>
- Window) <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>
- WebStorm: TypeScript tool window에서 `Restart TypeScript Service`
- TypeScript tool window 위치 : 에디터 오른쪽 하단 바 TypeScript 메뉴
## 12.3 타입스크립트 마이그레이션
### (1) 타입스크립트 마이그레이션의 필요성
타입스크립트를 새로운 기술 스택으로 도입하는 것을 결정하면 아래 두 작업 중 선택이 필요하다.
- 기존 프로젝트를 타입스크립트로 마이그레이션
- 타입스크립트 프로젝트로 새로 구축
프로젝트 규모와 특성 및 내외부 여건을 종합적으로 고려하며 어떤 방식이 나을지 신중하게 따져봐야한다.
### (2) 점진적인 마이그레이션
일반적으로 작은 부분부터 시작하여 점차 범위를 넓혀가며 마이그레이션을 진행하게 된다. 이 점진적인 시작이 가능하다는 점이 진입 장벽을 낮추고 프로젝트의 전반적인 동작을 안정적으로 유지할 수 있게 한다.
### (3) 마이그레이션 진행하기
1️⃣ 타입스크립트 개발 환경 설정 + 빌드 파이프라인에 타입스크립트 컴파일러를 통합함
2️⃣ tsconfig.json 파일 설정
```
// tsconfig.json
{
"compilerOptions": {
"allowJS": true,
// 타입스크립트에서 자바스크립트 함수 import 허용
// 자바스크립트에서 타입스크립트 함수 import 허용
"noImplicityAny": false
// 암시적 any 타입이 있을 때 오류가 발생하지 않도록 함
}
}
```
3️⃣ 타입스크립트로 변환해 감. 필요한 타입과 인터페이스를 하나씩 정의하며 함수 시그니처를 추가해 나감
4️⃣ tsconfig.json 파일 설정 : 2의 설정 해제. 타입이 명시되지 않은 부분이 없는지 점검
## 12.4 모노레포
여러 프로젝트를 관리하는 경우지만, 각 프로젝트의 공통된 요소를 찾아낼 수 있다면 통합 레포지토리를 사용해 조금 더 효율적으로 관리할 수 있다. 이런 **통합된 레포지토리**를 **모노레포**라고 칭한다.
### (1) 분산된 구조의 문제점
일반적으로는 개별 프로젝트마다 별도의 레포지토리를 생성해 관리한다. 이는 Jest, Babel, 등의 설정 파일도 별도, 빌드 파이프라인도 별도, 모든 내용들이 독립적으로 관리된다는 것.
이러한 상황에서 서로 다른 프로젝트가 공통으로 필요한 기능이 있으면 복사/붙여넣기를 활용하는데, 이런 경우 해당 기능 유지 보수 시 반복 작업이 필요하다. 이는 개발자 경험(DX) 저하를 불러올 수 있다.
이런 분산된 구조가 야기하는 문제에서 벗어나기 위해 **반복되는 코드를 함수화하여 통합하듯이 한 곳에서 프로젝트를 관리할 수 있도록 통합**해야 한다.
### (2) 통합할 수 있는 요소 찾기
먼저 프로젝트 내에서 공통으로 통합할 수 있는 요소를 찾아야 한다.
```
A 프로젝트 레포
📂utils
┣ 📜clipboard.ts
┣ 📜permission.ts
┗ 📜validation.ts
B 프로젝트 레포
📂utils
┣ 📜clipboard.ts
┣ 📜storage.ts
┗ 📜validation.ts
```
위의 경우 clipboard, validation 파일을 통합할 수 있는 파일로 우선 보고, 각 파일의 소스코드가 같지 않다면 통합을 위해 일부 수정해야한다.
### (3) 공통 모듈화로 관리하기
소스코드 수정 후 모듈화를 통해 통합할 수 있다.
npm과 같은 패키지 관리자를 활용하여 공통 모듈을 생성하고 관리한다면 각 프로젝트에서 간편하게 모듈고 의존성을 맺고 사용할 수 있게 된다. 새로운 프로젝트를 시작하더라도 모듈을 통해 코드를 재사용할 수 있고 유지보수도 쉬워진다.
공통 모듈화를 통해 단순 코드 복사 작업은 줄지만 공통 모듈에 변경이 발생한다면 해당 모듈을 사용하는 프로젝트에서도 추가 작업이 필요할 수 있는 등의 아쉬운 점은 아직 있다.
### (4) 모노레포의 탄생
**모노레포(Monorepo)** 란 **버전 관리 시스템에서 여러 프로젝트를 하나의 레포지토리로 통합하여 관리하는 소프트웨어 개발 전략**이다.
모노레포를 사용하면 개발 환경 설정도 통합할 수 있어 더 효율적인 관리가 가능해진다.
**다른 소프트웨어 개발 전략**
- 모놀리식(Monolithic) : 다양한 기능을 가진 프로젝트를 하나의 레포지토리로 관리하는 구조. 이전에 인기있던 기법이나 코드 간의 직접적인 의존이 발생하는 문제가 있어 효율적이지 못했음
- 폴리레포(Polyrepo) : 거대한 프로젝트를 작은 프로젝트의 집합으로 나누어 관리하는 구조
**모노레포의 장점**
- Lint, CI/CD 등 개발 환경 설정도 통합하여 관리하기 때문에 **불필요한 코드 중복을 줄여준다.**
- 별도의 패키지 관리를 통해 모듈을 게시하지 않아도 된다.
- 기능 변화를 쉽게 추적하고 의존성을 관리할 수 있게 된다.
**모노레포의 단점**
- 시간이 지나면서 레포지토리가 거대해질 수 있다.
- 하나의 레포지토리에 여러 팀의 이해관계가 얽혀있다면 소유권과 권한 관리가 복잡해질 수 있다.
👉 각 프로젝트나 모듈의 소유권을 명확히 정의하고 규칙을 설정하는 과정이 별도로 필요하다.
|
#include "main.h"
/**
* *leet - encode to 1337
* @str: address of string
* Return: pointer to the encoded string
*/
char *leet(char *str)
{
char s1[] = "aAeEoOtTlL";
char s2[] = "4433007711";
int i, j;
for (i = 0; str[i] != '\0'; i++)
{
for (j = 0; s1[j] != '\0'; j++)
{
if (str[i] == s1[j])
{
str[i] = s2[j];
}
}
}
return (str);
}
|
import React, { useEffect } from "react";
import "@glidejs/glide/src/assets/sass/glide.core.scss";
import Glide from "@glidejs/glide";
import { crew } from '../../../service/data.json';
import { imagesEmployees, getImageByIndex } from '../../../utils/GetIndexImages';
import {
BgImage,
GlideWrapper,
Container,
SectionInfo,
PageTitle,
RoleInformation,
NavigationPoints,
SectionPhoto,
Dot
} from "./style";
const Crew = (props: any) => {
useEffect(() => {
const glide = new Glide("#glide", {
type: 'slider',
perView: 1
})
glide.mount();
}, [])
return (
<>
<BgImage /> {
crew ? (
<div id="glide">
<div className="glide__track" data-glide-el="track">
<ul className="glide__slides">
{crew.map((item, index) => (
<li key={index}>
<GlideWrapper>
<Container>
<SectionInfo>
<PageTitle>
<h2><strong>02</strong>meet your crew</h2>
</PageTitle>
<RoleInformation>
<h3>{item.role}</h3>
<h1>{item.name}</h1>
<p>{item.bio}</p>
</RoleInformation>
<NavigationPoints data-glide-el="controls[nav]">
<Dot data-glide-dir="=0" />
<Dot data-glide-dir="=1" />
<Dot data-glide-dir="=2" />
<Dot data-glide-dir="=3" />
</NavigationPoints>
</SectionInfo>
<SectionPhoto>
<img src={getImageByIndex<string>(index, imagesEmployees)} alt={item.name} />
</SectionPhoto>
</Container>
</GlideWrapper>
</li>
))}
</ul>
</div>
</div>
) : <h1>CARREGANDO....</h1>
}
</>
)
}
export default Crew;
|
package com.sh.spring.log;
import org.apache.log4j.Logger;
/**
* loggingFramework
* - 모드별 출력가능
* - 개발-운영 변경 시,모드만 변경해서 성능저하문제해결
* - log4j, logback, javt.util.logging, apache-commons-loggin 등등
* - system.out.println()의 문제점 : 구분없이출력되어버려 서버 운영 효율을 떨어뜨림
* - 개발 - 운영 변경 시 출력코드 수정하다 처리되는코드도 주석되어 문제가 많이 발생
* - slf4j 서비스계층역할을 할 의존을 중간에 끼워 스프링앱에서 사용
*
* 모드
* - fatal : 아주 심각한 오류
* - error : 프로그램 실행 시 오류가 발생하는경우 = exception
* - warn : 현재 실행에는 문제가 없지만, 이후 버전에서는 변경될수 있는 잠재적오류
* - info : 정보성 메세지
* - debug : 개발,디버그 시 사용하는 로그
* - trace : 디버그를 더 세분화 / 추적용으로 메소드의 시작과 끝 등을 체크
*/
public class Log4jStudy {
private static final Logger log = Logger.getLogger(Log4jStudy.class);
public static void main(String[] args) {
log.fatal("message - fatal");
log.error("message - error");
log.warn("message - warn");
log.info("message - info"); //이거는 log4j.xml 파일에서 설정한 레벨에따라 출력되는게 다름
log.debug("message - debug"); // <level value="debug" /> 이걸로 설정했을 때 여기까지 나옴
log.trace("message - trace");
/** 출력값
FATAL: com.sh.spring.log.Log4jStudy - message - fatal
FATAL: com.sh.spring.log.Log4jStudy - message - error
WARN : com.sh.spring.log.Log4jStudy - message - warn
INFO : com.sh.spring.log.Log4jStudy - message - info
debut, trace 안나오는 이유는 ?
*
*/
}
}
|
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { CdQuestionService } from 'src/app/services/backend/cd-question.service';
import {NgbAccordionConfig} from '@ng-bootstrap/ng-bootstrap';
import Swal from 'sweetalert2';
@Component({
selector: 'app-cd-question',
templateUrl: './cd-question.component.html',
styleUrls: ['./cd-question.component.css'],
})
export class CdQuestionComponent implements OnInit {
//https://stackoverflow.com/questions/35446955/how-to-go-back-last-page
// https://viblo.asia/p/angular-reactive-forms-cach-su-dung-formarray-07LKXepkZV4
constructor(
config: NgbAccordionConfig,
private route:ActivatedRoute,
private CdQuestionService:CdQuestionService,
) {
config.closeOthers = true;
config.type = 'info';
}
page = 1;
count = 0;
tableSize = 8;
tableSizes = [this.tableSize, 10 ,12,14,16,18,20 ];
questions:Array <any>=[];
cateForm: string = "";
formValueAdd:FormGroup = new FormGroup({
id : new FormControl(),
text : new FormControl('',[Validators.required]),
quiz_id : new FormControl(this.getIdSubject()),
answers: new FormArray([])
});
answersArr = this.formValueAdd.get('answers') as FormArray;
addArrAnwserAdd() {
const group = new FormGroup({
id: new FormControl(),
text: new FormControl('',[Validators.required]),
is_correct: new FormControl('false')
});
this.answersArr.push(group);
}
addArrAnwserEdit() {
const group = new FormGroup({
id: new FormControl(),
text: new FormControl([Validators.required]),
is_correct: new FormControl('false')
});
const answersArr = this.formValueAdd.get('answers') as FormArray;
this.answersArr.push(group);
answersArr.push(group);
}
removeArrAnwserAdd(index: number) {
this.answersArr.removeAt(index);
}
removeArrAnwserEdit(index: number) {
this.answersArr.removeAt(index);
const answersArr = this.formValueAdd.get('answers') as FormArray;
answersArr.removeAt(index)
}
ngOnInit(): void {
this.listQuestion();
}
listQuestion(){
this.CdQuestionService.getQuestionQuiz(this.getIdSubject()).subscribe({
next:(res)=>{
this.questions =res
// console.log(res);
},
error:(err)=>{
}
})
}
getIdSubject(){
return this.route.snapshot.paramMap.get('id_quiz');
}
create(){
this.resetForm()
this.cateForm = 'add';
this.addArrAnwserAdd()
this.addArrAnwserAdd()
}
store(){
this.CdQuestionService.store(this.formValueAdd.value).subscribe((res:any)=>{
this.listQuestion()
this.resetForm()
this.swalSuccess("Thêm mới thành công !")
})
}
edit(id_question :any){
this.resetForm()
this.cateForm = 'edit';
this.CdQuestionService.edit(id_question).subscribe( res=>{
this.formValueAdd = new FormGroup({
id : new FormControl( res.id),
text : new FormControl( res.text),
quiz_id : new FormControl(this.getIdSubject()),
answers: new FormArray([])
});
for (let index = 0; index < res.answers.length; index++) {
const key = res.answers[index];
const group = new FormGroup({
id: new FormControl(key.id),
text: new FormControl(key.text),
is_correct: new FormControl(key.is_correct)
});
const answersArr = this.formValueAdd.get('answers') as FormArray;
this.answersArr.push(group);
answersArr.push(group);
}
});
}
update(){
this.CdQuestionService.findId(this.formValueAdd.value.id).subscribe(res=>{
this.CdQuestionService.update(this.formValueAdd.value.id ,this.formValueAdd.value).subscribe( res=>{
this.resetForm();
this.listQuestion();
this.swalSuccess("Cập nhập thành công !")
});
})
}
destroy(id_question:any){
Swal.fire({
title: 'Bạn có chắc muốn loại bỏ ?',
text: 'Bạn sẽ không thể khôi phục tệp này !',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'CHUẨN !',
cancelButtonText: 'Thôi , tao đổi ý !'
}).then((result) => {
if (result.value) {
this.CdQuestionService.destroy(id_question).subscribe(res=>{
this.listQuestion()
this.resetForm()
this.swalSuccess("Xóa thành công !")
})
} else if (result.dismiss === Swal.DismissReason.cancel) {
Swal.fire(
'Đã hủy',
'Tệp vẫn còn nha :)',
'error'
)
}
})
}
changeTextarea(e:any){
console.log(e.target.value);
}
resetForm(){
this. formValueAdd = new FormGroup({
id : new FormControl(),
text : new FormControl(),
quiz_id : new FormControl(this.getIdSubject()),
answers: new FormArray([])
});
this.answersArr = this.formValueAdd.get('answers') as FormArray;
}
swalSuccess(text:any){
Swal.fire({
icon: 'success',
title: text,
showConfirmButton: true,
timer: 1500
})
}
onTableDataChange(event:any){
this.page = event;
this.listQuestion();
}
onTableSizeChange(event:any): void {
this.tableSize = event.target.value;
this.page = 1;
this.listQuestion();
}
}
|
import { RouterModule } from '@angular/router';
import { Todo } from 'src/app/core/interfaces/todo.model';
import {
ComponentFixture,
inject,
TestBed,
waitForAsync,
} from '@angular/core/testing';
import { TodoService } from 'src/app/core/services/todo.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TableComponent } from './table.component';
describe('TableComponent', () => {
let component: TableComponent;
let fixture: ComponentFixture<TableComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [TableComponent],
imports: [HttpClientTestingModule, RouterModule.forRoot([])],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TableComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('retrieves all todos', inject([TodoService], (todoService: any) => {
todoService
.getTodoItems()
.subscribe((todo: Todo[]) => expect(todo.length).toBeGreaterThan(0));
}));
});
|
import 'package:flutter/material.dart';
import 'package:provides/Screen/Rest-api.dart';
class MyHome extends StatelessWidget {
const MyHome({super.key});
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
title: const Text(
"Amaar Raza",
style: TextStyle(fontSize: 27.0),
),
actions: [
IconButton(
onPressed: () {},
icon: const Icon(
Icons.shopping_bag,
size: 26,
)),
IconButton(
onPressed: () {},
icon: const Icon(
Icons.search,
size: 26,
)),
// Create a custom menu button
PopupMenuButton(
icon: Icon(Icons.menu),
itemBuilder: (context) {
return [
PopupMenuItem(
value: "Home",
child: IconButton(
onPressed: () {
Navigator.pushNamed(context, "/");
},
icon: const Icon(
Icons.shop,
size: 27,
color: Colors.pink,
),
)),
PopupMenuItem(
value: "Home",
child: IconButton(
onPressed: () {
Navigator.pushNamed(context, "/");
},
icon: const Icon(
Icons.shop,
size: 27,
color: Colors.pink,
),
)),
PopupMenuItem(
value: "Home",
child: IconButton(
onPressed: () {
Navigator.pushNamed(context, "/");
},
icon: const Icon(
Icons.shop,
size: 27,
color: Colors.pink,
),
)),
PopupMenuItem(
value: "Home",
child: IconButton(
onPressed: () {
Navigator.pushNamed(context, "/");
},
icon: const Icon(
Icons.shop,
size: 27,
color: Colors.pink,
),
)),
];
})
],
bottom: const TabBar(
physics: BouncingScrollPhysics(),
tabs: [
Tab(child: Text('Chat')),
Tab(child: Text('Status')),
Tab(child: Text('Calls')),
Tab(child: Text('Rest-Api'))
],
),
),
body: TabBarView(children: [
const Text("Hello from chat"),
const Text("Hello from status"),
const Text("Hello from calls"),
RestApi(),
]),
));
}
}
|
import Building from './5-building.js';
export default class SkyHighBuilding extends Building {
constructor(sqft, floors){
super(sqft);
if (!Number.isInteger(sqft)) throw new TypeError('sqft must be an Integer');
if (!Number.isInteger(floors)) throw new TypeError('floors must be an Integer');
this._floors = floors;
}
//getters
get sqft() {
return this._sqft;
}
get floors() {
return this._floors;
}
evacuationWarningMessage() {
return `Evacuate slowly the ${this._floors} floors`
}
}
|
<!-- @format -->
<template>
<div>
<system-bar class="mb-5" />
<drawer style="z-index: 9999999" v-if="drawer" />
<map-component />
<order-component
v-if="!orderProgress.status"
:carClasses="carClasses"
:demands="demands"
@demand-change="demands = $event"
:paymentMethods="paymentMethods"
@suggestFrom="suggestFrom"
@suggestTo="suggestTo"
/>
<order-progress v-if="orderProgress.status" />
<order-feedback v-if="orderFeedback.status" />
</div>
</template>
<script>
import { mapMutations, mapState } from "vuex";
import { Broadcast, Map, Order } from "../mixins";
import OrderFormComponent from "../components/view-component/form/OrderForm.component";
import MobileMapComponent from "../components/view-component/map/MobileMap.component";
import OrderProgressComponent from "../components/view-component/OrderProgressComponent";
import OrderFeedbackComponent from "../components/view-component/OrderFeedbackComponent";
import DialogueComponent from "../components/view-component/DialogueComponent";
export default {
name: "MobileIndex",
mixins: [Broadcast, Map, Order],
data() {
return {
suggestViewFrom: undefined,
suggestViewTo: undefined,
carClasses: [],
paymentMethods: [],
demands: [],
window: {
width: 0,
height: window.innerHeight - 30,
},
};
},
props: { initialClient: undefined, logoutRoute: undefined },
components: {
orderComponent: OrderFormComponent,
mapComponent: MobileMapComponent,
OrderProgress: OrderProgressComponent,
OrderFeedback: OrderFeedbackComponent,
dialogue: DialogueComponent,
},
computed: {
...mapState({
maps: "maps",
order: "order",
client: "client",
orderProgress: "orderProgress",
orderFeedback: "orderFeedback",
}),
drawer: {
get() {
return this.$store.state.drawer;
},
set(val) {
this.$store.state.drawer = val;
},
},
fromDisable: {
get() {
return this.$store.state.app.fromDisable;
},
set(value) {
this.$store.state.app.fromDisable = value;
},
},
toDisable: {
get() {
return this.$store.state.app.toDisable;
},
set(value) {
this.$store.state.app.toDisable = value;
},
},
broadcast: {
get() {
return this.$store.state.broadcast;
},
set(val) {
this.$store.state.broadcast = val;
},
},
},
methods: {
...mapMutations({
orderInit: "orderInit",
initClient: "initClient",
initMap: "initMap",
initOrderProgress: "initOrderProgress",
initOrderForm: "initOrderForm",
initDriver: "initDriver",
initCar: "initCar",
}),
suggestFrom() {
if (!this.suggestViewFrom) {
this.suggestViewFrom = new ymaps.SuggestView("from");
}
this.suggestViewFrom.events.add("select", e => {
if (this.suggestViewFrom) {
this.suggestViewFrom.destroy();
}
this.suggestViewFrom = null;
this.orderInit({ address_from: e.get("item").value });
ymaps.geocode(e.get("item").value).then(res => {
this.orderInit({ address_from_coordinates: res.geoObjects.get(0).geometry._coordinates });
});
});
},
suggestTo() {
if (!this.suggestViewTo) {
this.suggestViewTo = new ymaps.SuggestView("to");
}
this.suggestViewTo.events.add("select", e => {
this.suggestViewTo ? this.suggestViewTo.destroy() : null;
this.suggestViewTo = null;
this.orderInit({ address_to: e.get("item").value });
ymaps.geocode(e.get("item").value).then(res => {
this.orderInit({ address_to_coordinates: res.geoObjects.get(0).geometry._coordinates });
});
});
},
initSuggest() {
this.suggestFrom();
this.suggestTo();
},
handleResize() {
this.window.width = window.innerWidth;
this.window.height = window.innerHeight - 30;
},
hasGeoObjectsAddDriver(driver) {
if (!this.carGeoObjects) {
this.carGeoObjects = new ymaps.GeoObjectCollection();
this.addInGeoObject(driver);
this.maps.map.geoObjects.add(this.carGeoObjects);
}
this.carGeoObjects.add(this.createDriverMark(driver));
},
},
created() {
this.initialize();
window.addEventListener("resize", this.handleResize);
ymaps.ready(this.initSuggest);
this.broadcastEvents();
},
};
</script>
<style lang="scss" scoped>
/*#window-slide {*/
/* height: 100% !important;*/
/*}*/
</style>
|
import { useState } from "react";
import { getCategoriesApi, addCategoryApi, updateCategoryApi, deleteCategoryApi } from "../api/category";
import { useAuth } from "./useAuth";
export function useCategory() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const [categories, setCategories] = useState(null);
const { auth } = useAuth();
// Get all categories
const getCategories = async () => {
try {
setLoading(true);
const response = await getCategoriesApi();
setLoading(false);
setCategories(response);
} catch (error) {
setLoading(false);
setError(error);
}
}
// Add a new category
const addCategory = async (data) => {
try {
setLoading(true);
await addCategoryApi(data, auth.token);
setLoading(false);
} catch (error) {
setLoading(false);
setError(error);
}
}
// Update a category
const updateCategory = async (id, data) => {
try {
setLoading(true);
await updateCategoryApi(id, data, auth.token);
setLoading(false);
} catch (error) {
setLoading(false);
setError(error);
}
}
// Delete a category
const deleteCategory = async (id) => {
try {
setLoading(true);
await deleteCategoryApi(id, auth.token);
setLoading(false);
} catch (error) {
setLoading(false);
setError(error);
}
}
return {
loading,
error,
categories,
getCategories,
addCategory,
updateCategory,
deleteCategory
}
}
|
<p>This documentation applies to the version 20.4.</p>
<div class="callout callout--info">
<p class="callout__title">
<strong><span class="wysiwyg-font-size-large">React Native Bridge is a successor to the React Native SDK</span></strong>
</p>
<p>
The React Native SDK, which was developed earlier, will soon be end-of-life
and will no longer be maintained. Please use this (bridge) SDK for a more
complete and more tested version.
</p>
</div>
<p>
<span style="font-weight:400">This is the Countly SDK for React Native applications. It features bridging, meaning it includes all the functionalities that Android and iOS SDKs provide rather than having those functionalities as React Native code.</span>
</p>
<h1>Creating a new application</h1>
<p>
<span style="font-weight:400">In order to use the React Native SDK, please use the following commands to create a new React Native application.</span>
</p>
<pre><code class="shell">npm install -g react-native-cli # Install React Native
react-native init AwesomeProject # Create a new project
cd AwesomeProject # Go to that directory
react-native run-android # OR # Run the android project
react-native run-ios # Run the iOS project
# New terminal
adb reverse tcp:8081 tcp:8081 # Link Android port
npm start # Run the build server</code></pre>
<h1>Installing the Countly SDK</h1>
<p>
<span style="font-weight:400">Run the following snippet in the root directory of your React Native project to install the npm dependencies and link </span><strong>native libraries</strong><span style="font-weight:400">.</span>
</p>
<pre># Include the Countly Class in the file that you want to use.<br>npm install --save https://github.com/Countly/countly-sdk-react-native-bridge.git<br># OR <br>npm install --save [email protected]<br><br># Linking the library to your app<br><br># react-native < 0.60. For both Android and iOS<br>react-native link countly-sdk-react-native-bridge<br>cd node_modules/countly-sdk-react-native-bridge/ios/<br>pod install <br>cd ../../../<br><br># react-native >= 0.60 for iOS (Android will autolink)<br>cd ios <br>pod install<br>cd ..</pre>
<h1>Implementation</h1>
<p>
<span style="font-weight:400">We will need to call two methods (init and start) in order to set up our SDK. You may also like to specify other parameters at this step (i.e. whether logging will be used). These methods should only be called once during the app's lifecycle and should be done as early as possible. Your main App component's <code>componentDidMount</code>method may be a good place. </span>
</p>
<p>
<span style="font-weight:400">See the serverURL value in the code snippet below. If you are using the Countly Enterprise Edition trial servers, use <a href="https://try.count.ly" target="_self">https://try.count.ly</a></span><span style="font-weight:400">,</span><span style="font-weight:400"> </span><a href="https://us-try.count.ly/"><span style="font-weight:400">https://us-try.count.ly</span></a><span style="font-weight:400"> or </span><a href="https://asia-try.count.ly./"><span style="font-weight:400">https://asia-try.count.ly.</span></a><span style="font-weight:400"> In other words, use the domain from which you are accessing your trial dashboard.</span>
</p>
<p>
<span style="font-weight:400">If you use both Community Edition and Enterprise Edition, use your own domain name or IP address, such as </span><em><span style="font-weight:400">https://example.com</span></em><span style="font-weight:400"> or </span><em><span style="font-weight:400">https://IP</span></em><span style="font-weight:400"> (if SSL is setup).</span>
</p>
<pre><code class="javascript">import Countly from 'countly-sdk-react-native-bridge';
<br>// initialize
// modify serverURL to your own.
var serverURL = "https://mycompany.count.ly";
var appKey = "f0b2ac6919f718a13821575db28c0e2971e05ec5";
var deviceId = null; // or use some string that identifies current app user
Countly.init(serverURL, appKey, deviceId);
// configure other Countly parameters if needed
Countly.enableParameterTamperingProtection("salt");<br>Countly.enableLogging();
...<br><br>// start session tracking<br>Countly.start(); <br></code></pre>
<p>
<span style="font-weight:400">After init and start have been called once, you may use the commands in the rest of this document to send additional data and metrics to your server. </span>
</p>
<h1>User Location</h1>
<p>
<span>Countly allows you to send GeoLocation-based push notifications to your users. By default, the Countly Server uses the GeoIP database to deduce a user's location. However, if your app has a better way of detecting location, you may send this information to the Countly Server by using the <code>setLocationInit</code> or<code>setLocation</code> method.</span>
</p>
<div class="callout callout--info">
<p class="callout__title">
<span class="wysiwyg-font-size-large"><strong>Minimum Countly SDK Version</strong></span>
</p>
<p>
<span><code>setLocationInit</code></span> feature is only supported by the
minimum SDK version 20.04.7.
</p>
</div>
<p>
<span>Recommended using <code>setLocationInit</code> method before initialization to sent location. This include:</span>
</p>
<ul>
<li>
<code><span>countryCode</span></code><span> </span>a string in ISO 3166-1
alpha-2 format country code
</li>
<li>
<code>city</code><span> </span>a string specifying city name
</li>
<li>
<code>location</code><span> </span>a string comma separated latitude
and longitude
</li>
<li>
<code>IP</code><span> </span>a string specifying an IP address in IPv4
or IPv6 format
</li>
</ul>
<div>
<pre><span>var</span><span> </span><span>countryCode</span><span> = </span><span>"us"</span><span>; <br></span><span>var</span><span> </span><span>city</span><span> = </span><span>"Houston"</span><span>; <br></span><span>var</span><span> </span><span>latitude</span><span> = </span><span>"29.634933"</span><span>; <br></span><span>var</span><span> </span><span>longitude</span><span> = </span><span>"-95.220255"</span><span>; <br></span><span>var</span><span> </span><span>ipAddress</span><span> = </span><span>"103.238.105.167"</span><span>; </span><br><br><span>Countly</span><span>.</span><span>setLocationInit</span><span>(</span><span>countryCode</span><span>, </span><span>city</span><span>, </span><span>latitude</span><span> + </span><span>","</span><span> + </span><span>longitude</span><span>, </span><span>ipAddress</span><span>);</span></pre>
</div>
<p>
<span style="font-weight:400"><span>GeoLocation info recording methods may also be called at any time after the Countly SDK has started.<br>Use this <code>setLocation</code> method </span></span><span style="font-weight:400"></span>
</p>
<div>
<pre><span>var</span><span> </span><span>countryCode</span><span> = </span><span>"us"</span><span>; <br></span><span>var</span><span> </span><span>city</span><span> = </span><span>"Houston"</span><span>; <br></span><span>var</span><span> </span><span>latitude</span><span> = </span><span>"29.634933"</span><span>; <br></span><span>var</span><span> </span><span>longitude</span><span> = </span><span>"-95.220255"</span><span>; <br></span><span>var</span><span> </span><span>ipAddress</span><span> = </span><span>"103.238.105.167"</span><span>; </span><br><br><span>Countly</span><span>.</span><span>setLocation</span><span>(</span><span>countryCode</span><span>, </span><span>city</span><span>, </span><span>latitude</span><span> + </span><span>","</span><span> + </span><span>longitude</span><span>, </span><span>ipAddress</span><span>);</span></pre>
</div>
<p>
<span style="font-weight:400">The following will erase any cached location data from the device and stop further location tracking.</span>
</p>
<p>
<span style="font-weight:400">If, after disabling location, the <code>setLocation</code></span><span style="font-weight:400">is called with any non-null value, tracking will resume.</span>
</p>
<pre><code class="javascript">//disable location tracking
Countly.disableLocation();</code></pre>
<h1>Custom events</h1>
<p>
<span style="font-weight:400">You will find a quick summary on how to use custom events recording methods and what information they provide located below. For more information about how custom events and segmentations work, </span><a href="http://resources.count.ly/docs/custom-events"><span style="font-weight:400">review this guide</span></a><span style="font-weight:400"> first.</span>
</p>
<p>
<span style="font-weight:400">Note that all data passed to the Countly instance via the SDK or API should be in UTF-8.</span>
</p>
<pre><code class="javascript">// Example for sending basic custom event
var event = {"eventName":"basic_event","eventCount":1};
Countly.sendEvent(event);
// Example for event with sum
var event = {"eventName":"Event With Sum","eventCount":1,"eventSum":"0.99"};
Countly.sendEvent(event);
// Example for event with segment
var event = {"eventName":"Event With Segment","eventCount":1};
event.segments = {"Country" : "Germany", "Age" : "28"};
Countly.sendEvent(event);
// Example for event with segment and sum
var event = {"eventName":"Event With Sum And Segment","eventCount":1,"eventSum":"0.99"};
event.segments = {"Country" : "Germany", "Age" : "28"};
Countly.sendEvent(event);
// Timed events
// Basic timed event
Countly.startEvent("timedEvent");
Countly.endEvent("timedEvent");
// Timed event with a sum
Countly.startEvent("timedEvent");
var event = {
"eventName": "timedEvent",
"eventSum": "0.99"
};
Countly.endEvent(event);
// Timed event with segment
Countly.startEvent("timedEvent");
var event = {
"eventName": "timedEvent"
};
event.segments = {
"Country": "Germany",
"Age": "28"
};
Countly.endEvent(event);
// Timed event with segment, sum and count
Countly.startEvent("timedEvent");
var event = {
"eventName": "timedEvent",
"eventCount": 1,
"eventSum": "0.99"
};
event.segments = {
"Country": "Germany",
"Age": "28"
};
Countly.endEvent(event);
</code></pre>
<h1>User Profiles</h1>
<p>
<span style="font-weight:400">If you have any details about the user/visitor, you may provide Countly with that information. This will allow you to track each specific user on the "User Profiles" tab, which is available with Countly’s Enterprise Edition.</span>
</p>
<p>
<span style="font-weight:400">In order to set a user profile, use the code snippet below. After you send a user’s data, it may be viewed under Dashboard > User Profiles.</span>
</p>
<pre><code class="javascript">// Example for setting user data
var options = {};
options.name = "Nicola Tesla";
options.username = "nicola";
options.email = "[email protected]";
options.organization = "Trust Electric Ltd";
options.phone = "+90 822 140 2546";
options.picture = "http://www.trust.electric/images/people/nicola.png";
options.picturePath = "";
options.gender = "M";
options.byear = 1919;
Countly.setUserData(options);</code></pre>
<p>
<span style="font-weight:400">Countly also supports custom user properties where you can attach custom data for each user. In order to set or modify a user's data (e.g. increment, multiply, etc.), the following code sample may be used.</span>
</p>
<pre><code class="javascript">// examples for custom user properties
Countly.userData.setProperty("keyName", "keyValue"); //set custom property
Countly.userData.setOnce("keyName", 200); //set custom property only if property does not exist
Countly.userData.increment("keyName"); //increment value in key by one
Countly.userData.incrementBy("keyName", 10); //increment value in key by provided value
Countly.userData.multiply("keyName", 20); //multiply value in key by provided value
Countly.userData.saveMax("keyName", 100); //save max value between current and provided
Countly.userData.saveMin("keyName", 50); //save min value between current and provided
Countly.userData.setOnce("setOnce", 200);//insert value to array of unique values
Countly.userData.pushUniqueValue("type", "morning");//insert value to array of unique values
Countly.userData.pushValue("type", "morning");//insert value to array which can have duplicates
Countly.userData.pullValue("type", "morning");//remove value from array</code></pre>
<h1>Crash reporting</h1>
<p>
<span style="font-weight:400">With this feature, the Countly SDK will generate a crash report if your application crashes due to an exception and send it to the Countly server for further inspection.</span>
</p>
<p>
<span style="font-weight:400">If a crash report cannot be delivered to the server (e.g. no internet connection, unavailable server), then the SDK stores the crash report locally in order to try again at a later time.</span>
</p>
<p>
<span style="font-weight:400">You will need to call the following method before calling init in order to activate automatic crash reporting.</span>
</p>
<pre><code class="javascript">// Using countly crash reports
Countly.enableCrashReporting();<br>Countly.init(...);</code></pre>
<p>
<span style="font-weight:400">You may also add breadcrumb crash logs to your crash report using <code class="javascript">addCrashLog</code></span><span style="font-weight:400"> and catch and send exceptions manually yourself using <code class="javascript">logException</code></span><span style="font-weight:400">. Please review the example code below:</span>
</p>
<pre><code class="javascript">Countly.addCrashLog("User Performed Step A");
setTimeout(() => { Countly.addCrashLog("User Performed Step B");}, 1000);
setTimeout(() => { Countly.addCrashLog("User Performed Step C");}, 1500);
setTimeout(() => {
try {
var a = {};
var x = a.b.c; // this will throw an error.
} catch (exc) {
var stack = exc.stack.toString();
const customSegments = {"external_lib_version": "4.2.7", "theme": "dark"};
const nonfatal = true;
Countly.logException(stack, nonfatal, customSegments);
}
},2000);
</code></pre>
<p>
<span style="font-weight:400"><code class="javascript">logException</code>takes a string for the stack trace, a boolean flag indicating if the crash is considered fatal or not, and a segments dictionary to add additional data to your crash report.</span>
</p>
<h1>View tracking</h1>
<p>
<span style="font-weight:400">You may manually add your own views in your application, and each view will be visible under <code>Analytics > Views</code></span><span style="font-weight:400">. Below you may see two examples of sending a view using the <code>Countly.recordview</code></span><span style="font-weight:400"> function.</span>
</p>
<pre><code class="javascript">// record a view on your application
Countly.recordView("My Home Page");
Countly.recordView("Profile Page");</code></pre>
<p>
<span style="font-weight:400"><span>While tracking views, you may want to add custom segmentation to them.</span></span>
</p>
<pre><span style="font-weight:400"><span>// record view with segments<br>Countly.recordView("View with Segment", {"version": "1.0", "_facebook_version": "0.0.1"})</span></span></pre>
<h1>Application Performance Monitoring</h1>
<div class="callout callout--info">
<p class="callout__title">
<strong><span class="wysiwyg-font-size-large">Minimum Countly SDK Version</span></strong>
</p>
<p>
This feature is only supported by the minimum SDK version 20.04.7.
</p>
</div>
<p>
Performance Monitoring feature allows you to analyze your application's performance
on various aspects. For more details please see
<a href="https://support.count.ly/hc/en-us/articles/900000819806-Performance-monitoring" target="_self">Performance Monitoring documentation</a>.
</p>
<p>
Here is how you can utilize Performance Monitoring feature in your apps:
</p>
<p>First, you need to enable Performance Monitoring feature::</p>
<pre>Countly.<span>enableApm</span>(); <span>// Enable APM features.</span></pre>
<p>
With this, Countly SDK will start measuring some performance traces automatically.
Those include app foreground time, app background time. Additionally, custom
traces and network traces can be manually recorded.
</p>
<h2>Custom trace</h2>
<p>
<span><span class="Apple-converted-space">You may also measure any operation you want and record it using custom traces. First, you need to start a trace by using the <code class="objectivec">startTrace(traceKey)</code> method:</span></span>
</p>
<pre>Countly.<span>startTrace</span>(traceKey);</pre>
<p>
Then you may end it using the
<span><span class="Apple-converted-space"><code class="objectivec">endTrace(traceKey, customMetric)</code>method, optionally passing any metrics as key-value pairs:</span></span>
</p>
<pre>String traceKey = <span>"Trace Key"</span>;<br>Map<String, int> customMetric = {<br> <span>"ABC"</span>: <span>1233</span>,<br> <span>"C44C"</span>: <span>1337<br></span>};<br>Countly.<span>endTrace</span>(traceKey, customMetric);</pre>
<p>
The duration of the custom trace will be automatically calculated on ending. Trace
names should be non-zero length valid strings. Trying to start a custom
trace with the already started name will have no effect. Trying to end a
custom trace with already ended (or not yet started) name will have no effect.
</p>
<p>
You may also cancel any custom trace you started, using <span><span class="Apple-converted-space"><code class="objectivec">cancelTrace(traceKey)</code>method:</span></span>
</p>
<pre>Countly.cancelTrace(traceKey);</pre>
<p>
Additionally, if you need you may cancel all custom traces you started, using
<span><span class="Apple-converted-space"><code class="objectivec">clearAllTraces()</code>method:</span></span>
</p>
<pre>Countly.clearAllTraces(traceKey);</pre>
<h2>Network trace</h2>
<p>
You may record manual network traces using the<code><span>recordNetworkTrace(networkTraceKey, responseCode, requestPayloadSize, responsePayloadSize, startTime, endTime)</span></code> method.
</p>
<p>
A network trace is a collection of measured information about a network request.<br>
When a network request is completed, a network trace can be recorded manually
to be analyzed in the Performance Monitoring feature later with the following
parameters:
</p>
<p>
- <code>networkTraceKey</code>: A non-zero length valid string<br>
- <code>responseCode</code>: HTTP status code of the received response<br>
- <code>requestPayloadSize</code>: Size of the request's payload in bytes<br>
- <code>responsePayloadSize</code>: Size of the received response's payload in
bytes<br>
- <code>startTime</code>: UNIX time stamp in milliseconds for the starting time
of the request<br>
- <code>endTime</code>: UNIX time stamp in milliseconds for the ending time of
the request
</p>
<pre>Countly.<span>recordNetworkTrace</span>(networkTraceKey, responseCode, requestPayloadSize, responsePayloadSize, startTime, endTime);</pre>
<h1>Remote Config</h1>
<p>
<span style="font-weight:400"> Remote config allows you to modify how your app functions or looks by requesting key-value pairs from your Countly server. The returned values may be modified based on the user profile. For more details, please review this </span><a href="https://resources.count.ly/docs/remote-config"> <span style="font-weight:400">Remote Config documentation</span></a><span style="font-weight:400">. </span>
</p>
<pre><code class="javascript">// remoteConfigUpdate will update all remote config values
Countly.remoteConfigUpdate(function(data){
console.log(data);
});
// updateRemoteConfigForKeysOnly will update only those values which keyname are pass in array
Countly.updateRemoteConfigForKeysOnly(["test1"],function(data){
console.log(data);
});
// updateRemoteConfigExceptKeys will update only values except which keyname are pass in array
Countly.updateRemoteConfigExceptKeys(["test1"],function(data){
console.log(data);
});
// getRemoteConfigValueForKey will fetch remote config values for keyname sent
Countly.getRemoteConfigValueForKey("test1",function(data){
console.log(data);
});</code></pre>
<h1>Clearing Stored Remote Config values</h1>
<p>
<span style="font-weight:400">At some point, you might want to erase all the values downloaded from the server. To do so, you will need to call the following function:</span>
</p>
<pre><code class="javascript">Countly.remoteConfigClearValues();
</code></pre>
<h1>User Consent management</h1>
<p>
<span style="font-weight:400">In an effort to be compliant with GDPR and other data privacy regulations, Countly provides ways to toggle different Countly tracking features on/off depending on a user's given consent. To learn more about how Countly manages this issue and what capabilities we provide to our customers, please visit our guide on the </span><a href="https://resources.count.ly/docs/compliance-hub"><span style="font-weight:400">Compliance Hub plugin</span></a><span style="font-weight:400">. You may also find more information about how Countly helps organizations with GDPR regulations </span><a href="https://blog.count.ly/countly-the-gdpr-how-worlds-leading-mobile-and-web-analytics-platform-can-help-organizations-5015042fab27"><span style="font-weight:400">in this Countly blog post</span></a><span style="font-weight:400">.<br></span>
</p>
<p>
<span>Currently, available features with consent control are as follows</span>:
</p>
<ul>
<li>
sessions - tracking when, how often and how long users use your app
</li>
<li>events - allow sending custom events to the server</li>
<li>views - allow tracking which views user visits</li>
<li>location - allow sending location information</li>
<li>crashes - allow tracking crashes, exceptions and errors</li>
<li>
attribution - allow tracking from which campaign did user come
</li>
<li>
users - allow collecting/providing user information, including custom properties
</li>
<li>push - allow push notifications</li>
<li>star-rating - allow sending their rating and feedback</li>
<li>apm - allow application performance monitoring</li>
</ul>
<p>
<span style="font-weight:400">Since the React Native Bridge SDK employs our IOS and Android SDKs, you may also be interested in reviewing their relevant documentation on this topic (</span><a href="https://resources.count.ly/docs/countly-sdk-for-ios-and-os-x#section-consents"><span style="font-weight:400">here</span></a><span style="font-weight:400"> and </span><a href="https://resources.count.ly/docs/countly-sdk-for-android#section-user-consent-management"><span style="font-weight:400">here, </span></a><span style="font-weight:400">respectively).</span>
</p>
<p>
<span style="font-weight:400">Next we will go over the methods that are available in this SDK.</span>
</p>
<table>
<tbody>
<tr>
<th>Method</th>
<th>Parameters / Examples</th>
<th>Description</th>
</tr>
<tr>
<td>
<code>setRequiresConsent</code>
</td>
<td>boolean</td>
<td>
<p>
<span style="font-weight:400">The requirement for checking consent is disabled by default. To enable it, you will have to call <code>setRequiresConsent</code></span><span style="font-weight:400">with <code>true</code></span><span style="font-weight:400">before initializing Countly. You may also pass a consent flag as true/false when you call the <code>Countly.init</code></span><span style="font-weight:400">.</span>
</p>
</td>
</tr>
<tr>
<td>
<code>giveConsentInit</code>
</td>
<td>string array of strings</td>
<td>
<p>
<span style="font-weight:400">To add consent for a single feature (string parameter) or a subset of features (array of strings parameter). Use this method for giving consent before </span><span style="font-weight:400">initializing.<br><br><strong>This feature is only supported by the minimum SDK version 20.04.7.</strong><br></span>
</p>
</td>
</tr>
<tr>
<td>
<code>giveConsent</code>
</td>
<td>string array of strings</td>
<td>
<p>
<span style="font-weight:400">To add consent for a single feature (string parameter) or a subset of features (array of strings parameter). Use this method if want to give consent after </span><span style="font-weight:400">initializing.</span>
</p>
</td>
</tr>
<tr>
<td>
<code>removeConsent</code>
</td>
<td>string array of strings</td>
<td>
<p>
<span style="font-weight:400">To remove consent for a single feature (string parameter) or a subset of features (array of strings parameter).</span>
</p>
</td>
</tr>
<tr>
<td>
<code>giveAllConsent</code>
</td>
<td>none</td>
<td>To give consent for all available features.</td>
</tr>
<tr>
<td>
<code>removeAllConsent</code>
</td>
<td>none</td>
<td>To remove consent for all available features.</td>
</tr>
</tbody>
</table>
<pre><code class="javascript">// Usage examples
Countly.setRequiresConsent(true);
// for a single feature
Countly.giveConsentInit("events");
Countly.giveConsent("events");
Countly.removeConsent("events");
// for a subset of features
Countly.giveConsentInit(["events", "views", "star-rating", "crashes"]);
Countly.giveConsent(["events", "views", "star-rating", "crashes"]);
Countly.removeConsent(["events", "views", "star-rating", "crashes"]);
// for all available features
Countly.giveAllConsent();
Countly.removeAllConsent();</code></pre>
<p>
<span style="font-weight:400">The string values corresponding to the features that will be used in the <code>giveConsent</code> or <code>removeConsent</code></span><span style="font-weight:400">methods may be found </span><a href="https://resources.count.ly/docs/sdk-development-guide#section-exposing-available-features-for-consent"><span style="font-weight:400">here</span></a><span style="font-weight:400">. In addition, please review our platform SDK documents if the feature is applicable or not for that platform.</span>
</p>
<h1>Device ID</h1>
<p>
<span style="font-weight:400"><span>When the SDK is initialized for the first time and no device ID is provided, a device ID will be generated by SDK.</span></span><span style="font-weight:400"><span></span></span>
</p>
<p>
<span style="font-weight:400"><span>For iOS: the device ID generated by SDK is the Identifier For Vendor (IDFV)<br>For Android: the device ID generated by SDK is the OpenUDID or Google Advertising ID</span></span>
</p>
<p>
<span style="font-weight:400"><span>You may provide your own custom device ID when</span> initializing the SDK</span>
</p>
<pre>Countly.<span>init</span>(<span>SERVER_URL</span>, <span>APP_KEY, DEVICE_ID</span>)</pre>
<h2>
Changing the Device ID<span style="font-weight:400"></span>
</h2>
<p>
<span style="font-weight:400">You may configure/change the device ID anytime using:<br></span>
</p>
<pre>Countly.<span>changeDeviceId</span>(DEVICE_ID, <span>ON_SERVER</span>);</pre>
<p>
<span>You may either allow the device to be counted as a new device or merge existing data on the server. </span>If
the<code>onServer</code><span> </span>bool is set to <code>true</code>,
<span>the old device ID on the server will be replaced with the new one, and data associated with the old device ID will be merged automatically.<br>Otherwise, if <code>onServer</code> bool is set to <code>false</code>, the device will be counted as a new device on the server.<br></span>
</p>
<h2 id="temporary-device-id" class="anchor-heading">Temporary Device ID</h2>
<p>
You may use a temporary device ID mode for keeping all requests on hold until
the real device ID is set later.
</p>
<p>
You can enable temporary device ID
<span style="font-weight:400">when initializing the SDK:</span>
</p>
<pre>Countly.<span>init</span>(<span>SERVER_URL</span>, <span>APP_KEY, "TemporaryDeviceID"</span>)</pre>
<p>To enable a temporary device ID after init, you would call:</p>
<pre>Countly.<span>changeDeviceId</span>("TemporaryDeviceID", <span>ON_SERVER</span>);</pre>
<p>
<strong>Note:</strong> When passing<span> </span><code>TemporaryDeviceID</code><span> </span>for<span> </span><code>deviceID</code><span> </span>parameter,
argument for<span> </span><code>onServer</code>parameter does not matter.
</p>
<p>
As long as the device ID value is<span> </span><code>TemporaryDeviceID</code>,
the SDK will be in temporary device ID mode and all requests will be on hold,
but they will be persistently stored.
</p>
<p>
When in temporary device ID mode, method calls for presenting feedback widgets
and updating remote config will be ignored.
</p>
<p>
Later, when the real device ID is set using<span> </span><code>Countly.<span>changeDeviceId</span>(DEVICE_ID, <span>ON_SERVER</span>);</code><span> </span>method,
all requests which have been kept on hold until that point will start with the
real device ID
</p>
<h1>Enabling/disabling logging</h1>
<p>
<span style="font-weight:400">If logging is enabled, our SDK will then print out debug messages regarding its internal state and problems encountered. Logging is disabled by default. Enabling it during development is also advised. Enabling it before init is recommended so you may see the initialization process logs.</span>
</p>
<pre><code class="javascript">Countly.enableLogging();<br> Countly.init(...);
...<br> // to disable it again later
Countly.disableLogging();
</code></pre>
<h1>Forcing HTTP POST</h1>
<p>
<span style="font-weight:400">If the data sent to the server is short enough, the SDK will use HTTP GET requests. In the event you would like an override so that HTTP POST may be used in all cases, call the "setHttpPostForced" function after you have called "init". You may use the same function later in the app’s life cycle to disable the override. This function has to be called every time the app starts.</span>
</p>
<pre><code class="javascript">
// enabling the override
Countly.setHttpPostForced(true);
// disabling the override
Countly.setHttpPostForced(false);</code></pre>
<h1>Checking if init has been called</h1>
<p>
<span style="font-weight:400">You may use the following function in the event you would like to check if init has been called:</span>
</p>
<pre><code class="javascript">Countly.isInitialized().then(result => console.log(result)); // true or false
</code></pre>
<h1>Checking if onStart has been called</h1>
<p>
<span style="font-weight:400">For some Android applications there might be a use case where the developer would like to check if the Countly SDK onStart function has been called. To do so, they may use the following call:</span>
</p>
<pre><code class="javascript">Countly.hasBeenCalledOnStart().then(result => console.log(result)); // true or false </code></pre>
<h1>Rich Push Notifications</h1>
<p>
<span style="font-weight:400">Please first check our </span><a href="https://resources.count.ly/docs/countly-push-guide"><span style="font-weight:400">Push Notifications Guide</span></a><span style="font-weight:400"> to see how you can use this feature. Since Android and IOS handles notifications differently (from how you can send them externally to how they are handled in native code), we need to provide different instructions for these two platforms.</span>
</p>
<h1>Android Setup and Usage of Push Notifications</h1>
<p>
The following setup code is required starting from version 20.4.5.
</p>
<ol>
<li>
First thing you need to do is a FCM id and a google-services.json file.
You would input that FCM id into your apps configuration in your countly
dashboard. You also need to copy your google-services.json file to your android
apps directory, which most likely is in "./android/app".
</li>
<li>
You need to add firebase dependencies to your android apps gradle file, which
most likely is located in "./android/app/build.gradle", so start by opening
that file.
</li>
<li>
Inside the dependency section add the "firebase-messaging" dependency
with a call similar to "implementation 'com.google.firebase:firebase-messaging:20.1.7'"
</li>
<li>
At the bottom of your gradle file add this line "apply plugin: 'com.google.gms.google-services'"
</li>
<li>
Open you android projects gradle file, which most likely is located in "./android/build.gradle"
</li>
<li>
Add the following call in the dependency section "classpath 'com.google.gms:google-services:3.2.0'"
</li>
</ol>
<h1>JS Push Method Implementation</h1>
<p>
<span>First, when setting up push for the React Native SDK, you would first select the push token mode. This would allow you to choose either test or production modes, </span>push
token mode should be set before init.
</p>
<pre>// Important call this method before init method<br>Countly.pushTokenType(Countly.messagingMode.DEVELOPMENT, "Channel Name", "Channel Description");<br>// Countly.messagingMode.DEVELOPMENT<br>// Countly.messagingMode.PRODUCTION<br>// Countly.messagingMode.ADHOC</pre>
<p>
<span>When you are finally ready to initialise Countly push, you would call Countly.askForNotificationPermission(), this function should be call after init.</span>
</p>
<pre>// Call this method any time.<br>Countly.askForNotificationPermission();<br>// This method will ask for permission, <br>// and send push token to countly server.</pre>
<p>
React Native JS code to receive notification data. Call anywhere or event before
init.
</p>
<pre>Countly.registerForNotification(function(theNotification){<br>console.log(JSON.stringify(theNotification));<br>});</pre>
<h1>iOS Push Notification Documentation</h1>
<p class="has-line-data" data-line-start="2" data-line-end="3">
Note: This documentation assumes, that you have created the necessary certificate
and you have proper app bundle id.
</p>
<p class="has-line-data" data-line-start="4" data-line-end="5">
STEP 1: Make sure you have proper app bundle id and team selected.
</p>
<p class="has-line-data" data-line-start="6" data-line-end="12">
STEP 2: Add Capabilities<br>
1. Push Notification<br>
2. Background
Mode - Remote Notifications<br>
Go into
your AwesomeProject/ios dir and open AwesomeProject.xcworkspace workspace.
Select the top project “AwesomeProject” and select the “Signing & Capabilities”
tab. Add 2 new Capabilities using “+” button:<br>
Background
Mode capability and tick Remote Notifications.<br>
Push
Notifications capability
</p>
<h1>
<img src="/hc/article_attachments/900001150986/Screenshot_2020-05-05_at_1.43.11_PM.png" alt="Screenshot_2020-05-05_at_1.43.11_PM.png">
</h1>
<p class="has-line-data" data-line-start="13" data-line-end="14">
<img src="/hc/article_attachments/900001151086/Screenshot_2020-05-05_at_1.43.21_PM.png" alt="Screenshot_2020-05-05_at_1.43.21_PM.png">
</p>
<p class="has-line-data" data-line-start="13" data-line-end="14">
<img src="/hc/article_attachments/900001153423/Screenshot_2020-05-05_at_1.43.36_PM.png" alt="Screenshot_2020-05-05_at_1.43.36_PM.png">
</p>
<p class="has-line-data" data-line-start="13" data-line-end="14">
<img src="/hc/article_attachments/900001151106/Screenshot_2020-05-05_at_1.43.49_PM.png" alt="Screenshot_2020-05-05_at_1.43.49_PM.png">
</p>
<p>STEP 3: Place below code in there respective files.</p>
<p>### AppDelegate.m</p>
<p>
Add header file<br>
`#import "CountlyReactNative.h"`<br>
`#import <UserNotifications/UserNotifications.h>`
</p>
<p>
<br>
Before `@end` add these methods:
</p>
<pre> -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse
*)response withCompletionHandler:(void (^)(void))completionHandler{<br>
NSLog(@"didReceiveNotificationResponse");<br>
NSDictionary *notification = response.notification.request.content.userInfo;<br>
[CountlyReactNative onNotification: notification];<br>
completionHandler();<br>
}
//Called when a notification is delivered to a foreground app.<br>
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification
*)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions
options))completionHandler<br>
{<br>
NSLog(@"didReceiveNotificationResponse");<br>
NSDictionary *userInfo = notification.request.content.userInfo;<br>
[CountlyReactNative onNotification: userInfo];<br>
completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert
| UNAuthorizationOptionBadge);<br>
}
</pre>
<h1>Rich Push Notification</h1>
<p class="has-line-data" data-line-start="61" data-line-end="71">
STEP 1: Creating Notification Service Extension<br>
Editor -> Add Target -><br>
Make
sure <code>ios</code> is selected<br>
Make
sure <code>Notification Service Extension</code> is selected<br>
Click
<code>Next</code><br>
Enter
Product Name e.g. <code>CountlyNSE</code><br>
Language
<code>Objective-C</code><br>
Click
<code>Finish</code><br>
It will
ask for a modal / popup <code>Activate “CountlyNSE” scheme?</code><br>
Choose
<code>Cancel</code>
</p>
<p class="has-line-data" data-line-start="72" data-line-end="81">
<img src="/hc/article_attachments/900001153503/b0b0f12-f62249f-screen-1.png" alt="b0b0f12-f62249f-screen-1.png">
</p>
<p class="has-line-data" data-line-start="72" data-line-end="81">
<img src="/hc/article_attachments/900001153523/04c2353-17d2fec-screen-2.png" alt="04c2353-17d2fec-screen-2.png">
</p>
<p class="has-line-data" data-line-start="72" data-line-end="81">
STEP 2: Adding Compile Source<br>
Under <code>TARGETS</code> select <code>CountlyNSE</code><br>
Select
<code>Build Phases</code><br>
Expand
<code>Compile Sources</code><br>
Drag
and Drop <code>CountlyNotificationService.h</code> and
<code>CountlyNotificationService.m</code> file<br>
Note:
Make sure you have checked "Copy if necessary"<br>
Note:
You may also find this file in <code>Xcode</code> under
<code>Pods(Project) -> Pods(Folder) -> Countly</code><br>
Note:
You may also find this file in <code>Finder</code> under
<code>AwesomeProject/ios/Pods/Countly</code><br>
Note:
You may also find this file in <code>Xcode</code> under
<code>AwesomeProject(Project) -> Libraries(Folder) -> countly-sdk-react-native-bridge(Project)->src(Folder)</code><br>
Note:
You may also find this file in <code>Finder</code> under
<code>node_modules/countly-sdk-react-native-bridge/ios/Pods/Countly</code>
</p>
<p class="has-line-data" data-line-start="82" data-line-end="86">
<img src="/hc/article_attachments/900001153563/Screenshot_2020-05-05_at_1.44.05_PM.png" alt="Screenshot_2020-05-05_at_1.44.05_PM.png">
</p>
<p class="has-line-data" data-line-start="82" data-line-end="86"> </p>
<p class="has-line-data" data-line-start="82" data-line-end="86">
STEP 3: Updating NotificationService file<br>
Under
<code>AwesomeProject(Project) -> CountlyNSE(Folder) -> NotificationService.m</code><br>
Add
import header <code>#import "CountlyNotificationService.h"</code><br>
Add
the following line at the end of
<code>didReceiveNotificationRequest:withContentHandler:</code>
</p>
<pre><code> - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler
{
self.contentHandler = contentHandler;
self.bestAttemptContent = [request.content mutableCopy];
//delete existing template code, and add this line
[CountlyNotificationService didReceiveNotificationRequest:request withContentHandler:contentHandler];
}
Note: Please make sure you configure App Transport Security setting in extension's Info.plist file also, just like the main application. Otherwise media attachments from non-https sources can not be loaded.
Note: Please make sure you check Deployment Target version of extension target is 10, not 10.3 (or whatever minor version Xcode set automatically). Otherwise users running iOS versions lower than Deployment Target value can not get rich push notifications.
Note: To send push messages to applications that are Debug build use Countly.messagingMode.DEVELOPMENT, for App Store built ones use Countly.messagingMode.PRODUCTION, and for TestFlight/Ad Hoc builds use Countly.messagingMode.ADHOC. </code></pre>
<h1>Attribution analytics & install campaigns </h1>
<div class="callout callout--info">
<p class="callout__title">
<strong><span class="wysiwyg-font-size-large">Minimum Countly SDK Version</span></strong>
</p>
<p>
This feature is only supported by the minimum SDK version 20.04.6.
</p>
</div>
<p>
<a href="https://count.ly/attribution-analytics">Countly Attribution Analytics</a>
allows you to measure your marketing campaign performance by attributing installs
from specific campaigns. This feature is available for the Enterprise Edition.
</p>
<p>Call this before init.</p>
<pre><span>// Enable to measure your marketing campaign performance by attributing installs from specific campaigns.</span><br>Countly.<span>enableAttribution</span>();</pre>
<div class="callout callout--info">
<p class="callout__title">
<strong><span class="wysiwyg-font-size-large">Minimum Countly SDK Version</span></strong>
</p>
<p>
This feature is only supported by the minimum SDK version 20.04.8.
</p>
</div>
<p>
<span>From version 20.04.8+ for iOS use <code><span style="font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif">Countly</span><span style="font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif">.</span><span style="font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif">recordAttributionID("IDFA")</span></code></span><span style="font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif"> function instead of <span><code>Countly.enableAttribution()</code></span></span>
</p>
<p>
<span>You can use <code><span style="font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif">Countly</span><span style="font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif">.</span><span style="font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif">recordAttributionID</span></code> function to specify IDFA for campaign attribution</span>
</p>
<pre><span><span style="font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif">Countly</span><span style="font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif">.</span><span style="font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif">recordAttributionID("</span>IDFA_VALUE_YOU_GET_FROM_THE_SYSTEM");</span><span></span></pre>
<p>
<span>For iOS 14+ apple changes regarding Application tracking, you need to ask the user for permission to track Application.</span><span></span>
</p>
<p>
<span>For IDFA you can use this plugin, this plugin also supports iOS 14+ changes for Application tracking permission:<br></span><span><a href="https://github.com/ijunaid/react-native-advertising-id.git">https://github.com/ijunaid/react-native-advertising-id.git</a></span>
</p>
<p>
<span>Here is how to use this plugin with Countly attribution feature:</span>
</p>
<div>
<pre>npm install --save <a href="https://github.com/ijunaid/react-native-advertising-id.git">https://github.com/ijunaid/react-native-advertising-id.git</a><br><br>cd ./ios<br>pod install<br><br><strong>NSUserTrackingUsageDescription</strong><br>Add "Privacy - Tracking Usage Description" in your ios info.plist file.<br><br><strong>#Example Code for Countly attribution feature to support iOS 14+.</strong><br><br>import RNAdvertisingId from 'react-native-advertising-id';<br><br>if (Platform.OS.match("ios")) {<br>RNAdvertisingId.getAdvertisingId()<br>.then(response => {<br>Countly.recordAttributionID(response.advertisingId);<br>})<br>.catch(error => console.error(error));<br>}<br>else {<br>Countly.enableAttribution(); // Enable to measure your marketing campaign performance by attributing installs from specific campaigns.<br>}</pre>
</div>
<h1>Getting user feedback</h1>
<p>
<span style="font-weight:400">There are two ways of getting feedback from your users: Star-rating dialog and the feedback widget.</span>
</p>
<p>
<span style="font-weight:400">Star-rating dialog allows users to give feedback as a rating from 1 through 5. The feedback widget allows you to receive the same 1 through 5 rating and also a text comment.</span>
</p>
<h2>
<strong>Feedback widget</strong>
</h2>
<p>
<span style="font-weight:400">The feedback widget displays a server configured widget to your user devices.</span>
</p>
<div class="img-container">
<img src="https://count.ly/images/guide/ea55d24-072bb00-t1.png">
</div>
<p>
<span style="font-weight:400">It's possible to configure any of the shown text fields and replace them with a custom string of your choice.</span>
</p>
<p>
<span style="font-weight:400">In addition to a 1 through 5 rating, it is possible for users to leave a text comment and an email, should the user like to be contacted by the app developer.</span>
</p>
<p>
<span style="font-weight:400">Trying to show the rating widget is a single call, however, there is a two-set process underneath. Before it is shown, the SDK tries to contact the server to get more information about the dialog. Therefore, a network connection to it is needed.</span>
</p>
<p>
<span style="font-weight:400">You may try to display the widget after you have initialized the SDK. To do so, you will first need to get the widget ID from your server:</span>
</p>
<div class="img-container">
<img src="https://count.ly/images/guide/f773cf4-2dd58c6-t2.png">
</div>
<p>
<span style="font-weight:400">You may call the function to show the widget popup using the widget ID:</span>
</p>
<pre><code class="javascript">Countly.showFeedbackPopup("WidgetId", "Button Text");</code></pre>
<h1>Star-rating dialog</h1>
<p>
<span style="font-weight:400">Star-rating integration provides a dialog for getting users’ feedback about the application. It contains a title, a simple message explaining its purpose, a 1 through 5-star meter for getting users rating, and a dismiss button in case the user does not want to give a rating.</span>
</p>
<p>
<span style="font-weight:400">This star rating has nothing to do with Google Play Store ratings and reviews. It is simply for getting a brief feedback from your users to be displayed on the Countly dashboard. If the user dismisses the star-rating dialog without giving a rating, the event will not be recorded.</span>
</p>
<pre><code class="javascript">Countly.showStarRating();</code></pre>
<h1>Native C++ Crash Reporting</h1>
<p>
<span style="font-weight:400">If you have some C++ libraries in your Android app, the React Native Bridge SDK allows you to record possible crashes in your Countly server by integrating the <code>sdk-native</code></span><span style="font-weight:400">developed within our </span><a href="https://github.com/Countly/countly-sdk-android"><span style="font-weight:400">Android SDK</span></a><span style="font-weight:400">. You may receive more information on how this works </span><a href="https://resources.count.ly/docs/countly-sdk-for-android#section-native-c-crash-reporting"><span style="font-weight:400">here</span></a><span style="font-weight:400">.</span>
</p>
<p>
<span style="font-weight:400">As this feature is optional, you will need to uncomment some parts in our SDK files in order to make it available. First, go to <code>android/build.gradle</code></span><span style="font-weight:400">and add the package dependency (all file paths in this section are given relative to the <code>countly-sdk-react-native-bridge</code></span><span style="font-weight:400">which was <code>npm</code></span><span style="font-weight:400">installed above):</span>
</p>
<pre><code class="shell">dependencies {
implementation 'ly.count.android:sdk-native:19.02.3'
}</code></pre>
<p>
<span style="font-weight:400">Next, uncomment the following in the <code>android/src/main/java/ly/count/android/sdk/react/CountlyReactNative.java</code></span><span style="font-weight:400">file:</span>
</p>
<pre><code class="java">import ly.count.android.sdknative.CountlyNative;
@ReactMethod
public void initNative(){
CountlyNative.initNative(getReactApplicationContext());
}
@ReactMethod
public void testCrash(){
CountlyNative.crash();
}
</code></pre>
<p>
<span style="font-weight:400">Now modify <code>Countly.js</code></span><span style="font-weight:400">to connect from JS to these new methods:</span>
</p>
<pre><code class="javascript">Countly.initNative = function(){
CountlyReactNative.initNative();
}
Countly.testCrash = function(){
CountlyReactNative.testCrash();
}</code></pre>
<p>
<span style="font-weight:400">If you are using our sample app in <code>example/App.js</code></span><span style="font-weight:400">,</span><span style="font-weight:400"> you may also uncomment the following parts in it for easy testing:</span>
</p>
<pre><code class="javascript">initNative(){
Countly.initNative();
};
testCrash(){
Countly.testCrash();
}
// ...
< Button onPress = { this.initNative } title = "Init Native" color = "#00b5ad">
< Button onPress = { this.testCrash } title = "Test Native Crash" color = "crimson">
</code></pre>
<p>
<span style="font-weight:400">We suggest calling <code>Countly.initNative()</code></span><span style="font-weight:400">;</span><span style="font-weight:400"> as soon as your app is initialized to be able to catch setup time crashes. Sending crash dump files to the server will be taken care of by the Android SDK during the next app initialization. We also provide a gradle plugin which automatically uploads symbol files to your server (these are needed for the symbolication of crash dumps). You may integrate it to your React Native project as explained in the relevant Android documentation </span><a href="https://resources.count.ly/docs/countly-sdk-for-android#section-native-c-crash-reporting"><span style="font-weight:400">page</span></a><span style="font-weight:400">.</span>
</p>
<p>
<span style="font-weight:400">This is what the debug logs will look like if you are going to use this feature:</span>
</p>
<pre><code class="text">$ adb logcat -s Countly:V countly_breakpad_cpp:V
# when Countly.initNative() is called
D/countly_breakpad_cpp(123): breakpad initialize succeeded. dump files will be saved at /Countly/CrashDumps
# when a crash occurs (you may trigger one by Countly.testCrash())
D/countly_breakpad_cpp(123): DumpCallback started
D/countly_breakpad_cpp(123): DumpCallback ==> succeeded path=/Countly/CrashDumps/30f6d9b8-b3b2-1553-2efe0ba2-36588990.dmp
# when app is run again after the crash
D/Countly (124): Initializing...
D/Countly (124): Checking for native crash dumps
D/Countly (124): Native crash folder exists, checking for dumps
D/Countly (124): Crash dump folder contains [1] files
D/Countly (124): Recording native crash dump: [30f6d9b8-b3b2-1553-2efe0ba2-36588990.dmp]</code></pre>
<h3>Pinned Certificate (Call this method before init)</h3>
<h4>Terminal</h4>
<pre>openssl s_client -connect try.count.ly:443 -showcerts</pre>
<p>
Run the above command and copy the content inside begin certificate and end certificate.
</p>
<p>
Example files are here:<br>
<a href="https://github.com/Countly/countly-sdk-react-native-bridge/blob/dev-nicolson/example/android.count.ly.cer">https://github.com/Countly/countly-sdk-react-native-bridge/blob/master/example/android.count.ly.cer</a><br>
<a href="https://github.com/Countly/countly-sdk-react-native-bridge/blob/dev-nicolson/example/ios.count.ly.cer">https://github.com/Countly/countly-sdk-react-native-bridge/blob/master/example/ios.count.ly.cer</a>
</p>
<p>
Both files are different, android only needs the cert string, iOS needs the entire
.cer file.
</p>
<h4>Android</h4>
<pre>cd AwesomeProject<br>ls<br>count.ly.cer<br>mkdir -p ./android/app/src/main/assets/<br>cp ./count.ly.cer ./android/app/src/main/assets/</pre>
<h4>iOS</h4>
<pre>open ./ios/AwesomeProject.xcworkspace<br>Right click on AwesomeProject and select `New Group` (ScreenShot 1)<br>Name it `Resources`<br>Drag and Drop count.ly.cer file under that folder (ScreenShot 2)<br>Make sure copy bundle resources has your certificate (Screenshot 4).</pre>
<pre><br><img src="/hc/article_attachments/900002229303/Screenshot_2020-07-07_at_11.39.02_AM.png" alt="Screenshot_2020-07-07_at_11.39.02_AM.png"><br><img src="/hc/article_attachments/900001515963/ScreenShot_Pinned_Certificate_1.png" alt="ScreenShot_Pinned_Certificate_1.png"></pre>
<p>
<img src="/hc/article_attachments/900001515983/Screenshot_Pinned_Certificate_2.png" alt="Screenshot_Pinned_Certificate_2.png">
</p>
<pre><img src="/hc/article_attachments/900002229363/Screenshot_2020-07-07_at_11.39.40_AM.png" alt="Screenshot_2020-07-07_at_11.39.40_AM.png"></pre>
<h4>JS</h4>
<pre>Countly.pinnedCertificates("count.ly.cer");</pre>
<p>
Note: "count.ly.cer" is the name of the file. Replace this file with the one
you have.
</p>
|
import React from "react";
import { createBrowserRouter } from "react-router-dom";
import {
Batch,
Login,
Employees,
NotFound,
ChangePassword,
Orders,
} from "~/components/pages";
import MainLayout from "~/components/layouts/MainLayout";
import ErrorBoundary from "~/components/pages/ErrorBoundary";
const baseRouter = [
{
path: "/login",
element: <Login />,
},
{
path: "*",
element: <NotFound />,
},
];
const routerList = [
{
path: "/",
element: <Batch />,
},
{
path: "/employees",
element: <Employees />,
},
{
path: "/orders",
element: <Orders />,
},
{
path: "/change-password",
element: <ChangePassword />,
},
];
const devRouter = routerList.map((router) => {
return {
...router,
element: <MainLayout>{router.element}</MainLayout>,
};
});
const prodRouter = routerList.map((router) => {
return {
...router,
element: (
<ErrorBoundary>
<MainLayout>{router.element}</MainLayout>
</ErrorBoundary>
),
};
});
const routers =
process.env.NODE_ENV === "development"
? [...baseRouter, ...devRouter]
: [...baseRouter, ...prodRouter];
export default createBrowserRouter(routers);
|
// Template ID, Device Name and Auth Token are provided by the Blynk.Cloud
// See the Device Info tab, or Template settings
#define BLYNK_TEMPLATE_ID "TMPL873aSK-z"
#define BLYNK_DEVICE_NAME "MULTIPARAMETER VOLTAGE SENSING DEVICE"
#define BLYNK_AUTH_TOKEN "CqbCjamxV35uHfayr02WDDWgKbCmfKPp"
// Comment this out to disable prints and save space
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <PZEM004Tv30.h>
PZEM004Tv30 pzem(D1,D2);
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define button1 D5
#define button2 D6
#define button3 D7
boolean buttons1=true;
Multiparameter Voltage Sensing Device
Department of Electronics and Communication Engineering,AJCE
boolean buttons2=true;
boolean buttons3=true;
char auth[] = BLYNK_AUTH_TOKEN;
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "IOT";
char pass[] = "12345678";
BlynkTimer timer;
// This function sends Arduino's up time every second to Virtual Pin (5).
// In the app, Widget's reading frequency should be set to PUSH. This means
// that you define how often to send data to Blynk App.
void senddata()
{
// You can send any value at any time.
// Please don't send more that 10 values per second.
buttons1=digitalRead(button1);
buttons2=digitalRead(button2);
buttons3=digitalRead(button3);
if(buttons1==0)
{
float voltage = pzem.voltage();
lcd.clear();
lcd.setCursor(0,0);
lcd.print("voltage : ");
lcd.setCursor(10,0);
lcd.print(voltage);
lcd.print("V");
double current = pzem.current();
lcd.setCursor(0,1);
lcd.print("current : ");
lcd.setCursor(6,1);
lcd.setCursor(10,1);
lcd.print(current);
lcd.print("A");
delay(3000);
}
if(buttons2==0)
{
float power = pzem.power();
lcd.clear();
lcd.setCursor(0,0);
lcd.print("power : ");
lcd.setCursor(8,0);
lcd.print(power);
lcd.print("W");
float energy = pzem.energy();
lcd.setCursor(0,1);
lcd.print("energy : ");
//lcd.setCursor(10,1);
lcd.print(energy);
lcd.print("kWh");
delay(3000);
}
if(buttons3==0)
{
float frequency = pzem.frequency();
lcd.clear();
lcd.setCursor(0,0);
lcd.print("frequency : ");
lcd.setCursor(12,0);
lcd.print(frequency);
lcd.print("Hz");
float pf = pzem.pf();
lcd.setCursor(0,1);
lcd.print("pf : ");
lcd.setCursor(8,0);
lcd.print(pf);
delay(3000);
}
float voltage = pzem.voltage();
Blynk.virtualWrite(V0,voltage);
Serial.print("Voltage: ");
Serial.print(voltage);
Serial.println("V");
lcd.setCursor(0,0);
lcd.print("voltage : ");
lcd.setCursor(10,0);
lcd.print(voltage);
lcd.print("V");
delay(500);
lcd.clear();
double current = pzem.current();
Blynk.virtualWrite(V1,current);
Serial.print("Current: ");
Serial.print(current);
Serial.println("A");
lcd.setCursor(0,0);
lcd.print("current : ");
lcd.setCursor(10,0);
lcd.print(current); lcd.print("A");
delay(500);
lcd.clear();
float power = pzem.power();
Blynk.virtualWrite(V2,power);
Serial.print("Power: ");
Serial.print(power);
Serial.println("W");
lcd.setCursor(0,0);
lcd.print("power : ");
lcd.print(power);
lcd.print("W");
delay(500);
lcd.clear();
float energy = pzem.energy();
Blynk.virtualWrite(V3,energy);
Serial.print("Energy: ");
Serial.print(energy,3);
Serial.println("kWh");
lcd.setCursor(0,0);
lcd.print("energy : ");
//lcd.setCursor(1,0);
lcd.print(energy);
lcd.print("kWh");
delay(500);
lcd.clear();
float frequency = pzem.frequency();
Blynk.virtualWrite(V4,frequency);
Serial.print("Frequency: ");
Serial.print(frequency, 1);
Serial.println("Hz");
lcd.setCursor(0,0);
lcd.print("frequency : ");
lcd.setCursor(12,0);
lcd.print(frequency);
lcd.print("Hz");
delay(500);
lcd.clear();
float pf = pzem.pf();
Blynk.virtualWrite(V5,pf);
Serial.print("PF: ");
Serial.println(pf);
lcd.setCursor(0,0);
lcd.print("pf : ");
lcd.setCursor(6,0);
lcd.print(pf);
delay(500);
lcd.clear();
}
void setup()
{
// Debug console Serial.begin(115200);
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
pinMode(button3, INPUT_PULLUP);
Wire.begin(D4, D3); //sda,scl
lcd.begin();
lcd.home();
lcd.setCursor(2,0);
lcd.print("SMART ENERGY");
lcd.setCursor(5,1);
lcd.print("METER");
Blynk.begin(auth, ssid, pass);
timer.setInterval(3000L, senddata);
lcd.clear();
// You can also specify server:
//Blynk.begin(auth, ssid, pass, "blynk.cloud", 80);
//Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
// Setup a function to be called every second
}
void loop()
{
Blynk.run();
timer.run(); // Initiates BlynkTimer
}
For Tariff Calculation Code
# Import required libraries
import blynklib
# Blynk authentication token
BLYNK_AUTH = 'your_blynk_auth_token'
# Create Blynk instance
blynk = blynklib.Blynk(BLYNK_AUTH)
# Device variables
power_consumption = 100 # Power consumption of the device in watts
usage_duration = 4 # Usage duration in hours
electricity_rate = 0.12 # Electricity rate per kilowatt-hour
# Calculate bill function
def calculate_bill():
energy_consumed = (power_consumption / 1000) * usage_duration # Energy consumed in
kilowatt-hours
bill_amount = energy_consumed * electricity_rate # Total bill amount
return bill_amount
# Blynk virtual pin handler
@blynk.handle_event('write V1')
def write_virtual_pin_handler(pin, value):
# Retrieve values from Blynk app
power_consumption = int(blynk.virtual_write(1))
usage_duration = int(blynk.virtual_write(2))
electricity_rate = float(blynk.virtual_write(3))
# Calculate bill
bill_amount = calculate_bill()
# Display bill amount on Blynk app
blynk.virtual_write(4, bill_amount)
# Start Blynk connection
blynk.run()
|
import numpy as np
import matplotlib.pyplot as plt
ITERATION = 100
show = 1 # 0 = None, 1 = plot, 2 = ani
def get_point_cloud_from_file():
pc = np.load('verts.npz')["verts"]
x = pc[:, 0]
y = pc[:, 1]
z = pc[:, 2]
for i in range(len(z)):
if z[i] <= 0.0:
x[i] = 0
y[i] = 0
z[i] = 0
elif z[i] >= 6.0:
x[i] = 0
y[i] = 0
z[i] = 0
pc = np.column_stack((x[::10], y[::10], z[::10]))
return pc
def plot(pc):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(pc[0][::20], pc[1][::20], pc[2][::20], color="gray")
ax.set_xlabel("X Coordinate")
ax.set_ylabel("Y Coordinate")
ax.set_zlabel("Z Coordinate")
plt.show()
def get_plane_vectors(point_cloud):
# Generate three random indices
random_indices = np.random.choice(len(point_cloud)-1, 3, replace=False)
random_coordinates = point_cloud[random_indices]
if random_coordinates[0][2] == 0 or random_coordinates[1][2] == 0 or random_coordinates[2][2] == 0:
return get_plane_vectors(point_cloud)
vector1 = random_coordinates[1] - random_coordinates[0]
vector2 = random_coordinates[2] - random_coordinates[0]
normal_vector = np.cross(vector1, vector2)
return normal_vector, random_coordinates
def get_distance(point_cloud, normal_vector, threshold):
distance_list = []
z_val = [item[2] for item in point_cloud]
for i in range(len(point_cloud)):
if z_val[i] > 0:
#print(z_val[i])
distance = np.abs(np.divide(np.dot(point_cloud[i], normal_vector), np.linalg.norm(normal_vector)+0.00000000001))
if distance < threshold:
distance_list.append(distance)
return len(distance_list)
def plot(point_cloud, plane_vectors, coords, ax):
if show == 2:
plt.ion()
x = point_cloud[:, 0]
y = point_cloud[:, 1]
z = point_cloud[:, 2]
ax.scatter(x[::20], y[::20], z[::20], color="gray")
if plane_vectors is not None and coords is not None:
point = coords[0]
normal = plane_vectors
d = -point.dot(normal)
# create x,y
xx, yy = np.meshgrid(range(5), range(5))
# calculate corresponding z
zz = (-normal[0] * xx - normal[1] * yy - d) * 1. /(normal[2]+0.0000000001)
ax.plot_surface(xx, yy, zz, alpha=0.5, color='orange')
ax.scatter(coords[:, 0], coords[:, 1], coords[:, 2], color='blue')
ax.set_xlabel("X Coordinate")
ax.set_ylabel("Y Coordinate")
ax.set_zlabel("Z Coordinate")
plt.title("3D Point Cloud with Plane")
plt.grid(True)
if show == 2:
plt.pause(1.0)
plt.cla()
elif show == 1:
plt.show()
def plot_best_plane(point_cloud, plane_vectors, coords):
plt.ioff()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = point_cloud[:, 0]
y = point_cloud[:, 1]
z = point_cloud[:, 2]
ax.scatter(x[::20], y[::20], z[::20])
if plane_vectors is not None and coords is not None:
point = coords[0]
normal = plane_vectors
d = -point.dot(normal)
# create x,y
xx, yy = np.meshgrid(range(5), range(5))
# calculate corresponding z
zz = (-normal[0] * xx - normal[1] * yy - d) * 1. /(normal[2]+0.00000000001)
ax.plot_surface(xx, yy, zz, alpha=0.5, color='green')
ax.scatter(coords[:, 0], coords[:, 1], coords[:, 2], color='red')
ax.set_xlabel("X Coordinate")
ax.set_ylabel("Y Coordinate")
ax.set_zlabel("Z Coordinate")
plt.title("3D Point Cloud with Best Fitted Plane")
plt.grid(True)
plt.show()
def main():
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
pc = get_point_cloud_from_file()
vec, coords = get_plane_vectors(pc)
if show != 0:
plot(pc, vec, coords, ax)
plane_list = []
for i in range(ITERATION):
print("iteration: ", i)
vec, coords = get_plane_vectors(pc)
if show == 2:
plot(pc, vec, coords, ax)
inliers = get_distance(pc, vec, threshold=0.1)
plane_list.append([inliers, vec, coords])
inlier_list = [item[0] for item in plane_list]
min_index = inlier_list.index(max(inlier_list))
print("best plane: ", plane_list[min_index])
plot_best_plane(pc, plane_list[min_index][1], plane_list[min_index][2])
if __name__ == "__main__":
main()
|
import os
from celery import Celery ,schedules
from celery.schedules import crontab
# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
app = Celery('backend')
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django apps.
app.autodiscover_tasks()
from datetime import timedelta
app.conf.beat_schedule = {
# Executes every Monday morning at 7:30 a.m.
'check_subs': {
'task': 'subscription.tasks.check_subs',
'schedule': crontab(hour=0, minute=30),
},
# 'delete_closed_room':{
# 'task':'chat.tasks.delete_closed_room',
# 'schedule':crontab(hour=0, minute=30),
# },
# 'delete_unverified_image':{
# 'task':'chat.tasks.delete_unverified_image',
# 'schedule':crontab(hour=0, minute=30),
# }
# ,
# 'delete_signature':{
# 'task':'chat.tasks.delete_signature',
# 'schedule':timedelta(minute=30),
# }
# ,
'otp_expire':{
'task':'account.tasks.otp_expire',
'schedule':timedelta(minute=1),
}
}
|
import {
Grid,
Card,
Text,
Tooltip,
Button,
Table,
Badge,
Loading,
Switch,
} from "@nextui-org/react";
import { Form, Input, message, DatePicker, Progress, Space } from "antd";
import FetchApi from "../../../apis/FetchApi";
import { useNavigate } from "react-router-dom";
import { ManageTeacherApis } from "../../../apis/ListApi";
import { useState } from "react";
import { useEffect } from "react";
import ColumnGroup from "antd/lib/table/ColumnGroup";
import { Fragment } from "react";
import classes from "../../Admin/Sro/SroScreen.module.css";
import { RiEyeFill } from "react-icons/ri";
import moment from "moment";
import { toast } from "react-hot-toast";
import { ErrorCodeApi } from "../../../apis/ErrorCodeApi";
const ManageTeacher = () => {
const [dataSource, setDataSource] = useState([]);
const [isGetData, setIsGetData] = useState(true);
const [passRate, setPassRate] = useState(0);
const [passRateAll, setPassRateAll] = useState(0)
const [messageFailed, setMessageFailed] = useState(undefined);
const [form1] = Form.useForm();
const [form2] = Form.useForm();
const navigate = useNavigate();
const getListTeacher = (param) => {
setIsGetData(true);
FetchApi(ManageTeacherApis.searchTeacherBySro, null, param, null)
.then((res) => {
setDataSource(
res.data.map((item, index) => {
return {
...item,
key: item.id,
index: index + 1,
};
})
);
console.log(res.data);
setIsGetData(false);
})
.catch((err) => {
setIsGetData(false);
if (err?.type_error) {
return toast.error(ErrorCodeApi[err.type_error]);
}
toast.error("Lỗi lấy danh sách giáo viên");
});
};
const getPassRateAllTeacherInAllTime = () => {
FetchApi(ManageTeacherApis.getPassRateAllTeacherInAllTime, null, null, null)
.then((res) => {
const data = res.data === null ? "" : res.data;
let passStudent = 0;
let totalStudent = 0;
for (let i = 0; i < data.length; i++) {
passStudent += data[i].number_of_passed_students;
totalStudent += data[i].number_of_all_students;
}
if (totalStudent === 0) {
setPassRate(0);
} else {
setPassRate(passStudent / totalStudent);
setPassRateAll(passStudent / totalStudent);
}
})
.catch((err) => {
if (err?.type_error) {
return toast.error(ErrorCodeApi[err.type_error]);
}
toast.error("Lỗi lấy tỷ lệ học viên qua môn");
});
};
const handleSubmitForm = () => {
const data = form1.getFieldsValue();
const param = {
firstName: data.first_name.trim(),
lastName: data.last_name.trim(),
nickname: data.nickname.trim(),
email: data.email.trim(),
mobilePhone: data.mobile_phone.trim(),
emailOrganization: data.email_organization.trim(),
};
getListTeacher(param);
};
const handleSubmitForm2 = () => {
// setPassRate(0);
const data2 = form2.getFieldsValue();
const body = {
from_date: moment.utc(data2.periodtime[0]).local().format(),
to_date: moment.utc(data2.periodtime[1]).local().format(),
};
console.log(body);
FetchApi(
ManageTeacherApis.getPassRateAllTeacherOnPeriodTime,
body,
null,
null
)
.then((res) => {
const data = res.data === null ? "" : res.data;
let passStudent = 0;
let totalStudent = 0;
for (let i = 0; i < data.length; i++) {
passStudent += data[i].number_of_passed_students;
totalStudent += data[i].number_of_all_students;
}
if (totalStudent === 0) {
setPassRate(0);
} else {
setPassRate(passStudent / totalStudent);
}
})
.catch((err) => {
if (err?.type_error) {
return toast.error(ErrorCodeApi[err.type_error]);
}
toast.error("Lỗi lấy tỷ lệ học viên qua môn trong khoảng thời gian này");
});
};
const handleClearInput = () => {
form1.resetFields();
getListTeacher();
};
useEffect(() => {
getListTeacher();
getPassRateAllTeacherInAllTime();
}, []);
const renderGender = (id) => {
if (id === 1) {
return (
<Badge variant="flat" color="success">
Nam
</Badge>
);
} else if (id === 2) {
return (
<Badge variant="flat" color="error">
Nữ
</Badge>
);
} else if (id === 3) {
return (
<Badge variant="flat" color="default">
Khác
</Badge>
);
} else {
return (
<Badge variant="flat" color="default">
Không xác định
</Badge>
);
}
};
return (
<Grid.Container gap={2}>
<Grid sm={12}>
<Card variant="bordered">
<Card.Body
css={{
padding: "10px",
}}
>
<Form
name="basic"
layout="inline"
form={form1}
initialValues={{
first_name: "",
last_name: "",
mobile_phone: "",
nickname: "",
email: "",
email_organization: "",
}}
onFinish={handleSubmitForm}
>
<Form.Item
name="first_name"
style={{ width: "calc(15% - 16px)" }}
>
<Input placeholder="Họ" />
</Form.Item>
<Form.Item name="last_name" style={{ width: "calc(15% - 16px)" }}>
<Input placeholder="Tên" />
</Form.Item>
<Form.Item name="nickname" style={{ width: "calc(10% - 16px)" }}>
<Input placeholder="Biệt danh" />
</Form.Item>
<Form.Item
name="mobile_phone"
style={{ width: "calc(15% - 16px)" }}
>
<Input placeholder="Số điện thoại" />
</Form.Item>
<Form.Item name="email" style={{ width: "calc(15% - 16px)" }}>
<Input placeholder="Email cá nhân" />
</Form.Item>
<Form.Item
name="email_organization"
style={{ width: "calc(15% - 16px)" }}
>
<Input placeholder="Email tổ chức" />
</Form.Item>
<Form.Item style={{ width: "calc(9% - 16px)" }}>
<Button
flat
auto
type="primary"
htmlType="submit"
css={{ width: "100%" }}
>
Tìm kiếm
</Button>
</Form.Item>
<Form.Item style={{ width: "6%", marginRight: 0 }}>
<Button
flat
auto
color={"error"}
css={{
width: "100%",
}}
onPress={handleClearInput}
>
Huỷ
</Button>
</Form.Item>
</Form>
</Card.Body>
</Card>
</Grid>
<Grid sm={12}>
<Card
variant="bordered"
css={{
minHeight: "300px",
}}
>
<Card.Header>
<Grid.Container>
<Grid sm={4}>
<div style={{ height: "80px" }}>
<Text
b
size={12}
css={{
width: "100%",
textAlign: "left",
marginBottom: "2px",
}}
>
Tỷ lệ học viên qua môn từ:
</Text>
<Form
name="passrate"
layout="inline"
form={form2}
onFinish={handleSubmitForm2}
>
<Form.Item
name="periodtime"
rules={[
{ required: true, message: "Vui lòng chọn thời gian" },
]}
>
{/* <div style={{ width: 280 }}> */}
<DatePicker.RangePicker format={"DD-MM-YYYY"} />
{/* </div> */}
</Form.Item>
<Form.Item>
<Button
// disabled={form2.getFieldsValue().periodtime.length === 0}
auto
flat
type="primary"
htmlType="submit"
>
Xem
</Button>
</Form.Item>
</Form>
<div style={{ width: 300 }}>
<Progress
percent={Math.round(passRate * 1000) / 10}
size="small"
status={
Math.round(passRate * 1000) / 10 > 50
? "success"
: "default"
}
/>
</div>
</div>
</Grid>
<Grid sm={4}>
<Text
b
size={14}
p
css={{
width: "100%",
textAlign: "center",
}}
>
Danh sách giáo viên
</Text>
</Grid>
<Grid sm={4}></Grid>
</Grid.Container>
</Card.Header>
{isGetData && <Loading />}
{!isGetData && (
<Table aria-label="">
<Table.Header>
<Table.Column width={60}>STT</Table.Column>
<Table.Column width={270}>Họ và tên</Table.Column>
<Table.Column width={150}>Biệt danh</Table.Column>
<Table.Column width={150}>Cơ sở</Table.Column>
<Table.Column width={250}>Email cá nhân</Table.Column>
<Table.Column width={250}>Email tổ chức</Table.Column>
<Table.Column>Số điện thoại</Table.Column>
<Table.Column>Giới tính</Table.Column>
<Table.Column width={20}></Table.Column>
</Table.Header>
<Table.Body>
{dataSource.map((data, index) => (
<Table.Row key={data.user_id}>
<Table.Cell>{index + 1}</Table.Cell>
<Table.Cell>
<b>
{data.first_name} {data.last_name}
</b>
</Table.Cell>
<Table.Cell>{data.nickname}</Table.Cell>
<Table.Cell>{data.center_name}</Table.Cell>
<Table.Cell>{data.email}</Table.Cell>
<Table.Cell>{data.email_organization}</Table.Cell>
<Table.Cell>{data.mobile_phone}</Table.Cell>
<Table.Cell>{renderGender(data.gender.id)}</Table.Cell>
<Table.Cell>
<RiEyeFill
size={20}
color="5EA2EF"
style={{ cursor: "pointer" }}
onClick={() => {
navigate(`/sro/manage/teacher/${data.user_id}`);
}}
/>
</Table.Cell>
</Table.Row>
))}
</Table.Body>
<Table.Pagination
shadow
noMargin
align="center"
rowsPerPage={9}
/>
</Table>
)}
</Card>
</Grid>
</Grid.Container>
);
};
export default ManageTeacher;
|
#include "sort.h"
/**
* merge - Merges two subarrays back into the original array.
*
* @array: The original array.
* @left: The left subarray.
* @right: The right subarray.
* @size: The size of the original array.
*/
void merge(int *array, int *left, int *right, size_t size)
{
int *temp;
size_t i = 0, j = 0, k = 0;
temp = malloc(sizeof(int) * size);
if (temp == NULL)
return;
printf("Merging...\n");
printf("[left]: ");
print_array(left, size / 2);
printf("[right]: ");
print_array(right, size - (size / 2));
while (i < size / 2 && j < size - (size / 2))
{
if (left[i] < right[j])
temp[k++] = left[i++];
else
temp[k++] = right[j++];
}
while (i < size / 2)
temp[k++] = left[i++];
while (j < size - (size / 2))
temp[k++] = right[j++];
for (i = 0; i < size; i++)
array[i] = temp[i];
printf("[Done]: ");
print_array(array, size);
free(temp);
}
/**
* merge_sort - Sorts an array of integers using Merge Sort.
*
* @array: The array of integers to be sorted.
* @size: The size of the array.
*/
void merge_sort(int *array, size_t size)
{
size_t middle;
int *left, *right;
if (array == NULL || size <= 1)
return;
if (size > 1)
{
middle = size / 2;
left = array;
right = array + middle;
merge_sort(left, middle);
merge_sort(right, size - middle);
merge(array, left, right, size);
}
}
|
import { IOption } from 'ng-select'; // select option <option>
import { Component, OnInit, ViewChild, ElementRef, TemplateRef, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { environment } from '../../../../../environments/environment';
import { AppService } from '../../../../app.service';
// Import BlockUI decorator & optional NgBlockUI type
import { BlockUI, NgBlockUI } from 'ng-block-ui';
// import Modal
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
// chỉnh css angular
import { ViewEncapsulation } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
// import viewchild
import { AgeMenuComponent } from '../../../viewchild/agemenu/agemenu.component';
// import notification
import { NotifierService } from 'angular-notifier';
import { BehaviorSubject } from 'rxjs';
import { language } from '../../../admin/admin_language';
import { language_en } from '../../../admin/admin_language_en';
@ViewChild(AgeMenuComponent)
@Component({
templateUrl: './webhookage.component.html',
styleUrls: ['./webhookage.component.scss'],
// chỉnh css angular
encapsulation: ViewEncapsulation.None
})
export class WebhookageComponent implements OnInit, OnDestroy {
@ViewChild('dataTable') table: ElementRef;
@BlockUI() blockUI: NgBlockUI;
private readonly notifier: NotifierService;
can_add: boolean;
can_update: boolean;
can_delete: boolean;
// Khai báo kiểu dữ kiệu
public data: any;
data_filter: any;
data_update: any;
organization_id: string;
organization_arr: Array<IOption>;
modalRef: BsModalRef;
// phân trang bảng
rowsOnPage = 15;
SelectionDisplay: boolean;
menu_tree: any;
siteSelectionDisplay: boolean;
userlogged = JSON.parse(localStorage.getItem(environment.UserLoged));
webState: BehaviorSubject<any>;
showSelectCrud: boolean;
subcription: any;
tu_khoa: any;
option_delete: number;
oldState: string;
siteSelected: any;
error_array: any[];
delete_object: any;
language: any;
siteFilterModel: any;
siteFilterDisplay: boolean;
module_id: number;
codeText: string;
codeOptions: any = {
maxLines: 1000,
printMargin: false,
wrap: true
};
constructor(
private router: Router,
private route: ActivatedRoute,
notifierService: NotifierService,
private appservice: AppService,
private modalService: BsModalService) {
this.notifier = notifierService;
}
ngOnInit(): void {
this.codeText = '[\n\twebhookSendData: {\n\
\tcustomer_name: "Nguyễn Văn A",\n\t\tphone_number: 0123456789\n\t}\n]';
const firstState = {
data: null
, state: null
};
const type_language = JSON.parse(localStorage.getItem(environment.language));
type_language === 'vn' ? this.language = language : this.language = language_en;
this.webState = new BehaviorSubject(firstState);
this.get_organization();
this.setDefaultValue();
this.watchStateChange();
this.set_default_crud(false);
}
watchStateChange() {
this.subcription = this.webState.asObservable();
this.subcription.subscribe(res => {
const currentState = res.state;
const item = res.data;
// console.log('trạng thái trước', this.oldState);
// console.log('trạng thái hiện tại', currentState);
// Đây là sự kiện khi vừa load trang get data về
if (currentState === environment.STATE.retrieve) {
// Sự kiện nhận dữ liệu về thì bỏ hành động tìm kiếm trước đó
this.tu_khoa = null;
this.data = item;
this.data_filter = this.data;
// Nếu là sự kiện thêm mới
} else if (currentState === environment.STATE.insert) {
this.data.push(item);
// Nếu trạng thái trước đó là search
if (this.oldState === environment.STATE.search) {
this.updateState(environment.STATE.search);
}
this.notifier.notify('success', 'Thêm mới dữ liệu thành công');
// nếu là sự kiện sửa
} else if (currentState === environment.STATE.update) {
for (let i = 0; i < this.data.length; i++) {
if (Number(this.data[i].id) === Number(item.id)) {
this.data[i] = item;
break;
}
}
// Nếu trạng thái trước đó là search
if (this.oldState === environment.STATE.search) {
this.updateState(environment.STATE.search);
}
this.notifier.notify('success', 'Cập nhật dữ liệu thành công');
// Nếu là sự kiện xóa
} else if (currentState === environment.STATE.delete) {
this.data.splice(this.data.findIndex(e => e.id === item.id), 1);
// Nếu trạng thái trước đó là search
if (this.oldState === environment.STATE.search) {
this.updateState(environment.STATE.search);
}
this.notifier.notify('success', 'Xóa dữ liệu thành công');
// Nếu có sự kiện tìm kiếm
} else if (currentState === environment.STATE.search) {
const string = this.tu_khoa ? this.tu_khoa.toLowerCase() : '';
// console.log(string);
if (string === '') {
this.data_filter = this.data;
} else {
this.data_filter = this.data.filter(x => x.webhook_name.toLowerCase().indexOf(string) !== -1);
}
}
});
}
showSelectFunc() {
this.showSelectCrud = false;
const lever = Number(this.userlogged.lever);
const org_id = Number(this.userlogged.organization_id);
if (lever === 0 && org_id === 0) {
this.showSelectCrud = true;
}
}
set_default_crud(bool: boolean) {
this.can_add = bool;
this.can_update = bool;
this.can_delete = bool;
}
search_organization() {
this.tu_khoa = null;
this.get_site();
}
site_filter(item: any) {
this.tu_khoa = null;
this.siteFilterModel = item;
this.siteFilterDisplay = true;
this.get_data();
}
change_delete_option() {
this.tu_khoa = null;
this.get_data();
}
setDefaultValue() {
this.data_filter = [];
this.data = [];
this.data_update = null;
this.error_array = [];
this.option_delete = 0;
this.siteFilterDisplay = true;
this.siteFilterModel = null;
this.module_id = 3;
}
// Hàm đệ quy menu
recusive_menu(array: any[], id = null, space = 0) {
array.forEach(element => {
if (element.parent_id === id) {
const a_id = element.id;
this.menu_tree.push({
id: element.id
, site_name: element.site_name
, parent_id: element.parent_id
, alevel: space
, enables: element.enables
, store: element.store
});
const scope = space + 1;
this.recusive_menu(array, a_id, scope);
}
});
}
updateState(stateString: string, data = null) {
const stateWithData = {
state: stateString
, data: data
};
const oldStateObj = this.webState.getValue();
this.oldState = oldStateObj.state;
this.webState.next(stateWithData);
}
// Lấy thông tin tổ chức lên ng-select
get_organization() {
this.blockUI.start('Đang tải dữ liệu...');
const url = environment.API.userGetOrg;
this.appservice.get(url).subscribe(
param => {
if (!environment.production) {
// console.log('get_user_page_parametter', param);
}
if ('message' in param) {
this.notifier.notify('error', 'Đã có lỗi xảy ra');
return;
}
const org = param.organization_arr.slice(0);
this.organization_arr = org;
this.organization_id = param.organization_arr[0].value;
this.get_site();
},
(error) => {
if (!environment.production) {
// console.log(error);
}
this.notifier.notify('error', 'Không thể kết nối máy chủ');
this.blockUI.stop();
});
}
// Thay đổi tổ chức header của bảng
changeorganization_table(event) {
if (!environment.production) {
console.log('mã tổ chức', event);
}
this.organization_id = event;
this.get_site();
}
// Modal hỏi xóa
modal_question(item, dialog: TemplateRef<any>) {
if (!environment.production) {
console.log('dữ liệu từng bản ghi', item);
}
// this.delete_tablet_id = item;
this.modalRef = this.modalService.show(dialog, {
backdrop: true,
ignoreBackdropClick: true
});
this.delete_object = item;
}
// Open Modal thêm mới
open_modal_them_moi(templates: TemplateRef<any>) {
this.siteSelected = null;
this.error_array = [];
this.modalRef = this.modalService.show(templates, {
backdrop: true,
ignoreBackdropClick: true
});
}
// Hành động click chọn site ở menu tree thêm mới
change_site_seleted(organization_id, item) {
if (!environment.production) {
console.log('id', item);
}
if (item.store === '0' || item.enables === '0') {
this.modalRef.hide();
this.notifier.notify('error', 'Đã có lỗi xảy ra');
return;
}
this.siteSelected = item;
this.siteSelectionDisplay = false;
}
open_modal_update(item, template: TemplateRef<any>) {
if (!environment.production) {
console.log('dữ liệu từng bản ghi', item);
}
this.error_array = [];
this.data_update = Object.assign({}, item);
const site_id = item.site_id;
this.siteSelected = this.menu_tree.find(e => e.id === site_id);
this.modalRef = this.modalService.show(template, {
backdrop: true,
ignoreBackdropClick: true
});
}
open_modal_webhook(template: TemplateRef<any>) {
this.error_array = [];
// this.data_update = Object.assign({}, item);
this.modalRef = this.modalService.show(template, {
backdrop: true,
ignoreBackdropClick: true
});
}
get_site() {
this.blockUI.start('Đang tải dữ liệu...');
this.menu_tree = [];
const url = environment.API.sites + '_get_site_with_permission';
const data = {
organization_id: this.organization_id
, deleted: 0
};
this.appservice.post(data, url).subscribe(
param => {
if (!environment.production) {
console.log('get_site_tree', param);
}
if (param.site_in_role.length === 0) {
this.notifier.notify('warning', 'Tổ chức chưa tạo site');
this.blockUI.stop();
return;
}
this.recusive_menu(param.site_in_role);
this.siteFilterModel = this.menu_tree.find(i => i.enables === '1');
this.get_data();
},
(error) => {
if (!environment.production) {
// console.log(error);
}
this.notifier.notify('error', 'Không thể kết nối máy chủ');
this.blockUI.stop();
});
}
get_data() {
this.blockUI.start('Đang tải dữ liệu...');
const data = {
organization_id: this.organization_id
, deleted: this.option_delete
, module_id: this.module_id
, site_id: this.siteFilterModel.id
};
const url = environment.API.sp_get_web_hook;
if (!environment.production) {
// console.log('data gửi đi', data);
}
this.appservice.post(data, url).subscribe(res => {
if (!environment.production) {
console.log(res);
}
this.set_default_crud(true);
this.updateState('retrieve', res.webhookArray);
},
(error) => {
if (!environment.production) {
// console.log(error);
}
this.notifier.notify('error', 'Không thể kết nối máy chủ');
}).add(() => {
this.blockUI.stop();
});
}
// thêm thiết bị
insert_object(item) {
if (item.invalid) {
this.notifier.notify('error', 'Nhập liệu gặp sự cố');
return;
}
const url = environment.API.sp_get_web_hook + '_insert';
const location_id = item.value.location_id;
const data = {
...item.value
, site_id: this.siteFilterModel.id
};
// xét error về rỗng.
this.error_array = [];
this.blockUI.start('Đang thêm dữ liệu...');
this.appservice.post(data, url).subscribe(
res => {
if (!environment.production) {
console.log('dữ liệu gửi về', res);
}
if (res.message === 1) {
delete res.insertedData.id;
const transData = { ...res.insertedData, id: res.insertedData.gid };
// console.log('transData', transData);
this.updateState(environment.STATE.insert, transData);
this.modalRef.hide();
} else {
this.error_array = this.appservice.validate_error(res);
// console.log(this.error_array);
}
},
(error) => {
this.error_array = ['Không thể kết nối tới máy chủ'];
}).add(() => {
this.blockUI.stop();
});
}
callWebhookApi() {
const sendData = {
access_token: 'op7ESyrVyv4gxwFyCW54'
, data: {
customer_name: 'Nguyễn Văn A'
, phone_number: '0123456789'
}
};
this.error_array = [];
this.blockUI.start('Đang thực hiện gửi test...');
const url = 'api/web_hook';
this.appservice.post(sendData, url).subscribe(
res => {
if (!environment.production) {
console.log('dữ liệu gửi về', res);
}
if (res.status === 1) {
this.notifier.notify('success', 'Gửi dữ liệu thành công');
} else {
this.notifier.notify('error', 'Gửi dữ liệu không thành công');
}
},
(error) => {
this.notifier.notify('error', 'Gửi dữ liệu không thành công. Thông tin lỗi:' + error);
}).add(() => {
this.blockUI.stop();
});
}
preventChange() {
this.modalRef.hide();
this.notifier.notify('error', 'Lỗi dữ liệu không được thay đổi');
}
// cập nhật thiết bị
update_object(item) {
if (!environment.production) {
console.log(item);
}
if (!item.dirty) {
this.notifier.notify('warning', 'Thông tin không thay đổi');
return;
}
this.error_array = [];
this.blockUI.start('Đang cập nhật dữ liệu...');
const url = environment.API.sp_get_web_hook + '_update';
this.appservice.post(item.value, url).subscribe(
res => {
if (!environment.production) {
console.log('dữ liệu gửi về', res);
}
if (res.message === 1) {
this.updateState(environment.STATE.update, res.updatedData);
// this.data_filter = res.updatedData;
this.get_data();
// this.notifier.notify('success', 'Cập nhật thành công');
// this.modalRef.hide();
} else {
this.error_array = this.appservice.validate_error(res);
}
},
(error) => {
this.error_array = ['Không thể kết nối tới máy chủ'];
}).add(() => {
this.blockUI.stop();
});
}
search_table(searchString: string) {
this.tu_khoa = searchString;
this.updateState(environment.STATE.search);
}
soft_delete_item() {
this.blockUI.start('Đang xử lý dữ liệu...');
const url = environment.API.sp_get_web_hook + '_soft_delete';
const data = {
id: this.delete_object.id
, deleted: this.delete_object.deleted
};
this.appservice.post(data, url).subscribe(
param => {
if (param.message === 1) {
this.updateState('delete', this.delete_object);
} else {
this.notifier.notify('error', 'Đã có lỗi xảy ra');
}
},
(error) => {
this.notifier.notify('error', 'Không thể kết nối máy chủ');
}).add(() => {
this.modalRef.hide();
this.blockUI.stop();
});
}
clone_item(item: any) {
console.log(item);
const selBox = document.createElement('textarea');
selBox.style.position = 'fixed';
selBox.style.left = '0';
selBox.style.top = '0';
selBox.style.opacity = '0';
selBox.value = item.access_token;
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
document.body.removeChild(selBox);
this.notifier.notify('success', 'Copy thành công');
}
delete_item() {
this.blockUI.start('Đang xử lý dữ liệu...');
const url = environment.API.sp_get_web_hook + '_delete';
const data = {
id: this.delete_object.id
};
this.appservice.post(data, url).subscribe(
param => {
if (param.message === 1) {
this.updateState('delete', this.delete_object);
} else {
this.notifier.notify('error', 'Đã có lỗi xảy ra');
}
},
(error) => {
this.notifier.notify('error', 'Không thể kết nối máy chủ');
}).add(() => {
this.modalRef.hide();
this.blockUI.stop();
});
}
ngOnDestroy() {
this.webState.complete();
}
}
|
import React, { useCallback, useMemo } from 'react'
import { useBlockTypes } from '../hooks';
import { __ } from '@wordpress/i18n';
import {
PanelBody,
BaseControl,
SelectControl,
Spinner,
} from '@wordpress/components';
import type { ControlOptions } from '../types';
export type SettingsProps = {
data: ControlOptions;
updateData: (data: Partial<ControlOptions>) => void;
}
export const Settings = ({ data, updateData }: SettingsProps) => {
const blockTypes = useBlockTypes()
const blockOptions = useMemo(() => {
if (blockTypes) {
const options = blockTypes.map((block) => ({
label: block.title.raw,
value: String(block.slug)
}))
return [
{ disabled: true, label: __('Select one or more blocks', '@@text_domain'), value: '' },
...options,
]
}
return []
}, [blockTypes])
const handleBlocksChange = useCallback((value: string[]) => {
updateData({ allowed_blocks: value })
}, [])
return (
<PanelBody>
<BaseControl
id="lzb-inner-blocks-block-id"
label={__('Block', '@@text_domain')}
help={__('Defines the block to show here')}
>
{!blockTypes ? (
<Spinner />
) : (
<SelectControl<string[]>
multiple
style={{ height: 'auto' }}
value={data.allowed_blocks}
options={blockOptions}
onChange={handleBlocksChange}
/>
)}
</BaseControl>
</PanelBody>
)
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class BuatTabelSales extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('sales', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('id_supplier');
$table->string('nama');
$table->string('no_telp');
$table->foreign('id_supplier')->references('id')->on('supplier')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('sales');
}
}
|
<?php
namespace Tests\Unit\UserCases;
use App\Adapters\Presenters\Json\CalculateProductPriceJsonPresenter;
use App\Domain\Interfaces\Country\CountryFactory;
use App\Domain\Interfaces\Country\CountryRepository;
use App\Domain\Interfaces\Product\ProductFactory;
use App\Domain\Interfaces\Product\ProductRepository;
use App\Domain\UseCases\Product\CalculatePrice\CalculatePriceInteractor;
use App\Domain\UseCases\Product\CalculatePrice\CalculatePriceRequestModel;
use App\Domain\UseCases\Product\CalculatePrice\CalculateProductPriceViewModelFactory;
use App\Repositories\Eloquent\CountryRepositoryEloquent;
use App\Repositories\Eloquent\ProductRepositoryEloquent;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\MockObject\Exception;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Tests\TestCase;
use Tests\Traits\ProvidesProducts;
class CalculateProductPriceUseCaseTest extends TestCase
{
use RefreshDatabase;
use ProvidesProducts;
/**
* @dataProvider productsDataProvider
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Exception
*/
public function testInteractor(
?array $product,
?array $country,
string $taxNumber,
?float $price,
?string $errorMessage = null,
): void {
/** @var ProductFactory $productFactory */
$productFactory = $this->app->get(ProductFactory::class);
/** @var CountryFactory $countryFactory */
$countryFactory = $this->app->get(CountryFactory::class);
$this->app->bind(
CalculateProductPriceViewModelFactory::class,
CalculateProductPriceJsonPresenter::class,
);
$product = $product
? $productFactory->make($product)
: null;
$requestModel = new CalculatePriceRequestModel([
'product' => $product,
'product_id' => 1,
'tax_number' => $taxNumber,
]);
$productRepositoryMock = $this->createMock(ProductRepositoryEloquent::class);
$productRepositoryMock->method('getById')->with(1)->willReturn($product);
$this->app->bind(
ProductRepository::class,
fn() => $productRepositoryMock,
);
$countryRepositoryMock = $this->createMock(CountryRepositoryEloquent::class);
$countryRepositoryMock->method('getByCode')->withAnyParameters()->willReturn(
$country ? $countryFactory->make($country) : null,
);
$this->app->bind(
CountryRepository::class,
fn() => $countryRepositoryMock,
);
/** @var CalculatePriceInteractor $interactor */
$interactor = $this->app->make(CalculatePriceInteractor::class);
$response = $interactor->calculatePrice($requestModel);
if ($errorMessage) {
$this->assertEquals(
$errorMessage,
$response->getResponse()['message'] ?? null,
);
} else {
$this->assertProductMatches(
$response->getResponse()['product'] ?? [],
$product,
);
$this->assertEquals(
$price,
$response->getResponse()['price'] ?? null,
);
}
}
}
|
@extends('master')
@section('title','Produit')
@section('content')
<a href="{{route('produits.index')}}" class="mb-3" style="font-size: xx-large; cursor:pointer;">
<span>
<i class="ti ti-arrow-left"></i>
Back
</span>
</a>
<div class="container-fluid">
<div class="container-fluid">
<div class="card">
<div class="card-body">
<h5 class="card-title fw-semibold mb-4">New Produit</h5>
<div class="card">
<div class="card-body">
<form action="{{route('produits.store')}}" method="post">
@csrf
@method('POST')
<div class="row mb-3">
<div class="col-6">
<label for="ref" class="form-label">Ref</label>
<input type="text" class="form-control" id="ref" name="ref" placeholder="mx123" value="{{old('ref')}}">
@error('ref')
<div class="form-text text-danger d-block">{{ $message }}</div>
@enderror
</div>
<div class="col-6">
<label for="nom" class="form-label">Nom de produit</label>
<input type="text" class="form-control" id="nom" name="nom" value="{{old('nom')}}" placeholder="Samsung S23">
@error('nom')
<div class="form-text text-danger d-block">{{ $message }}</div>
@enderror
</div>
</div>
<div class="row mb-3">
<div class="col-6">
<label for="prix" class="form-label">Prix</label>
<input type="prix" class="form-control" id="prix" name="prix" value="{{old('prix')}}" placeholder="399.99">
@error('prix')
<div class="form-text text-danger d-block">{{ $message }}</div>
@enderror
</div>
<div class="col-6">
<label for="categorie" class="form-label">Categorie<span class="text-danger">*</span></label>
<select name="categorie" id="categorie" class="form-control">
<option value="PC Portable">PC Portable</option>
<option value="PC Poste">PC Poste</option>
<option value="Smartphone">Smartphone</option>
<option value="Tablette">Tablette</option>
</select>
@error('categorie')
<span class="text-danger d-block">{{ $message }}</span>
@enderror
</div>
</div>
<button type="reset" class="btn btn-danger">Annuler</button>
<button type="submit" class="btn btn-primary">Create</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
|
/*
This file is a part of MonaSolutions Copyright 2017
mathieu.poux[a]gmail.com
jammetthomas[a]gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License received along this program for more
details (or else see http://www.gnu.org/licenses/).
*/
#pragma once
#include "Mona/Mona.h"
#include "Mona/Socket.h"
#include "Mona/HTTP/HTTP.h"
namespace Mona {
/*!
HTTP send,
Send a HTTP response (or request? TODO) is used directly.
Children class are mainly used by call to TCPSender::send(pHTTPSender) */
struct HTTPSender : Runner, virtual Object {
NULLABLE(_end);
/*!
If onEnd is set you must wait onEnd signal to release this HTTPSender,
+ resend the HTTPSender on every socket.onFlush if !flushing() */
typedef Event<void()> ON(End);
HTTPSender(const char* name,
const shared<const HTTP::Header>& pRequest,
const shared<Socket>& pSocket) : _end(false), pHandler(NULL), _chunked(0), _pSocket(pSocket), // hold socket to the sending (answer even if server falls)
pRequest(pRequest), connection(pRequest->connection), Runner(name), crossOriginIsolated(false) {}
virtual ~HTTPSender() {
onEnd = nullptr; // useless to call onFlush, no more handle on this HTTPSender
end();
}
bool flushing() const { return pHandler && _pSocket->queueing() ? true : false; }
bool isFile() const;
virtual bool hasHeader() const { return true; }
/*!
Set pHandler on construction to works in asynchronous way:
pause if socket queueing and wait socket.onFlush */
const Handler* pHandler;
bool crossOriginIsolated;
void setCookies(shared<Buffer>& pSetCookie);
Buffer& buffer();
/*!
Send HTTP header
If extraSize=UINT64_MAX + (path() || !mime): Transfer-Encoding: chunked
If extraSize=UINT64_MAX + !path(): live streaming => no content-length, live attributes and close on end of response */
bool send(const char* code, MIME::Type mime = MIME::TYPE_UNKNOWN, const char* subMime = NULL, UInt64 extraSize = 0);
/*!
Send HTTP body content */
bool send(const Packet& content);
/*!
Finalize send */
void end();
template <typename ...Args>
bool sendError(const char* code, Args&&... args) {
writeError(code, std::forward<Args>(args)...);
return send(code, MIME::TYPE_TEXT, "html; charset=utf-8");
}
protected:
const SocketAddress& peerAddress() { return _pSocket ? _pSocket->peerAddress() : SocketAddress::Wildcard(); }
const shared<const HTTP::Header> pRequest;
UInt8 connection;
template <typename ...Args>
void writeError(const char* code, Args&&... args) {
HTML_BEGIN_COMMON_RESPONSE(buffer(), code)
UInt32 size(__writer.size());
String::Append(__writer, std::forward<Args>(args)...);
if (size == __writer.size()) // nothing has been written, write code in content!
String::Append(__writer, code);
HTML_END_COMMON_RESPONSE(pRequest->host)
}
private:
virtual const Path& path() const { return Path::Null(); }
bool socketSend(const Packet& packet);
virtual bool run(Exception&);
/*!
must return end if finished, otherwise false */
virtual bool run() { ERROR(name, " not runnable"); return true; }
shared<Buffer> _pBuffer;
UInt8 _chunked;
bool _end;
shared<Socket> _pSocket;
};
} // namespace Mona
|
import React, { useState } from "react";
import { Link } from "react-router-dom";
import { FaGithub } from 'react-icons/fa';
const ProjectCard = ({ name, description, image, urlGitHub, urlDeploy }) => {
const [showFullDescription, setShowFullDescription] = useState(false);
const toggleDescription = () => {
setShowFullDescription(!showFullDescription);
};
return (
<div className="max-w-sm flex flex-col items-center bg-blue-light py-10 px-5 border border-gray-900 hover:border-gray-800">
<div className="flex gap-4">
<h2 className="text-xl text-green font-mono mb-5">{name}</h2>
</div>
<Link to={urlDeploy} target="_blank">
<img src={image} alt="project image" />
</Link>
<div className="bg-blue-light">
<h2 className="mt-4">
{showFullDescription
? description
: `${description.split(" ").slice(0, 15).join(" ")}...`}
</h2>
<button className="text-green p-1" onClick={toggleDescription}>
{showFullDescription ? "Read Less" : "Read More"}
</button>
</div>
<div className="ml-48">
{urlGitHub ? (
<Link className="text-3xl" to={urlGitHub} target="_blank">
<FaGithub />
</Link>
) : null}
</div>
</div>
);
};
export default ProjectCard;
|
from abc import ABC, abstractmethod
class IShape:
@abstractmethod
def move(self, x, y):
pass
@abstractmethod
def draw(self):
pass
class Rectangle(IShape):
def __init__(self, x, y, l, b):
self.x = x
self.y = y
self.x = x
self.y = y
def move(self, x, y):
self.x += x
self.y += y
def draw(self):
print("Draw a Rectangle at (%s, %s)."%(self.x, self.y))
return "<Rectangle>"
class Circle(IShape):
def __init__(self, x, y, radius):
self.x = x
self.y = y
self.radius = radius
def move(self, x, y):
self.x += x
self.y += y
def draw(self):
print("Draw a Circle of radius %s at (%s, %s) ."%(self.radius, self.x, self.y))
return "<Circle>"
class CompoundShape(IShape):
def __init__(self):
self.children = set()
def add(self, child):
self.children.add(child)
def remove(self, child):
self.children.remove(child)
def move(self, x, y):
for child in self.children:
child.move(x, y)
def draw(self):
st = "Shapes("
for child in self.children:
st += child.draw()
st += ")"
return st
# Client code.
all = CompoundShape()
all.add( Rectangle(1, 2, 1, 2))
all.add( Circle(5, 3, 10))
group = CompoundShape()
group.add(Rectangle(5, 7, 1, 2))
group.add(Circle(2, 1, 2))
all.add(group)
print(all.draw())
"""
Draw a Rectangle at (1, 2).
Draw a Circle of radius 2 at (2, 1) .
Draw a Rectangle at (5, 7).
Draw a Circle of radius 10 at (5, 3) .
Shapes(<Rectangle>Shapes(<Circle><Rectangle>)<Circle>)
"""
|
package org.nwpu.i_gua_da.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.nwpu.i_gua_da.entity.User;
import java.util.List;
@Mapper
public interface UserMapper {
int setUserAsAdmin(@Param("userId") Integer userId, @Param("adminCode") int adminCode, @Param("notDeleteStatus") int notDeleteStatus);
int setUserAsCommon(@Param("userId") Integer userId, @Param("adminName") String adminName, @Param("commonCode") Integer commonCode, @Param("notDeleteStatus") int notDeleteStatus);
User selectUserById(Integer userId);
User selectUserByName(String userName);
int setUserStatusByUserId(@Param("userId") Integer userId,
@Param("status") Integer status);
/**
* 对用户名和密码进行验证
* @param user
* @return 不为null则验证成功
*/
Integer selectForVerify(User user);
int addUser(User user);
int setUserPassword(User user);
/**
* 查重, 用户名|学号|邮箱有一个重复则返回不为空
* @param user
* @return
*/
Integer verifyByNameOrStudentNumbOrEmail(User user);
/**
* 查重, 用户名|邮箱有一个重复则返回不为空
* @param user
* @return
*/
Integer verifyByNameOrEmail(User user);
/**
* 设置新的用户名+学号+邮箱
* @param user
* @return
*/
int setUserInformation(User user);
Integer getUserPermissionByUserId(Integer userId);
List<User> getAllUser(@Param("userId") Integer userId);
User getUserByEmail(@Param("email") String email);
Integer getUserStatusByUserId(Integer userId);
List<User> listUserByLikeUserName(String userName);
/**
* 用户第一次注册登录,赋给openid和本次登录的code
* @param openid
* @param code
* @return
*/
int setUserOpenidAndCode(@Param("userId") Integer userId, @Param("openid") String openid, @Param("code") String code);
/**
* 用户再一次登录,更新code
* @param code
* @return
*/
int updateCode(@Param("userId") Integer userId, @Param("code") String code);
/**
* 通过code获取对应的user
* @param code
* @return
*/
User getUserByCode(@Param("code") String code);
User getUserByOpenid(@Param("openid") String openid);
List<User> listUserByLikeStudentNumber(@Param("userId") int userId,@Param("studentNumber") int studentNumber);
int setUserPermission(int userId, int permission);
int updateUserByOpenid(@Param("openid") String openid, @Param("nickname") String nickname,
@Param("studentNumber") String studentNumber, @Param("email") String email);
User getUserByStudentNumber(@Param("studentNumber") String studentNumber);
int incrementCredit(@Param("userId") Integer userId);
int decrementCredit(@Param("userId") Integer userId);
}
|
import React, {
FC,
PropsWithChildren,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import { t } from 'i18next';
import { nanoid } from 'nanoid';
import {
NotificationType,
OrderDirection,
OrderOptions,
Table,
} from '@sovryn/ui';
import { DEFAULT_HISTORY_FRAME_PAGE_SIZE } from '../../../../../constants/general';
import { getTokenDisplayName } from '../../../../../constants/tokens';
import { useNotificationContext } from '../../../../../contexts/NotificationContext';
import { useAccount } from '../../../../../hooks/useAccount';
import { useBlockNumber } from '../../../../../hooks/useBlockNumber';
import { translations } from '../../../../../locales/i18n';
import { LendingHistoryType } from '../../../../../utils/graphql/rsk/generated';
import { dateFormat } from '../../../../../utils/helpers';
import { BaseConversionsHistoryFrame } from '../../../ConversionsHistoryFrame/components/BaseConversionsHistoryFrame/BaseConversionsHistoryFrame';
import { COLUMNS_CONFIG } from './LendingHistoryFrame.constants';
import { LendingEvent } from './LendingHistoryFrame.types';
import {
generateRowTitle,
getTransactionType,
} from './LendingHistoryFrame.utils';
import { useGetLendingHistory } from './hooks/useGetLendingHistory';
const pageSize = DEFAULT_HISTORY_FRAME_PAGE_SIZE;
export const LendingHistoryFrame: FC<PropsWithChildren> = ({ children }) => {
const { account } = useAccount();
const [page, setPage] = useState(0);
const [normalizedLendingEvents, setNormalizedLendingEvents] = useState<
LendingEvent[]
>([]);
const [total, setTotal] = useState(0);
const [orderOptions, setOrderOptions] = useState<OrderOptions>({
orderBy: 'timestamp',
orderDirection: OrderDirection.Desc,
});
const { addNotification } = useNotificationContext();
const { value: block } = useBlockNumber();
const { data, loading, refetch } = useGetLendingHistory(account);
useEffect(() => {
if (!loading && data?.user?.lendingHistory) {
const flattenedTxs: LendingEvent[] = data.user.lendingHistory
.map(
val =>
val?.lendingHistory?.map(item => ({
amount: `${item.type === LendingHistoryType.Lend ? '' : '-'}${
item.amount
}`,
asset: item.asset?.id || '',
transactionHash: item.transaction?.id,
timestamp: item.timestamp,
type: item.type,
resolvedAsset: getTokenDisplayName(item.asset?.symbol || ''),
})) || [],
)
.flat()
.sort((a, b) =>
orderOptions.orderDirection === OrderDirection.Asc
? a.timestamp - b.timestamp
: b.timestamp - a.timestamp,
);
setNormalizedLendingEvents(flattenedTxs);
setTotal(flattenedTxs.length);
}
}, [account, data, loading, orderOptions.orderDirection]);
useEffect(() => {
refetch();
}, [refetch, block]);
const exportData = useCallback(async () => {
if (!normalizedLendingEvents || normalizedLendingEvents.length === 0) {
addNotification({
type: NotificationType.warning,
title: t(translations.common.tables.actions.noDataToExport),
dismissible: true,
id: nanoid(),
});
}
return normalizedLendingEvents
.sort((a, b) =>
orderOptions.orderDirection === OrderDirection.Asc
? a.timestamp - b.timestamp
: b.timestamp - a.timestamp,
)
.map(item => ({
timestamp: dateFormat(item.timestamp),
transactionType: getTransactionType(item.type),
balanceChange: item.amount,
token: item.resolvedAsset,
txId: item.transactionHash,
}));
}, [addNotification, normalizedLendingEvents, orderOptions.orderDirection]);
const paginatedLendingEvents = useMemo(
() =>
normalizedLendingEvents.slice(
page * pageSize,
page * pageSize + pageSize,
),
[normalizedLendingEvents, page],
);
return (
<BaseConversionsHistoryFrame
exportData={exportData}
name="lending"
table={
<Table
setOrderOptions={setOrderOptions}
orderOptions={orderOptions}
columns={COLUMNS_CONFIG}
rows={paginatedLendingEvents}
rowTitle={generateRowTitle}
isLoading={loading}
className="bg-gray-80 text-gray-10 lg:px-6 lg:py-4"
noData={t(translations.common.tables.noData)}
loadingData={t(translations.common.tables.loading)}
dataAttribute="earn-history-table"
/>
}
setPage={setPage}
page={page}
totalItems={total}
isLoading={loading}
>
{children}
</BaseConversionsHistoryFrame>
);
};
|
# Nutshell Installer
An installer for disposable, containerized applications.
For further information on how to use Nutshell Installer, visit our documentation page [here.](https://nutshell.me)
Nutshell Installer allows you to access your favourite apps - from web browsers, to office tools, to entire desktops - in a way where each session is destroyed when closed.
These applications also feature isolation from your device core systems through the power of Docker containers and Linuxserver.io webtops, meaning hackers won't so easily be able to access what's precious to you.
## Nutshell Installer features both Disposable and Persistent Applications.
In short, disposable applications are your everyday programs - from web browsers, to office tools, to whole other desktops - which self-destruct when you close them.
This ensures third parties cannot maintain a trace on your data, keeping you safe and anonymous as you go about your daily tasks.
Disposable application also have the benefit of being opened in their own ecosystem, separate from the host machine.
Though persistent applications also have this "containerized" feature that keeps them separate from your computer, they will not get destroyed upon closing. Thus, we recommend installation of disposable applications.
## Installation
There are two ways to approach the installation of Nutshell:
1. Download the Nutshell Operating System
2. Download the Nutshell Installer
Nutshell OS comes fully-featured, with some addons - installation instructions are found [here.](https://nutshellos.me)
This section details installation of Nutshell Installer itself, for usage on your current OS.
### Installing Nutshell Installer
1. Clone the repository, and extract the files to your Desktop.
2. Open the command window in your Desktop, and run ```pip install -r requirements.txt``` - this installs all the necessary packages to run the installer.
3. Open another tab in your web browser and type: "download docker for {Your OS}"
4. Follow the link to the Docker site, and download it.
5. Execute the "main.py" file in the "Nutshell_Config" folder - the Installer UI should appear.
**NOTE:** For easier access, consider making a Desktop shortcut for the "main.py" file.
## Using the Installer
There are two buttons you should familiarise yourself with: Application Search and Manage Applications.
### Application Search
This button takes you to another window, asking whether you want to view Disposable or Persistent applications. Select whichever option you prefer.
A new window should pop up. Here, you can browse for whatever one of our programs you'd like to install - here is a list of them below:
1. Firefox Browser
2. Chromium Browser
3. Opera Browser
4. Ubuntu Desktop
5. Fedora Desktop
6. Arch Desktop
7. Debian Desktop
8. Alpine Desktop
9. LibreOffice Suite
Found an app you want? Click on its icon.
Once it's been installed, you'll see a new Python file/shortcut appear on the Desktop. Click on it - note that the first boot will take a couple of minutes to initiate. **Do not get impatient!**
After a while, the program should start up.
### Manage Applications
This button takes you to a page where you can view all your existing applications. When you click on a specific app's icon, you'll be able to see when you first built it.
Additionally, there is a button providing you the option to uninstall a program. Should you wish to do so, simply click the button and select "OK" in the popup window.
## Conclusion
While Nutshell OS is not a perfect system, it aims to improve the quality of security in our daily lives - for in the Digital Age, nothing is more important than ensuring everything we love dearly is kept safe.
~ Gladon Chua
|
import { prisma } from "@/libs/prisma";
import { NextResponse } from 'next/server'
export async function GET(
request: Request,
{ params: { id, asistenciaId } }: { params: { id: string; asistenciaId: string } }
) {
try {
const miembro = await prisma.asistencia.findFirst({
where: {
id: Number(asistenciaId),
miembroId: Number(id)
}
})
if (miembro) {
return new NextResponse(JSON.stringify({
success: "La asistencia se ha encontrado con éxito.",
data: miembro,
}), { status: 201 });
}
}catch (error) {
return new NextResponse(
JSON.stringify({ error: "No se encuentra la asistencia o ID. Por favor, inténtelo de nuevo.", }),
{ status: 400 }
);
}
}
export async function PUT(
request: Request,
{ params: { asistenciaId } }: { params: { id: string; asistenciaId: string } }
) {
try {
const json = await request.json()
const updateAsistencia = await prisma.asistencia.update({
where: {
id: parseInt(asistenciaId, 10)
},
data: {
fecha: json.fecha //|| null,
}
})
if (updateAsistencia) {
return new NextResponse(JSON.stringify({
success: "La asistencia se ha actualizado con éxito.",
data: updateAsistencia,
}), { status: 201 });
}
}catch (error) {
return new NextResponse(
JSON.stringify({ error: "Verifique todos los campos. Por favor, inténtelo de nuevo.", }),
{ status: 400 }
);
}
}
export async function PATCH(
request: Request,
{ params: { asistenciaId } }: { params: { id: string; asistenciaId: string } }
) {
try {
const json = await request.json()
const updateAsistencia = await prisma.asistencia.update({
where: {
id: Number(asistenciaId)
},
data: json
})
if (updateAsistencia) {
return new NextResponse(JSON.stringify({
success: "La asistencia se ha actualizado con éxito.",
data: updateAsistencia,
}), { status: 201 });
}
}catch (error) {
return new NextResponse(
JSON.stringify({ error: "Verifique todos los campos. Por favor, inténtelo de nuevo.", }),
{ status: 400 }
);
}
}
export async function DELETE(
request: Request,
{ params: { asistenciaId } }: { params: { id: string; asistenciaId: string } }
) {
try {
const deleteAsistencia = await prisma.asistencia.delete({
where: {
id: Number(asistenciaId)
}
})
if (deleteAsistencia) {
return new NextResponse(JSON.stringify({
success: "La asistencia se ha eliminado con éxito.",
data: deleteAsistencia,
}), { status: 201 });
}
}catch (error) {
return new NextResponse(
JSON.stringify({ error: "No existe la asistencia o ID. Por favor, inténtelo de nuevo.", }),
{ status: 400 }
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.