text
stringlengths 184
4.48M
|
|---|
namespace Harvest.Tests.Tests;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Common;
using Moq;
using Moq.Protected;
[TestFixture]
public class TimeEntriesRequestBuilderTests
{
public class WhenListingTimeEntries : BaseTestFixture
{
[Test]
public async Task ShouldSetQueryParameters()
{
// Arrange
(HarvestServiceClient harvestServiceClient, Mock<HttpMessageHandler> httpMessageHandler) =
this.GetHarvestServiceClient();
long userId = 1234;
long clientId = 2341;
long projectId = 3412;
long taskId = 4123;
string externalReferenceId = "abc";
bool isBilled = true;
bool isRunning = true;
var updatedSince = new DateTime(2023, 4, 9);
var from = new DateTime(2023, 4, 1);
var to = new DateTime(2023, 4, 10);
int page = 2;
int perPage = 100;
string expectedRequestUrl =
$"https://api.harvestapp.com/v2/time_entries?user_id={userId}&client_id={clientId}&project_id={projectId}&task_id={taskId}&external_reference_id={externalReferenceId}&is_billed={isBilled}&is_running={isRunning}&updated_since={HttpUtility.UrlEncode(updatedSince.ToString("O"))}&from={HttpUtility.UrlEncode(from.ToString("O"))}&to={HttpUtility.UrlEncode(to.ToString("O"))}&page={page}&per_page={perPage}"
.ToLowerInvariant();
// Act
await harvestServiceClient.TimeEntries.GetAsync(c =>
{
c.QueryParameters.UserId = userId;
c.QueryParameters.ClientId = clientId;
c.QueryParameters.ProjectId = projectId;
c.QueryParameters.TaskId = taskId;
c.QueryParameters.ExternalReferenceId = externalReferenceId;
c.QueryParameters.IsBilled = isBilled;
c.QueryParameters.IsRunning = isRunning;
c.QueryParameters.UpdatedSince = updatedSince;
c.QueryParameters.From = from;
c.QueryParameters.To = to;
c.QueryParameters.Page = page;
c.QueryParameters.PerPage = perPage;
});
// Assert
httpMessageHandler.Protected().Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(req =>
req.RequestUri.ToString().ToLowerInvariant() == expectedRequestUrl),
ItExpr.IsAny<CancellationToken>());
}
}
}
|
package util.geom;
import components.BoundBox;
import components.Transform3D;
#if nme
import nme.geom.Rectangle;
#elseif flash
import flash.geom.Rectangle;
#else
import jeash.geom.Rectangle;
#end
import util.TypeDefs;
/**
* ...
* @author Glenn Ko
*/
#if alternExpose @:expose #end
class AABBUtils
{
public static inline var MAX_VALUE:Float = 1.7976931348623157e+308;
public static inline var THRESHOLD:Float = .1;
public static inline function getRect(aabb:BoundBox, threshold:Float=THRESHOLD):Rectangle {
return new Rectangle(aabb.minX, aabb.minZ, clampMagnitude(aabb.maxX - aabb.minX, threshold), clampMagnitude(aabb.maxZ - aabb.minZ, threshold) );
}
public static inline function clampMagnitude(mag:Float, threshold:Float=THRESHOLD):Float {
return mag < 0 ? threshold : mag < threshold ? threshold : mag;
}
private static inline function abs(val:Float):Float {
return val < 0 ? -val : val;
}
private static inline function norm(w:Int):Int
{
return w != 0 ? w < 0 ? -1 : 1 : 0;
}
public static inline function getString(aabb:BoundBox):String {
return "AABB: "+[aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ];
}
public static inline function pointInside(aabb:BoundBox, pt:Vec3):Bool {
return !(pt.x < aabb.minX || pt.y < aabb.minY || pt.z < aabb.minZ || pt.x > aabb.maxX || pt.y > aabb.maxY || pt.z > aabb.maxZ);
}
public static inline function intersectsEachOther(a:BoundBox, b:BoundBox):Bool {
return !(a.maxX < b.minX || a.maxY < b.minY || a.maxZ < b.minZ || a.minX > b.maxX || a.minY > b.maxY || a.minZ > b.maxZ);
}
public static inline function intersectsBoundValues(a:BoundBox, minX:Float, minY:Float, minZ:Float, maxX:Float, maxY:Float, maxZ:Float):Bool {
return !(a.maxX < minX || a.maxY < minY || a.maxZ < minZ || a.minX > maxX || a.minY > maxY || a.minZ > maxZ);
}
public static inline function transform(aabb:BoundBox, t:Transform3D):Void {
var minX = aabb.minX;
var minY = aabb.minY;
var minZ = aabb.minZ;
var maxX = aabb.maxX;
var maxY = aabb.maxY;
var maxZ = aabb.maxZ;
AABBUtils.reset(aabb);
var x = minX;
var y = minY;
var z = minZ;
var ex;
var ey;
var ez;
ex = x * t.a + y * t.b + z * t.c + t.d;
ey = x * t.e + y * t.f + z * t.g + t.h;
ez = x * t.i + y * t.j + z * t.k + t.l;
AABBUtils.expand(ex, ey, ez, aabb);
x = maxX;
y = minY;
z = minZ;
ex = x * t.a + y * t.b + z * t.c + t.d;
ey = x * t.e + y * t.f + z * t.g + t.h;
ez = x * t.i + y * t.j + z * t.k + t.l;
AABBUtils.expand(ex, ey, ez, aabb);
x = minX;
y = maxY;
z = minZ;
ex = x * t.a + y * t.b + z * t.c + t.d;
ey = x * t.e + y * t.f + z * t.g + t.h;
ez = x * t.i + y * t.j + z * t.k + t.l;
AABBUtils.expand(ex, ey, ez, aabb);
x = minX;
y = minY;
z = maxZ;
ex = x * t.a + y * t.b + z * t.c + t.d;
ey = x * t.e + y * t.f + z * t.g + t.h;
ez = x * t.i + y * t.j + z * t.k + t.l;
AABBUtils.expand(ex, ey, ez, aabb);
x = aabb.maxX;
y = aabb.maxY;
z = aabb.minZ;
ex = x * t.a + y * t.b + z * t.c + t.d;
ey = x * t.e + y * t.f + z * t.g + t.h;
ez = x * t.i + y * t.j + z * t.k + t.l;
AABBUtils.expand(ex, ey, ez, aabb);
x = minX;
y = maxY;
z = maxZ;
ex = x * t.a + y * t.b + z * t.c + t.d;
ey = x * t.e + y * t.f + z * t.g + t.h;
ez = x * t.i + y * t.j + z * t.k + t.l;
AABBUtils.expand(ex, ey, ez, aabb);
x = maxX;
y = minY;
z = maxZ;
ex = x * t.a + y * t.b + z * t.c + t.d;
ey = x * t.e + y * t.f + z * t.g + t.h;
ez = x * t.i + y * t.j + z * t.k + t.l;
AABBUtils.expand(ex, ey, ez, aabb);
x = aabb.maxX;
y = aabb.maxY;
z = aabb.maxZ;
ex = x * t.a + y * t.b + z * t.c + t.d;
ey = x * t.e + y * t.f + z * t.g + t.h;
ez = x * t.i + y * t.j + z * t.k + t.l;
AABBUtils.expand(ex, ey, ez, aabb);
}
public static inline function match(aabb:BoundBox, refAABB:BoundBox):Void {
aabb.minX = refAABB.minX;
aabb.minY = refAABB.minY;
aabb.minZ = refAABB.minZ;
aabb.maxX = refAABB.maxX;
aabb.maxY = refAABB.maxY;
aabb.maxZ = refAABB.maxZ;
}
public static inline function setToMax(aabb:BoundBox):Void {
aabb.minX = -MAX_VALUE;
aabb.minY = -MAX_VALUE;
aabb.minZ = -MAX_VALUE;
aabb.maxX = MAX_VALUE;
aabb.maxY = MAX_VALUE;
aabb.maxZ = MAX_VALUE;
}
public static inline function reset(aabb:BoundBox):Void {
aabb.minX = MAX_VALUE;
aabb.minY = MAX_VALUE;
aabb.minZ = MAX_VALUE;
aabb.maxX = -MAX_VALUE;
aabb.maxY = -MAX_VALUE;
aabb.maxZ = -MAX_VALUE;
}
public static inline function expand2(aabb:BoundBox, refAABB:BoundBox):Void {
if (refAABB.minX < aabb.minX) aabb.minX = refAABB.minX;
if (refAABB.minY < aabb.minY) aabb.minY = refAABB.minY;
if (refAABB.minZ < aabb.minZ) aabb.minZ = refAABB.minZ;
if (refAABB.maxX > aabb.maxX) aabb.maxX = refAABB.maxX;
if (refAABB.maxY > aabb.maxY) aabb.maxY = refAABB.maxY;
if (refAABB.maxZ > aabb.maxZ) aabb.maxZ = refAABB.maxZ;
}
public static inline function expand(x:Float, y:Float, z:Float, aabb:BoundBox):Void {
if (x < aabb.minX) aabb.minX = x;
if (y < aabb.minY) aabb.minY = y;
if (z < aabb.minZ) aabb.minZ = z;
if (x > aabb.maxX) aabb.maxX = x;
if (y > aabb.maxY) aabb.maxY = y;
if (z > aabb.maxZ) aabb.maxZ = z;
}
public static inline function expandWithPoint(vec:Vec3, aabb:BoundBox):Void {
if (vec.x < aabb.minX) aabb.minX = vec.x;
if (vec.y < aabb.minY) aabb.minY = vec.y;
if (vec.z < aabb.minZ) aabb.minZ = vec.z;
if (vec.x > aabb.maxX) aabb.maxX = vec.x;
if (vec.y > aabb.maxY) aabb.maxY = vec.y;
if (vec.z > aabb.maxZ) aabb.maxZ = vec.z;
}
// -- Alternativa3d methods
/*
public function checkRays(origins:Array<Vec3>, directions:Array<Vec3>, raysLength:Int):Bool {
for (var i:int = 0; i < raysLength; i++) {
var origin:Vector3D = origins[i];
var direction:Vector3D = directions[i];
if (origin.x >= minX && origin.x <= maxX && origin.y >= minY && origin.y <= maxY && origin.z >= minZ && origin.z <= maxZ) return true;
if (origin.x < minX && direction.x <= 0 || origin.x > maxX && direction.x >= 0 || origin.y < minY && direction.y <= 0 || origin.y > maxY && direction.y >= 0 || origin.z < minZ && direction.z <= 0 || origin.z > maxZ && direction.z >= 0) continue;
var a:Number;
var b:Number;
var c:Number;
var d:Number;
var threshold:Number = 0.000001;
// Intersection of X and Y projection
if (direction.x > threshold) {
a = (minX - origin.x)/direction.x;
b = (maxX - origin.x)/direction.x;
} else if (direction.x < -threshold) {
a = (maxX - origin.x)/direction.x;
b = (minX - origin.x)/direction.x;
} else {
a = 0;
b = 1e+22;
}
if (direction.y > threshold) {
c = (minY - origin.y)/direction.y;
d = (maxY - origin.y)/direction.y;
} else if (direction.y < -threshold) {
c = (maxY - origin.y)/direction.y;
d = (minY - origin.y)/direction.y;
} else {
c = 0;
d = 1e+22;
}
if (c >= b || d <= a) continue;
if (c < a) {
if (d < b) b = d;
} else {
a = c;
if (d < b) b = d;
}
// Intersection of XY and Z projections
if (direction.z > threshold) {
c = (minZ - origin.z)/direction.z;
d = (maxZ - origin.z)/direction.z;
} else if (direction.z < -threshold) {
c = (maxZ - origin.z)/direction.z;
d = (minZ - origin.z)/direction.z;
} else {
c = 0;
d = 1e+22;
}
if (c >= b || d <= a) continue;
return true;
}
return false;
}
*/
public static inline function checkSphere(aabb:BoundBox, sphere:Vector3D):Bool {
return sphere.x + sphere.w > aabb.minX && sphere.x - sphere.w < aabb.maxX && sphere.y + sphere.w > aabb.minY && sphere.y - sphere.w < aabb.maxY && sphere.z + sphere.w > aabb.minZ && sphere.z - sphere.w < aabb.maxZ;
}
static inline var THRESHOLD_RAY:Float = 0.000001;
public static function intersectRay(aabb:BoundBox, origin:Vector3D, direction:Vector3D):Bool {
if (origin.x >= aabb.minX && origin.x <= aabb.maxX && origin.y >= aabb.minY && origin.y <= aabb.maxY && origin.z >= aabb.minZ && origin.z <= aabb.maxZ) return true;
if (origin.x < aabb.minX && direction.x <= 0) return false;
if (origin.x > aabb.maxX && direction.x >= 0) return false;
if (origin.y < aabb.minY && direction.y <= 0) return false;
if (origin.y > aabb.maxY && direction.y >= 0) return false;
if (origin.z < aabb.minZ && direction.z <= 0) return false;
if (origin.z > aabb.maxZ && direction.z >= 0) return false;
var a:Float;
var b:Float;
var c:Float;
var d:Float;
// Intersection of X and Y projection
if (direction.x > THRESHOLD_RAY ) {
a = (aabb.minX - origin.x) / direction.x;
b = (aabb.maxX - origin.x) / direction.x;
} else if (direction.x < -THRESHOLD_RAY) {
a = (aabb.maxX - origin.x) / direction.x;
b = (aabb.minX - origin.x) / direction.x;
} else {
a = -1e+22;
b = 1e+22;
}
if (direction.y > THRESHOLD_RAY) {
c = (aabb.minY - origin.y) / direction.y;
d = (aabb.maxY - origin.y) / direction.y;
} else if (direction.y < -THRESHOLD_RAY) {
c = (aabb.maxY - origin.y) / direction.y;
d = (aabb.minY - origin.y) / direction.y;
} else {
c = -1e+22;
d = 1e+22;
}
if (c >= b || d <= a) return false;
if (c < a) {
if (d < b) b = d;
} else {
a = c;
if (d < b) b = d;
}
// Intersection of XY and Z projections
if (direction.z > THRESHOLD_RAY) {
c = (aabb.minZ - origin.z) / direction.z;
d = (aabb.maxZ - origin.z) / direction.z;
} else if (direction.z < -THRESHOLD_RAY) {
c = (aabb.maxZ - origin.z) / direction.z;
d = (aabb.minZ - origin.z) / direction.z;
} else {
c = -1e+22;
d = 1e+22;
}
if (c >= b || d <= a) return false;
return true;
}
}
|
//Author ANTHONY GOTZ
//Class CPT-187
//START-DATE 4/15/20
//Purpose This class keeps track and validates all users and logins
package edu.cpt187.gotz.participation;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class UserAccounts
{
private final boolean FILE_FOUND = true;//declare and initalize FILE FOUND
private final boolean FILE_NOT_FOUND = false;//declare and initalize FILE NOT FOUND
private final int NOT_FOUND = -1;//declare and initalize NOT FOUND
private final int RESET_VALUE = 0;//declare and initalize RESET VALUE
private final int MAXIMUM_RECORDS = 50;//declare and initalize MAXIMUM RECORDS
private String[] userNames = new String[MAXIMUM_RECORDS];//declare and initalize username array
private String[] passwords = new String[MAXIMUM_RECORDS];//declare and initalize password array
private boolean fileFoundFlag = false;//declare and initalize file found flag
private String masterFileName = "";//declare and initalize master file name
private int recordCount = 0;//declare and initalize record count
private int searchedIndex = 0;//declare and initalize searched index
UserAccounts(String borrowedFileName)//non default constructor
{
masterFileName = borrowedFileName;//assignment statement
}
public void setUserAccountsArrays()//load array
{
recordCount = RESET_VALUE;//sets record count
try//begin try
{
Scanner infile = new Scanner (new FileInputStream(masterFileName));//create infile
while(infile.hasNext() == true && recordCount < MAXIMUM_RECORDS)//begin while less than max
{
userNames[recordCount] = infile.next();//set id
passwords[recordCount] = infile.next();//set title
recordCount++;//increment counter
}//end while less than max
infile.close();//close infile
}//end try
catch (IOException ex)//begin exception catch
{
recordCount = NOT_FOUND;//assignment statement
}//end exception catch
}//end load array
public void setSearchedIndex(String borrowedUserName)//set searched index overloaded
{
searchedIndex = getSeqSearch(borrowedUserName);//assignment statement
}//end set searched index
public void setSearchedIndex(String borrowedUserName, String borrowedPassword)//set searched index overloaded
{
searchedIndex = getSeqSearch(borrowedUserName);//assignment statement
fileFoundFlag = getPasswordMatch(borrowedPassword);//assignment statement
}//end set searched index
public void setWriteOneRecord(String borrowedUserName, String borrowedPassword)//set write one record
{
setSearchedIndex(borrowedUserName);
if(searchedIndex < 0)//if username doesnt match if
{
try//begin try block
{
PrintWriter filePW = new PrintWriter(new FileWriter(masterFileName, true));//constructor
filePW.printf("%n%s\t%s%n", borrowedUserName, borrowedPassword);//write to file
fileFoundFlag = FILE_FOUND;//assignment statement
recordCount++;//increment counter
filePW.close();//close file writer
}//end try block
catch(IOException ex)//begin catch block
{
fileFoundFlag = FILE_NOT_FOUND;//assignment statement
}//end catch block
}//end if
else//username does match else
{
fileFoundFlag = FILE_NOT_FOUND;//assignment statement
}//end else
}//end write one record
public int getSearchedIndex()//get searched index
{
return searchedIndex;//return statement
}//end get searched index
public int getRecordCount()//get record count
{
return recordCount;//return statement
}//end get record count
public String getFileName()//get file name
{
return masterFileName;//return statement
}//end get file name
public boolean getFileFoundFlag()//get file found flag
{
return fileFoundFlag;//return statement
}//end get file found flag
public boolean getPasswordMatch(String borrowedborrowedPassword)//get password match
{
boolean localMatch = FILE_NOT_FOUND;//assignment statement
if(searchedIndex >= 0)//if viable username if
{
if(borrowedborrowedPassword.equals(passwords[searchedIndex]))//passwords match if
{
localMatch = FILE_FOUND;//assignment statement
}//end if
}//end if
return localMatch;//return statement
}// end get password match
public int getSeqSearch(String borrowedborrowedUserName)// get username match
{
int localIndex = 0;//assignment statement
int localfound = NOT_FOUND;//assignment statement
while(localIndex < recordCount)//While searching
{
if(borrowedborrowedUserName.equals(userNames[localIndex]))//if usernames match
{
localfound = localIndex;//assignment statement
localIndex = recordCount;//assignment statement
}//end usernames match if
else//beging match else
{
localIndex++;//increment counter
}//end match else
}//end still searching loop
return localfound;//return statement
}//end get username match
}
|
---
layout: post
title: "[파이썬][Django] 정적 파일 서빙 및 설정 방법과 예제"
description: " "
date: 2023-08-29
tags: [python,django]
comments: true
share: true
---
Django에서 정적 파일을 서빙하고 설정하는 방법과 예제를 설명하겠습니다. 정적 파일은 CSS, JavaScript, 이미지 및 기타 웹 자산을 제공하는 데 사용됩니다.
### 정적 파일 서빙 설정
1. **Django 설정 파일 (settings.py) 수정**:
`settings.py` 파일에서 정적 파일 관련 설정을 확인하고 수정합니다.
```python
# settings.py
# 정적 파일 디렉토리 경로 설정
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
# 개발 중에는 DEBUG 모드에서만 사용
if DEBUG:
STATICFILES_DIRS += [os.path.join(BASE_DIR, 'your_additional_static_folder')]
# 프로덕션 환경에서는 웹 서버 (예: Nginx)를 통해 제공하는 것을 고려
```
- `STATIC_URL`: 정적 파일을 불러올 때 사용하는 URL 경로입니다.
- `STATICFILES_DIRS`: 정적 파일이 저장된 디렉토리 경로를 설정합니다.
- `DEBUG`: 개발 중인 환경에서만 정적 파일을 Django에서 서빙하도록 설정합니다.
2. **URL 패턴 설정 (urls.py)**:
`urls.py` 파일에 정적 파일을 서빙하는 URL 패턴을 추가합니다.
```python
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# 다른 URL 패턴들 추가
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
```
위 코드는 개발 환경에서만 동작하도록 설정되어 있습니다.
### 정적 파일 사용
3. **정적 파일 디렉토리 생성**:
프로젝트 루트 디렉토리에 `static` 디렉토리를 생성하고 그 안에 정적 파일 (예: CSS, JavaScript, 이미지)을 배치합니다.
```
arduino
myproject/
├── myapp/
│ ├── ...
├── static/
│ ├── css/
│ │ ├── styles.css
│ ├── js/
│ │ ├── scripts.js
│ ├── img/
│ │ ├── image.jpg
│ │ ├── ...
```
4. **템플릿에서 정적 파일 사용**:
```html
<pre>
<code>
{% raw %}
HTML 템플릿에서 정적 파일을 불러올 때는 `{% static %}` 템플릿 태그를 사용합니다.
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
<script src="{% static 'js/scripts.js' %}"></script>
<img src="{% static 'img/image.jpg' %}" alt="이미지">
{% endraw %}
</code>
</pre>
```
이제 Django에서 정적 파일을 서빙하고 설정하는 방법을 알았습니다. 이러한 설정을 통해 웹 애플리케이션에서 정적 파일을 효과적으로 관리하고 제공할 수 있습니다. 개발 환경에서는 Django에서 서빙하고, 프로덕션 환경에서는 웹 서버 (예: Nginx)를 통해 제공하는 것이 일반적인 관례입니다.
|
import 'package:flutter/material.dart';
import '../../widgets.dart';
class DismissiblePage extends StatefulWidget {
const DismissiblePage({Key? key}) : super(key: key);
@override
State<DismissiblePage> createState() => _DismissiblePageState();
}
class _DismissiblePageState extends State<DismissiblePage> {
final items = List<String>.generate(20, (i) => 'Item ${i + 1}');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: appbarWidget('Dismissible'),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return Dismissible(
key: Key(item),
onDismissed: (direction) {
setState(() {
items.removeAt(index);
});
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('$item dismissed')));
},
background: Container(color: Colors.red),
confirmDismiss: (DismissDirection direction) async {
return await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Confirm"),
content: const Text(
"Are you sure you wish to delete this item?"),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text("DELETE")),
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text("CANCEL"),
),
],
);
},
);
},
child: ListTile(
title: Text(item),
),
);
},
),
);
}
}
|
'use client'
import { HomeIcon, TruckIcon, CogIcon, ClipboardDocumentListIcon, DocumentIcon, ComputerDesktopIcon, ArrowPathIcon, ArrowTrendingUpIcon } from "@heroicons/react/24/outline"
import Link from "next/link"
import Image from "next/image"
import triaWhite from '@/public/logos/triaWhite.png'
import { useState } from "react"
export default function Sidebar({open}:{open:Boolean}) {
const [selectedLink, setSelectedLink] = useState('link1')
const active = "flex gap-4 text-lg text-white"
const nonactive = "flex gap-4 text-lg hover:text-gray-300"
return (
<div className='fixed left-0 z-40 h-screen hidden md:flex md:flex-col justify-between p-2 bg-gray-800 text-gray-400'>
<div className="px-4 py-8 space-y-4">
<Link href={'/'} className={selectedLink === 'link1' ? active : nonactive} onClick={() => setSelectedLink('link1')}>
<HomeIcon className="w-6 h-6"/>
Home
</Link>
<p className="font-light tracking-wider text-sm pt-4">MATERIAL RODANTE</p>
<Link href={'/Vehiculos'} className={selectedLink === 'link2' ? active : nonactive} onClick={() => setSelectedLink('link2')}>
<TruckIcon className="w-6 h-6"/>
Vehículos
</Link>
<Link href={'/EAVMs'} className={selectedLink === 'link3' ? active : nonactive} onClick={() => setSelectedLink('link3')}>
<CogIcon className="w-6 h-6"/>
Ejes EAVM
</Link>
<p className="font-light tracking-wider text-sm pt-4">GESTIÓN ADIF</p>
<Link href={'/Documentacion/General'} className={selectedLink === 'link4' ? active : nonactive} onClick={() => setSelectedLink('link4')}>
<DocumentIcon className="w-6 h-6"/>
Documentación
</Link>
<Link href={'/gestor_documentacion'} className={selectedLink === 'link5' ? active : nonactive} onClick={() => setSelectedLink('link5')}>
<ComputerDesktopIcon className="w-6 h-6"/>
Gestor Doc.
</Link>
</div>
<div className="mb-10 py-4 flex space-x-4 text-sm justify-center border-t border-gray-600">
<p className="">Creado por </p>
<Image src={triaWhite} width = {66} height={21} alt='logo adif' priority/>
</div>
</div>
)
}
|
package com.acooly.module.lottery.portal;
import com.acooly.core.common.facade.ResultBase;
import com.acooly.core.common.web.AbstractStandardEntityController;
import com.acooly.core.common.web.support.JsonEntityResult;
import com.acooly.core.common.web.support.JsonResult;
import com.acooly.core.utils.Ids;
import com.acooly.core.utils.Strings;
import com.acooly.module.lottery.domain.Lottery;
import com.acooly.module.lottery.facade.LotteryFacade;
import com.acooly.module.lottery.facade.order.LotteryCountOrder;
import com.acooly.module.lottery.facade.order.LotteryOrder;
import com.acooly.module.lottery.facade.result.LotteryCountResult;
import com.acooly.module.lottery.facade.result.LotteryResult;
import com.acooly.module.lottery.service.LotteryService;
import com.acooly.module.lottery.service.LotteryWinnerService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 抽奖活动 抽象实现
*
* @author zhangpu
*/
public abstract class AbstractLotteryPortalController
extends AbstractStandardEntityController<Lottery, LotteryService> {
@Resource
protected LotteryFacade lotteryFacade;
@Resource
protected LotteryWinnerService lotteryWinnerService;
/**
* 抽奖
*
* @param request
* @param response
* @return
*/
@RequestMapping("lottery")
@ResponseBody
public JsonEntityResult<LotteryResult> lottery(
HttpServletRequest request, HttpServletResponse response) {
JsonEntityResult<LotteryResult> result = new JsonEntityResult<LotteryResult>();
try {
doLotteryCheck(request);
LotteryOrder lotteryOrder =
new LotteryOrder(getLotteryCode(request), getLotteryUser(request), "测试");
LotteryResult lotteryResult = lotteryFacade.lottery(lotteryOrder);
result.setEntity(lotteryResult);
} catch (Exception e) {
handleException(result, "抽奖", e);
}
return result;
}
/**
* 添加抽奖次数
*
* @param request
* @param response
* @return
*/
@RequestMapping("addCount")
@ResponseBody
public JsonResult addLotteryCount(HttpServletRequest request, HttpServletResponse response) {
JsonResult result = new JsonResult();
try {
String requCount = request.getParameter("count");
if (Strings.isBlank(requCount) || !Strings.isNumeric(requCount)) {
throw new RuntimeException("必须传入增加的次数参数:count");
}
LotteryCountOrder lotteryCountOrder =
new LotteryCountOrder(getLotteryCode(request), getLotteryUser(request));
lotteryCountOrder.setCount(Integer.parseInt(requCount));
lotteryCountOrder.setGid(Ids.gid());
lotteryCountOrder.setPartnerId(Ids.getDid());
ResultBase resultBase = lotteryFacade.addLotteryCount(lotteryCountOrder);
result.setCode(resultBase.getCode());
result.setMessage(resultBase.getDetail());
result.setSuccess(resultBase.success());
} catch (Exception e) {
handleException(result, "增加抽奖次数", e);
}
return result;
}
@RequestMapping("getCount")
@ResponseBody
public JsonResult getCount(HttpServletRequest request, HttpServletResponse response) {
JsonResult result = new JsonResult();
try {
LotteryCountOrder lotteryCountOrder =
new LotteryCountOrder(getLotteryCode(request), getLotteryUser(request));
lotteryCountOrder.setGid(Ids.gid());
lotteryCountOrder.setPartnerId(Ids.getDid());
LotteryCountResult lotteryCountResult = lotteryFacade.getLotteryCount(lotteryCountOrder);
result.setCode(lotteryCountResult.getCode());
result.setMessage(lotteryCountResult.getDetail());
result.setSuccess(lotteryCountResult.success());
result.appendData("totalTimes", lotteryCountResult.getTotalTimes());
result.appendData("playTimes", lotteryCountResult.getPlayTimes());
} catch (Exception e) {
handleException(result, "查询抽奖次数", e);
}
return result;
}
protected abstract String getLotteryCode(HttpServletRequest request);
protected abstract String getLotteryUser(HttpServletRequest request);
/**
* 根据具体抽奖逻辑check当前用户是否可以参与抽奖
*
* @param request
*/
protected abstract void doLotteryCheck(HttpServletRequest request);
}
|
import Image, { StaticImageData } from "next/image";
import MainBtn from "./MainBtn";
import { useLanguage } from "../_contexts/ContextHooks";
import Icon from "./GoogleIcon";
import { useState } from "react";
import { useInView } from "react-intersection-observer";
type carouselItem = {
id: number;
pES?: string;
pEN?: string;
h3ES?: string;
h3EN?: string;
imgSrc?: StaticImageData;
btn?: {
bgColor: "white" | "blue";
target: boolean;
href: string;
};
};
type carouselItems = carouselItem[];
type CarouselProps = {
carouselItems: carouselItems;
overlay?: boolean;
controls?: string;
};
const Carousel = ({ carouselItems, overlay, controls }: CarouselProps) => {
const { language } = useLanguage();
const [active, setActive] = useState(0);
const [inverted, setInverted] = useState(false);
const { inView: itemInView, ref: itemRef } = useInView({
threshold: 0.3,
triggerOnce: true,
});
const rightArrow = () => {
if (active >= 2) {
return;
} else {
setActive(active + 1);
}
console.log(active);
};
const leftArrow = () => {
if (active === 0) {
return;
} else {
setActive(active - 1);
}
console.log(active);
};
return (
<div
ref={itemRef}
style={{ opacity: "0" }}
className={itemInView ? "carousel fade-up" : "carousel"}
>
{overlay ? <div className="carousel-overlay"></div> : null}
{carouselItems.map((item, index) => {
return (
<div
data-inverted={inverted ? "true" : "false"}
key={index}
className={
active === index ? "carousel-item active" : "carousel-item"
}
>
{item.imgSrc ? (
<div className="carousel-img">
<Image
src={item.imgSrc}
alt="carousel item"
width={700}
height={700}
/>
</div>
) : null}
{language === "ES" ? (
<>
<p>{item.pES}</p>
<h3>{item.h3ES}</h3>
</>
) : (
<>
<p>{item.pEN}</p>
<h3>{item.h3EN}</h3>
</>
)}
{item.btn ? (
<MainBtn
href={item.btn.href}
target={item.btn.target}
bgColor={item.btn.bgColor}
></MainBtn>
) : null}
</div>
);
})}
{controls ? (
<div className="arrow-container">
<div
style={active === 0 ? { opacity: "0.2" } : { opacity: "1" }}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter") {
leftArrow();
setInverted(true);
}
}}
onClick={() => {
leftArrow();
setInverted(true);
}}
className="arrow"
>
<Icon icon="arrow_forward_ios" />
</div>
<div
style={active === 2 ? { opacity: "0.2" } : { opacity: "1" }}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter") {
rightArrow();
setInverted(false);
}
}}
onClick={() => {
rightArrow();
setInverted(false);
}}
className="arrow"
>
<Icon icon="arrow_forward_ios" />
</div>
</div>
) : null}
</div>
);
};
export default Carousel;
|
using Microsoft.EntityFrameworkCore;
using NetTopologySuite.Geometries;
using NetTopologySuite;
namespace EFCoreFilms.entities.seeding
{
public static class SeedingConsultModule
{
public static void Seed(ModelBuilder modelBuilder)
{
var acción = new Gender { Identifier = 1, Name = "Acción" };
var animación = new Gender {Identifier = 2, Name = "Animación" };
var comedia = new Gender {Identifier = 3, Name = "Comedia" };
var cienciaFicción = new Gender {Identifier = 4, Name = "Ciencia ficción" };
var drama = new Gender {Identifier = 5, Name = "Drama" };
modelBuilder.Entity<Gender>().HasData(acción, animación, comedia, cienciaFicción, drama);
var tomHolland = new Actor() { Id = 1, Name = "Tom Holland", BirthDate = new DateTime(1996, 6, 1), Bio = "Thomas Stanley Holland (Kingston upon Thames, Londres; 1 de junio de 1996), conocido simplemente como Tom Holland, es un actor, actor de voz y bailarín británico." };
var samuelJackson = new Actor() { Id = 2, Name = "Samuel L. Jackson", BirthDate = new DateTime(1948, 12, 21), Bio = "Samuel Leroy Jackson (Washington D. C., 21 de diciembre de 1948), conocido como Samuel L. Jackson, es un actor y productor de cine, televisión y teatro estadounidense. Ha sido candidato al premio Óscar, a los Globos de Oro y al Premio del Sindicato de Actores, así como ganador de un BAFTA al mejor actor de reparto." };
var robertDowney = new Actor() { Id = 3, Name = "Robert Downey Jr.", BirthDate = new DateTime(1965, 4, 4), Bio = "Robert John Downey Jr. (Nueva York, 4 de abril de 1965) es un actor, actor de voz, productor y cantante estadounidense. Inició su carrera como actor a temprana edad apareciendo en varios filmes dirigidos por su padre, Robert Downey Sr., y en su infancia estudió actuación en varias academias de Nueva York." };
var chrisEvans = new Actor() { Id = 4, Name = "Chris Evans", BirthDate = new DateTime(1981, 06, 13) };
var laRoca = new Actor() { Id = 5, Name = "Dwayne Johnson", BirthDate = new DateTime(1972, 5, 2) };
var auliCravalho = new Actor() { Id = 6, Name = "Auli'i Cravalho", BirthDate = new DateTime(2000, 11, 22) };
var scarlettJohansson = new Actor() { Id = 7, Name = "Scarlett Johansson", BirthDate = new DateTime(1984, 11, 22) };
var keanuReeves = new Actor() { Id = 8, Name = "Keanu Reeves", BirthDate = new DateTime(1964, 9, 2) };
modelBuilder.Entity<Actor>().HasData(tomHolland, samuelJackson,
robertDowney, chrisEvans, laRoca, auliCravalho, scarlettJohansson, keanuReeves);
var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);
var agora = new Cinema() { Id = 1, Name = "Agora Mall", Location = geometryFactory.CreatePoint(new Coordinate(-69.9388777, 18.4839233)) };
var sambil = new Cinema() { Id = 2, Name = "Sambil", Location = geometryFactory.CreatePoint(new Coordinate(-69.911582, 18.482455)) };
var megacentro = new Cinema() { Id = 3, Name = "Megacentro", Location = geometryFactory.CreatePoint(new Coordinate(-69.856309, 18.506662)) };
var acropolis = new Cinema() { Id = 4, Name = "Acropolis", Location = geometryFactory.CreatePoint(new Coordinate(-69.939248, 18.469649)) };
var agoraCineOferta = new CinemaOffer { Id = 1, CinemaId = agora.Id, StartDate = DateTime.Today, EndDate = DateTime.Today.AddDays(7), DiscountPercentage = 10 };
var salaDeCine2DAgora = new CinemaRoom()
{
Id = 1,
CinemaId = agora.Id,
Price = 220,
CinemaType = CinemaType.TwoDimensions
};
var salaDeCine3DAgora = new CinemaRoom()
{
Id = 2,
CinemaId = agora.Id,
Price = 320,
CinemaType = CinemaType.ThreeDimensions
};
var salaDeCine2DSambil = new CinemaRoom()
{
Id = 3,
CinemaId = sambil.Id,
Price = 200,
CinemaType= CinemaType.TwoDimensions
};
var salaDeCine3DSambil = new CinemaRoom()
{
Id = 4,
CinemaId = sambil.Id,
Price = 290,
CinemaType = CinemaType.ThreeDimensions
};
var salaDeCine2DMegacentro = new CinemaRoom()
{
Id = 5,
CinemaId = megacentro.Id,
Price = 250,
CinemaType = CinemaType.TwoDimensions
};
var salaDeCine3DMegacentro = new CinemaRoom()
{
Id = 6,
CinemaId = megacentro.Id,
Price= 330,
CinemaType = CinemaType.ThreeDimensions
};
var salaDeCineCXCMegacentro = new CinemaRoom()
{
Id = 7,
CinemaId = megacentro.Id,
Price = 450,
CinemaType = CinemaType.CxC
};
var salaDeCine2DAcropolis = new CinemaRoom()
{
Id = 8,
CinemaId = acropolis.Id,
Price = 250,
CinemaType = CinemaType.TwoDimensions
};
var acropolisCineOferta = new CinemaOffer { Id = 2, CinemaId = acropolis.Id, StartDate = DateTime.Today, EndDate = DateTime.Today.AddDays(5), DiscountPercentage = 15 };
modelBuilder.Entity<Cinema>().HasData(acropolis, sambil, megacentro, agora);
modelBuilder.Entity<CinemaOffer>().HasData(acropolisCineOferta, agoraCineOferta);
modelBuilder.Entity<CinemaRoom>().HasData(salaDeCine2DMegacentro, salaDeCine3DMegacentro, salaDeCineCXCMegacentro, salaDeCine2DAcropolis, salaDeCine2DAgora, salaDeCine3DAgora, salaDeCine2DSambil, salaDeCine3DSambil);
var avengers = new Films()
{
Id = 1,
Title = "Avengers",
OnBillboard = false,
ReleaseDate = new DateTime(2012, 4, 11),
posterURL = "https://upload.wikimedia.org/wikipedia/en/8/8a/The_Avengers_%282012_film%29_poster.jpg",
};
var entidadGeneroPelicula = "FilmsGender";
var generoIdPropiedad = "GendersIdentifier";
var peliculaIdPropiedad = "FilmsId";
var entidadSalaDeCinePelicula = "CinemaRoomFilms";
var salaDeCineIdPropiedad = "cinemaRoomsId";
modelBuilder.Entity(entidadGeneroPelicula).HasData(
new Dictionary<string, object> { [generoIdPropiedad] = acción.Identifier, [peliculaIdPropiedad] = avengers.Id },
new Dictionary<string, object> { [generoIdPropiedad] = cienciaFicción.Identifier, [peliculaIdPropiedad] = avengers.Id }
);
var coco = new Films()
{
Id = 2,
Title = "Coco",
OnBillboard = false,
ReleaseDate = new DateTime(2017, 11, 22),
posterURL = "https://upload.wikimedia.org/wikipedia/en/9/98/Coco_%282017_film%29_poster.jpg"
};
modelBuilder.Entity(entidadGeneroPelicula).HasData(
new Dictionary<string, object> { [generoIdPropiedad] = animación.Identifier, [peliculaIdPropiedad] = coco.Id }
);
var noWayHome = new Films()
{
Id = 3,
Title = "Spider-Man: No way home",
OnBillboard = false,
ReleaseDate = new DateTime(2021, 12, 17),
posterURL = "https://upload.wikimedia.org/wikipedia/en/0/00/Spider-Man_No_Way_Home_poster.jpg"
};
modelBuilder.Entity(entidadGeneroPelicula).HasData(
new Dictionary<string, object> { [generoIdPropiedad] = cienciaFicción.Identifier, [peliculaIdPropiedad] = noWayHome.Id },
new Dictionary<string, object> { [generoIdPropiedad] = acción.Identifier, [peliculaIdPropiedad] = noWayHome.Id },
new Dictionary<string, object> { [generoIdPropiedad] = comedia.Identifier, [peliculaIdPropiedad] = noWayHome.Id }
);
var farFromHome = new Films()
{
Id = 4,
Title = "Spider-Man: Far From Home",
OnBillboard = false,
ReleaseDate = new DateTime(2019, 7, 2),
posterURL = "https://upload.wikimedia.org/wikipedia/en/0/00/Spider-Man_No_Way_Home_poster.jpg"
};
modelBuilder.Entity(entidadGeneroPelicula).HasData(
new Dictionary<string, object> { [generoIdPropiedad] = cienciaFicción.Identifier, [peliculaIdPropiedad] = farFromHome.Id },
new Dictionary<string, object> { [generoIdPropiedad] = acción.Identifier, [peliculaIdPropiedad] = farFromHome.Id },
new Dictionary<string, object> { [generoIdPropiedad] = comedia.Identifier, [peliculaIdPropiedad] = farFromHome.Id }
);
// Para matrix pongo la fecha en el futuro
var theMatrixResurrections = new Films()
{
Id = 5,
Title = "The Matrix Resurrections",
OnBillboard = true,
ReleaseDate = new DateTime(2100, 1, 1),
posterURL = "https://upload.wikimedia.org/wikipedia/en/5/50/The_Matrix_Resurrections.jpg",
};
modelBuilder.Entity(entidadGeneroPelicula).HasData(
new Dictionary<string, object> { [generoIdPropiedad] = cienciaFicción.Identifier, [peliculaIdPropiedad] = theMatrixResurrections.Id },
new Dictionary<string, object> { [generoIdPropiedad] = acción.Identifier, [peliculaIdPropiedad] = theMatrixResurrections.Id },
new Dictionary<string, object> { [generoIdPropiedad] = drama.Identifier, [peliculaIdPropiedad] = theMatrixResurrections.Id }
);
modelBuilder.Entity(entidadSalaDeCinePelicula).HasData(
new Dictionary<string, object> { [salaDeCineIdPropiedad] = salaDeCine2DSambil.Id, [peliculaIdPropiedad] = theMatrixResurrections.Id },
new Dictionary<string, object> { [salaDeCineIdPropiedad] = salaDeCine3DSambil.Id, [peliculaIdPropiedad] = theMatrixResurrections.Id },
new Dictionary<string, object> { [salaDeCineIdPropiedad] = salaDeCine2DAgora.Id, [peliculaIdPropiedad] = theMatrixResurrections.Id },
new Dictionary<string, object> { [salaDeCineIdPropiedad] = salaDeCine3DAgora.Id, [peliculaIdPropiedad] = theMatrixResurrections.Id },
new Dictionary<string, object> { [salaDeCineIdPropiedad] = salaDeCine2DMegacentro.Id, [peliculaIdPropiedad] = theMatrixResurrections.Id },
new Dictionary<string, object> { [salaDeCineIdPropiedad] = salaDeCine3DMegacentro.Id, [peliculaIdPropiedad] = theMatrixResurrections.Id },
new Dictionary<string, object> { [salaDeCineIdPropiedad] = salaDeCineCXCMegacentro.Id, [peliculaIdPropiedad] = theMatrixResurrections.Id }
);
var keanuReevesMatrix = new FilmActor
{
ActorId = keanuReeves.Id,
FilmId = theMatrixResurrections.Id,
Order = 1,
Character = "Neo"
};
var avengersChrisEvans = new FilmActor
{
ActorId = chrisEvans.Id,
FilmId = avengers.Id,
Order = 1,
Character = "Capitán América"
};
var avengersRobertDowney = new FilmActor
{
ActorId = robertDowney.Id,
FilmId = avengers.Id,
Order = 2,
Character = "Iron Man"
};
var avengersScarlettJohansson = new FilmActor
{
ActorId = scarlettJohansson.Id,
FilmId = avengers.Id,
Order = 3,
Character = "Black Widow"
};
var tomHollandFFH = new FilmActor
{
ActorId = tomHolland.Id,
FilmId = farFromHome.Id,
Order = 1,
Character = "Peter Parker"
};
var tomHollandNWH = new FilmActor
{
ActorId = tomHolland.Id,
FilmId = noWayHome.Id,
Order = 1,
Character = "Peter Parker"
};
var samuelJacksonFFH = new FilmActor
{
ActorId = samuelJackson.Id,
FilmId = farFromHome.Id,
Order = 2,
Character = "Samuel L. Jackson"
};
modelBuilder.Entity<Films>().HasData(avengers, coco, noWayHome, farFromHome, theMatrixResurrections);
modelBuilder.Entity<FilmActor>().HasData(samuelJacksonFFH, tomHollandFFH, tomHollandNWH, avengersRobertDowney, avengersScarlettJohansson,
avengersChrisEvans, keanuReevesMatrix);
}
}
}
|
blog/templates/blogにpost_detail.htmlというファイルを作成し、コードエディタで開きます。
こんな感じですね。
blog/templates/blog/post_detail.html
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h2>{{ post.title }}</h2>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endblock %}
もう一度base.htmlを拡張します。 contentブロックでは、投稿の公開日(存在する場合)、タイトル、およびテキストを表示します。 ここで重要なポイントについて見てみます。
{% if ... %} ... {%endif%}は、何かをチェックしたいときに使用できるテンプレートタグです。 (if ... else...をPython入門のチャプターでやったのを覚えていますか?) この場合、投稿のpublished_date(公開日)が空でないかを確認します。
これで、ページを更新してTemplateDoesNotExistがもうなくなったかどうか確認できます。
|
//
// ACreateEventView.swift
// myShelf
//
// Created by Dewashish Dubey on 04/05/24.
//
import SwiftUI
import Firebase
struct ACreateEventView: View {
@FocusState private var isFocused: Bool
@State private var title = ""
@State private var selectedDate = Date()
@State private var selectedTime = Date()
@State private var address = ""
@State private var room = ""
@State private var guest = ""
@State private var capacity = ""
@State private var summary = ""
@State private var showAlert = false
@Environment(\.presentationMode) var presentationMode
var body: some View {
ZStack{
Color.black.ignoresSafeArea(.all)
ScrollView(showsIndicators:false){
VStack{
CustomInputField(imageName: "textformat.alt", title: "Title", text: $title)
.preferredColorScheme(.dark)
.previewLayout(.sizeThatFits)
.padding(.top,20)
HStack {
HStack {
Image(systemName: "calendar")
Text("Date")
Rectangle()
.foregroundColor(.clear)
.frame(width: 3, height: 20)
.background(Color(red: 0.19, green: 0.19, blue: 0.19))
.padding(.leading, 10)
DatePicker("", selection: $selectedDate, displayedComponents: .date)
.labelsHidden()
.datePickerStyle(DefaultDatePickerStyle())
.padding(.leading)
}
.padding([.top, .bottom])
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
.foregroundColor(Color.white)
.background(Color(red: 0.11, green: 0.11, blue: 0.12))
.cornerRadius(8)
.padding(.bottom, 10)
HStack {
HStack {
Image(systemName: "clock")
Text("Time")
Rectangle()
.foregroundColor(.clear)
.frame(width: 3, height: 20)
.background(Color(red: 0.19, green: 0.19, blue: 0.19))
.padding(.leading, 10)
DatePicker("Select a Time", selection: $selectedTime, displayedComponents: .hourAndMinute)
.labelsHidden()
.datePickerStyle(CompactDatePickerStyle())
.padding(.leading)
}
.padding([.top, .bottom])
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
.foregroundColor(Color.white)
.background(Color(red: 0.11, green: 0.11, blue: 0.12))
.cornerRadius(8)
.padding(.bottom, 10)
CustomInputField(imageName: "location", title: "Address", text: $address)
.preferredColorScheme(.dark)
.padding(5)
.previewLayout(.sizeThatFits)
CustomInputField(imageName: "mappin", title: "Room", text: $room)
.preferredColorScheme(.dark)
.padding(5)
.previewLayout(.sizeThatFits)
CustomInputField(imageName: "person", title: "Guest", text: $guest)
.preferredColorScheme(.dark)
.padding(5)
.previewLayout(.sizeThatFits)
HStack {
HStack {
Image(systemName: "person.fill.questionmark")
Text("Capacity")
Rectangle()
.foregroundColor(.clear)
.frame(width: 3, height: 20)
.background(Color(red: 0.19, green: 0.19, blue: 0.19))
.padding(.leading, 10)
TextField("", text: $capacity)
.foregroundColor(.white)
.keyboardType(.numberPad)
.focused($isFocused)
}
.padding([.top, .bottom])
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
.foregroundColor(Color.white)
.background(Color(red: 0.11, green: 0.11, blue: 0.12))
.cornerRadius(8)
.padding(.bottom, 10)
VStack {
HStack {
Image(systemName: "text.book.closed")
Text("Summary")
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.leading, 10)
.padding(.top, 10)
TextField("", text: $summary)
.foregroundColor(.white)
.lineLimit(7) // Allow multiple lines
.frame(maxWidth: .infinity) // Expand horizontally
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
.foregroundColor(Color.white)
.background(Color(red: 0.11, green: 0.11, blue: 0.12))
.cornerRadius(8)
.padding(.bottom, 20)
Button{
addEventToFirebase()
}label: {
Text("Submit")
.padding()
.frame(maxWidth: .infinity)
.padding(.horizontal,20)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
.padding(.bottom,20)
}
.alert(isPresented: $showAlert) {
Alert(title: Text("Event added"), dismissButton: .default(Text("OK")) {
presentationMode.wrappedValue.dismiss()
})
}
Spacer()
}
}
}
.onTapGesture {
isFocused = false
}
}
func addEventToFirebase() {
let db = Firestore.firestore()
var eventData: [String: Any] = [
"title": title,
"selectedDate": selectedDate,
"selectedTime": selectedTime,
"address": address,
"room": room,
"guest": guest,
"capacity": Int(capacity) ?? 0,
"summary": summary
// Add other fields as needed
]
// Add the event to Firebase
/*let docRef = db.collection("events").addDocument(data: eventData) { error in
if let error = error {
print("Error adding event: \(error.localizedDescription)")
} else {
print("Event added successfully!")
// Show alert
showAlert = true
}
}*/
let documentRef = db.collection("events").addDocument(data: eventData)
eventData["uid"] = documentRef.documentID
// Update the document in Firestore with the UID included
documentRef.setData(eventData)
showAlert = true
}
}
struct CustomInputField: View {
var imageName: String
var title: String
@Binding var text: String
var body: some View {
HStack {
HStack {
Image(systemName: imageName)
Text(title)
Rectangle()
.foregroundColor(.clear)
.frame(width: 3, height: 20)
.background(Color(red: 0.19, green: 0.19, blue: 0.19))
.padding(.leading, 10)
TextField("", text: $text)
.foregroundColor(.white)
}
.padding([.top, .bottom])
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
.foregroundColor(Color.white)
.background(Color(red: 0.11, green: 0.11, blue: 0.12))
.cornerRadius(8)
.padding(.bottom, 10)
}
}
#Preview {
ACreateEventView()
}
|
.. _ReferencePhysicsMaterial:
.. rst-class:: searchtitle
PhysicsMaterial
.. rst-class:: searchdescription
This material describes properties of a collider mainly used during collision.
.. include:: Description/PhysicsMaterial.rst
.. cpp:class:: PhysicsMaterial
Base Class: :cpp:type:`Resource`
.. _ReferencePhysicsMaterialProperties:
Properties
----------
.. rst-class:: collapsible
.. cpp:member:: String PhysicsMaterial::Name
Name of resource for display.
.. rst-class:: collapsible
.. cpp:member:: real PhysicsMaterial::Density
Density is used to determine the mass of an object. Mass can be computed as density volume. Density can be set to 0 exactly to produce a massless object, however this should only be done with children objects to add collision.
.. rst-class:: collapsible
.. cpp:member:: real PhysicsMaterial::Restitution
How much an object will bounce during a collision. Values should be in the range[0,1] where 0 is an in-elastic collision and 1 is a fully elastic collision. Note: due to solving constraints with baumgarte energy will not be perfectly conserved with restitution 1.
.. rst-class:: collapsible
.. cpp:member:: real PhysicsMaterial::Friction
How slippery or rough the object is. When friction is 0 the object will be completely slippery. As friction increases sliding objects will stop quicker. The friction of two object's are combined with the formula sqrt(a b).
.. rst-class:: collapsible
.. cpp:member:: bool PhysicsMaterial::HighPriority
If high priority is set, this object's restitution will be used always unless the other material is also high priority. If both are high priority then the max restitution is taken.
.. _ReferencePhysicsMaterialMethods:
Methods
-------
.. rst-class:: collapsible
.. cpp:function:: Resource PhysicsMaterial::RuntimeClone()
Clone a resource for runtime modification.
.. include:: Remarks/PhysicsMaterial.rst
|
import React from 'react'
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native'
import InputStructure from '../components/InputStructure'
import ButtonStructure from '../components/ButtonStructure'
const LogIn = () => {
return (
<View style= {styles.container}>
<View style={styles.titleContainer}>
<Text style={styles.bigTitle}>Welcome Back ! </Text>
<Text style={styles.smallTitle} >Login with Username & password </Text>
</View>
<View style={styles.formContainer}>
<View style={styles.usernameContainer}>
<InputStructure placeholder="Enter your name" label="Username" />
</View>
<View style={styles.passwordContainer}>
<InputStructure placeholder="Enter your password" label="Password" />
</View>
<View style={styles.buttonContainer}>
<ButtonStructure title="Sign In"/>
</View>
</View>
<View style={styles.newAccountContainer}>
<Text style={styles.newAccountText}>Create a new account? {' '}
<TouchableOpacity style={styles.signUpContainer}>
<Text style={styles.signUp}>Sign Up</Text>
</TouchableOpacity>
</Text>
</View>
</View>
)
}
const styles = StyleSheet.create({
container : {
flex:1,
marginLeft:'10%',
marginRight:'10%'
},
titleContainer: {
marginTop:152
},
bigTitle: {
fontSize:30
},
smallTitle: {
fontSize:16
},
formContainer: {
marginTop:67,
shadowColor:'#CECECE',
shadowOffset:{width:-2, height:4},
shadowOpacity:0.2,
shadowRadius:3,
borderRadius:20,
borderWidth:1,
paddingHorizontal:20,
alignItems:'center'
},
usernameContainer: {
marginTop:30
},
passwordContainer: {
marginTop:20
},
buttonContainer: {
marginTop:30,
marginBottom:30
},
newAccountContainer: {
marginTop: 67,
justifyContent:'center',
alignItems:'center'
},
newAccountText: {
fontSize:16,
},
signUp: {
fontSize:16,
color:'#120EDB',
},
signUpContainer:{
}
})
export default LogIn
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<script src="/script.js" type="text/javascript"></script>
<!--Bootstrap library -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4"
crossorigin="anonymous"></script>
<!--Dayschedule widget library from https://dayschedule.com/widget -->
<script src="https://cdn.jsdelivr.net/npm/dayschedule-widget@latest/dist/dayschedule-widget.min.js" defer></script>
<script>
daySchedule.initPopupWidget({
"url": "https://provautoscuolaalvolante.dayschedule.com",
"type": "popup",
"color": {
"primary": "#0f0980",
"secondary": "#afeefe"
}
})
</script>
</head>
<body>
<header>
<nav class="navbar navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="#"> Your Logo </a>
</div>
</nav>
</header>
<div class="container px-3 my-5">
<main>
<div class="row">
<div class="col-md-6 my-auto">
Che bello rivederti
<h1>Benvenuto, <%= nomeUtente %>
</h1>
<p class="lead">
Click on the <strong>book appointment</strong> button to try this out.
You can customize the color, calendar availability, etc., by passing the options on widget
<a href="https://provautoscuolaalvolante.dayschedule.com">
See documentation →
</a>
</p>
</div>
<div class="col-md-6">
<img src="/public/img/galary/login-photo/foto-login.png" class="img-fluid" />
</div>
</div>
<div class="row mt-4 mb-4">
<div class="col-md-6 my-3">
<div class="card">
<div class="card-header">Orthopedic</div>
<div class="card-body">
<h5 class="card-title">Dr Tawang</h5>
<p class="card-text">
With supporting text below as a natural lead-in to additional
content.
</p>
<button class="btn btn-primary"
onclick="openDaySchedule('https://provautoscuolaalvolante.dayschedule.com')">
Book appointment
</button>
</div>
</div>
</div>
</div>
</main>
</div>
<footer class="page-footer font-small pt-4 px-4">
<!-- Footer Text -->
<div class="container d-flex justify-content-center">
<p>©</p>
<p class="copyAnno_P" style="padding-right: 3px;"></p>
<p>Copyright autoscuolealvolante.com Autoscuole Al Volante di Salvatore Torrisi S.r.l.s</p>
</div>
<!-- Footer Text -->
</footer>
</body>
<script>
function copyAnno() {
var dataCorrente = new Date();
var annoCorrente = dataCorrente.getFullYear();
return annoCorrente;
}
function aggiornaAnno() {
var valore = document.querySelector('.copyAnno_P');
if (valore) {
var nuovoValore = copyAnno();
valore.textContent = nuovoValore;
}
}
window.addEventListener('load', aggiornaAnno);
//------
// Ottieni il nome dell'utente dal valore inserito nella pagina dal server
const nomeUtente = "<%= nomeUtente %>"; // Utilizzo di una variabile server-side
// Inserisci il nome dell'utente nell'elemento HTML
document.getElementById('nomeUtente').textContent = nomeUtente;
</script>
</html>
|
// write a program to find tha maximum element in queue in javascript:
class Queue{
constructor(){
this.items = [];
}
enqueue(element){
this.items.push(element)
}
dequeue(){
if (this.isEmpty()) {
return "Queue is empty";
}
return this.items.shift();
}
front(){
if(this.isEmpty()){
return 'Queue is Empty'
}
return this.items[0];
}
isEmpty(){
return this.items.length === 0;
}
size(){
return this.items.length;
}
print(){
console.log(this.items.join(' '));
}
}
function findMaximumElement(queue){
if(queue.isEmpty()){
return "Queue is empty";
}
let max = queue.front();
while(!queue.isEmpty()){
let curEle = queue.dequeue();
if(curEle > max){
max = curEle;
}
}
return max;
}
let myQueue = new Queue();
myQueue.enqueue(5);
myQueue.enqueue(10);
myQueue.enqueue(15);
myQueue.enqueue(8);
console.log("Original Queue:");
myQueue.print();
const maxElement = findMaximumElement(myQueue);
console.log("\nMaximum Element:", maxElement);
|
import { HTMLAttributes, memo, ReactNode } from 'react';
import { classNames, Mods } from '@/shared/lib/classNames/classNames';
import classes from './Card.module.scss';
export type CardVariant = 'normal' | 'outlined' | 'light';
export type CardBorder = 'round' | 'normal' | 'semi';
export type CardPaddings = '0' | '8' | '16' | '24';
interface CardProps extends HTMLAttributes<HTMLDivElement> {
className?: string;
children: ReactNode;
variant?: CardVariant;
maxWidth?: boolean;
maxHeight?: boolean;
paddings?: CardPaddings;
border?: CardBorder;
}
const mapPaddingsToClassName: Record<CardPaddings, string> = {
0: classes.padding0,
8: classes.padding8,
16: classes.padding16,
24: classes.padding24,
};
export const Card = memo(
({
className,
children,
maxWidth,
maxHeight,
variant = 'normal',
paddings = '8',
border = 'normal',
...otherProps
}: CardProps) => {
const mods: Mods = {
[classes.maxWidth]: maxWidth,
[classes.maxHeight]: maxHeight,
};
return (
<div
className={classNames(classes.Card, mods, [
className,
classes[variant],
mapPaddingsToClassName[paddings],
classes[`${border}Radius`],
])}
{...otherProps}
>
{children}
</div>
);
},
);
|
--------------------------------------------------------
-- 고객번호, 고객명, 고객전화번호, 담당직원명, 담당직원직급, 담당직원연봉등급 을 출력하면?
-- <조건>담당직원이 없는 고객도 포함
--------------------------------------------------------
select
c.cus_ no "고객번호"
, c.cus_name "고객명"
, c.tel_num "고객전화번호"
, e.emp_name "담당직원명"
, e.jikup "담당직원직급"
, s.sal_grade_no "담당직원연봉등급"
from customer c, employee e, salary_grade s
where c.emp_no = e.emp_no(+)
and e.salary between s.min_salary(+) and s.max_salary(+)
-------------------
-- ANSI outer join
-------------------
select
c.cus_ no "고객번호"
, c.cus_name "고객명"
, c.tel_num "고객전화번호"
, e.emp_name "담당직원명"
, e.jikup "담당직원직급"
, s.sal_grade_no "담당직원연봉등급"
from ( customer c left outer join employee e ) left outer join salary_grade s
on ( c.emp_no = e.emp_no ) and e.salary between s.min_salary and s.max_salary
--------------------------------------------------------
-- 고객번호, 고객명, 고객주민번호 를 출력하면?
-- 단, 연봉이 3000 이상인 담당직원이 담당한 고객이어야 한다.
--------------------------------------------------------
select
c.cus_no "고객번호"
, c.cus_name "고객명"
, c.jumin_num "고객주민번호"
from customer c, employee e
where c.emp_no = e.emp_no
and e.salary >=3000
-------------------
-- ANSI inner join
-------------------
select
c.cus_no "고객번호"
, c.cus_name "고객명"
, c.jumin_num "고객주민번호"
from customer c inner join employee e
on c.emp_no = e.emp_no
where e.salary >=3000
--------------------------------------------------------
-- 고객번호, 고객명, 고객주민번호 를 출력하면?
-- 단, 40살 이상인 담당직원이 담당한 고객이어야 한다.
--------------------------------------------------------
select
c.cus_no "고객번호"
, c.cus_name "고객명"
, c.jumin_num "고객주민번호"
from customer c, employee e
where c.emp_no = e.emp_no
and
( to_number (to_char (sysdate, 'YYYY' ))
-
to_number( case substr(e.jumin_num, 7, 1)
when '1' then '19'
when '2' then '19'
else '20'
end
|| substr(e.jumin_num, 1, 6))+1
)
>= 40
-------------------
-- ANSI inner join
-------------------
select
c.cus_no "고객번호"
, c.cus_name "고객명"
, c.jumin_num "고객주민번호"
from customer c inner join employee e on c.emp_no = e.emp_no
where
( to_number ( to_char( sysdate, 'YYYY') )
-
to_number( decode ( substr(e.jumin_num, 7, 1), '1', '19', '2', '19', '20' )
|| substr(e.jumin_num, 1, 6) ) +1
) >= 40;
--------------------------------------------------------
-- 직원명, 직원 전화번호와 고객명, 고객 전화번호를 종으로 붙여 출력하면?
-- <조건> 중복하지 말 것
--------------------------------------------------------
select
e.emp_num "직원명"
, e.phone_num "직원전화번호"
union cus_name "고객명"
, c.tel_num "고객전화번호"
from employee e, customer c
where e.emp_no = c.emp_no(+);
--------------------------------------------------------
-- 최고 연봉을 받는 직원을 검색하라
--------------------------------------------------------
select * from employee where max(salary) ;
--------------------------------------------------------
-- 평균 연봉보다 많이 받는 직원을 검색하라
--------------------------------------------------------
select * from employee e where e.salary >= avg(e.salary)
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Portfolio</title>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="mediaqueries.css" />
</head>
<body>
<nav id="desktop-nav">
<div class="logo">Oletilwe Lephalala</div>
<div>
<ul class="nav-links">
<li><a href="#about">About</a></li>
<li><a href="#experience">Experience</a></li>
<li><a href="#projects">Project</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</nav>
<nav id="hamburger-nav">
<div class="logo">Oletilwe Lephalala</div>
<div class="hamburger-menu">
<div class="hamburger-icon" onclick="toggleMenu()">
<span></span>
<span></span>
<span></span>
</div>
<div class="menu-links">
<li><a href="#about" onclick="toggleMenu()">About</a></li>
<li><a href="#experience" onclick="toggleMenu()" >Experience</a></li>
<li><a href="#projects" onclick="toggleMenu()" >Project</a></li>
<li><a href="#contact" onclick="toggleMenu()" >Contact</a></li>
</div>
</div>
</nav>
<section id="profile">
<div class="section__pic-container">
<img src="./assets/Capture laptop.PNG" alt="Oletilwe profile picture" />
</div>
<div class="section__text">
<p class="section__text__p1">Hello im </p>
<h1 class="title">Oletilwe Lephalala</h1>
<p class="section__text__p2">Full stack Web Developer</p>
<div class="btn-container">
<button
class="btn btn-color-2" onclick="window.open('./assets/Oletilwe Lephalala Cv.pdf')">
Download CV
</button>
<button
class="btn btn-color-1" onclick="location.href='./#contact'">
Contact Info
</button>
</div>
<div id="socials-container">
<img src="./assets/linkedin.png" alt="My linkedin Profile" class="icon" onclick="location.href='https:www.linkedin.com/in/oletilwe-lephalala-214941280'"/>
<img src="./assets/github.png" alt="My github Profile" class="icon" onclick="location.href='https:github.com/oletilwe'"/>
</div>
</div>
</section>
<section id="about">
<p class="section__text__p1">Get to know more</p>
<h1 class="title">About Me</h1>
<div class="section-container">
<div class="about-details-container">
<div class="about-containers">
<div class="details-container">
<img src="./assets/experience.png" alt="Experience icon" class="icon" />
<h3>Experience</h3>
<p>festive season sales assistent<br /></p>
<p>Cape Union Mart</p>
</div>
<div class="details-container">
<img src="./assets/education.png" alt="Education icon" class="icon" />
<h3>Education</h3>
<p>Diploma in Systems Development<br /></p>
<p>Certificate in full stack Web Development <br /></p>
<p>Certificate in Software Engineering (2023 - present)<br /></p>
</div>
</div>
<div class="text-container">
<p>I am a recent graduate with a Systems Development Diploma, i also have a Certificate in Full Stack Web Development from udemy. I am also studying towards
a Certificate in Software Engineering. I enjoy developing websites especially Frontend and i am still bettering my skills in areas like User Experience(UX) and User Interface(UI).
I am a very good team worker and im also very good with communication and problem solving.
</p>
</div>
</div>
</div>
<img src="./assets/arrow.png" alt="arrow icon" class="icon arrow" onclick="location.href='./#experience'"/>
</section>
<section id="experience">
<P class="section__text__p1">Explore My</P>
<h1 class="title">Experience</h1>
<div class="experience-details-container">
<div class="about-containers">
<div class="details-container">
<h2 class="experience-sub-title">Frontend Development</h2>
<div class="article-container">
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon" />
<div>
<h3>HTML</h3>
<p>Intermediate</p>
</div>
</article>
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon" />
<div>
<h3>CSS</h3>
<p>Intermediate</p>
</div>
</article>
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon" />
<div>
<h3>Bootstrap</h3>
<p>intermediate</p>
</div>
</article>
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon" />
<div>
<h3>Javascript</h3>
<p>intermediate</p>
</div>
</article>
</div>
</div>
<div class="details-container">
<h2 class="experience-sub-title">Backend Development</h2>
<div class="article-container">
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon" />
<div>
<h3>Node.js</h3>
<p>Basic</p>
</div>
</article>
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon" />
<div>
<h3>React.js</h3>
<p>intermediate</p>
</div>
</article>
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon" />
<div>
<h3>Github</h3>
<p>intermediate</p>
</div>
</article>
<article>
<img src="./assets/checkmark.png" alt="Experience icon" class="icon" />
<div>
<h3>C</h3>
<p>Basic</p>
</div>
</article>
</div>
</div>
</div>
</div>
<img src="./assets/arrow.png" alt="arrow icon" class="icon arrow" onclick="location.href='./#projects'"/>
</section>
<section id="projects">
<p class="section__text__p1">Browse My Recent</p>
<h1 class="title">projects</h1>
<div class="experience-details-container">
<div class="about-containers">
<div class="details-container color-container">
<div class="article-container">
<img src="./assets/Capture logo.PNG" alt="project 1" class="project-img" />
</div>
<h2 class="experience-sub-title project-title">Car Brain</h2>
<div class="btn-container">
<button class="btn btn-color-2 project-btn" onclick="location.href='https://github.com/oletilwe/CarBrain'">
Github
</button>
</div>
</div>
<div class="details-container color-container">
<div class="article-container">
<img src="./assets/Capture project.PNG" alt="project 2" class="project-img" />
</div>
<h2 class="experience-sub-title project-title">project comming soon !!</h2>
</div>
<div class="details-container color-container">
<div class="article-container">
<img src="./assets/Capture project.PNG" alt="project 3" class="project-img" />
</div>
<h2 class="experience-sub-title project-title">project comming soon !!</h2>
</div>
</div>
</div>
<img src="./assets/arrow.png" alt="arrow icon" class="icon arrow" onclick="location.href='./#projects'"/>
</section>
<section id="contact">
<p class="section__text__p1">Get in touch</p>
<h1 class="title">Contact Me</h1>
<div class="contact-info-upper-container">
<div class="contact-info-container">
<img src="./assets/email.png" alt="email icon" class="icon contact-icon email-icon" />
<p>oletilwelephalala8@gmail.com</p>The Car Blog
</div>
<div class="contact-info-container">
<img src="./assets/linkedin.png" alt="linkedin icon" class="icon contact-icon" />
<p><a href="https://www.linkedin.com/in/oletilwe-lephalala-214941280/">linkedin</a></p>
</div>
</div>
<img src="./assets/arrow.png" alt="arrow icon" class="icon arrow" onclick="location.href='./#contact'"/>
</section>
<footer>
<nav>
<div class="nav-links-container">
<ul class="nav-links">
<li><a href="#about">About</a></li>
<li><a href="#experience">Experience</a></li>
<li><a href="#projects">Project</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</nav>
<p>Copyright © 2024 Oletilwe Lephalala. All Rights Reserved</p>
</footer>
<script src="script.js"></script>
</body>
</html>
|
interface IntSet {
public boolean contains(int x); // Retorna true se x esta no conjunto
public boolean add(int x); // Adiciona x ao conjunto (devolve true se conseguir)
public boolean remove(int x); // Remove x do conjunto (devolve true se conseguir)
public int size(); // Retorna o numero de elementos do conjunto
public void clear(); // Limpa o conjunto (torna-o vazio)
// Metodos a adicionar (nao existentes na classe base)
public boolean equals(IntSet s); // Retorna true se ambos os conjuntos sao iguais
public IntSet intersection(IntSet s); // devolve um novo conjunto: a intersecao de ambos
}
public class BooleanArrayIntSet implements IntSet {
private int size;
private boolean[] isElemento;
public BooleanArrayIntSet(int n) {
size = 0;
isElemento = new boolean[n+1];
}
@Override
public boolean contains(int x) {
return isElemento[x];
}
@Override
public boolean add(int x) {
if (isElemento[x]) return false;
isElemento[x] = true;
size++;
return true;
}
@Override
public boolean remove(int x) {
if (!isElemento[x]) return false;
isElemento[x] = false;
size--;
return true;
}
@Override
public int size() {
return size;
}
@Override
public void clear() {
size = 0;
isElemento = new boolean[isElemento.length];
}
@Override
public boolean equals(IntSet s) {
if (this.size != s.size()) return false;
for (int i=0; i<isElemento.length; i++)
if (isElemento[i] && !s.contains(i)) return false;
return true;
}
@Override
public IntSet intersection(IntSet s) {
IntSet novo = new BooleanArrayIntSet(isElemento.length);
for (int i=0; i<isElemento.length-1; i++)
if (s.contains(i) && contains(i)) novo.add(i);
return novo;
}
// public static void main(String[] args) {
// IntSet set1 = new BooleanArrayIntSet(5);
// IntSet set2 = new BooleanArrayIntSet(4);
// set1.add(1);
// set1.add(5);
// set2.add(4);
// IntSet set3 = set1.intersection(set2);
// System.out.println(set3.contains(1));
// }
}
|
package com.hello.member.global;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
@Configuration
public class IpSensor implements HandlerInterceptor {
private static final ThreadLocal<String> clientIPThreadLocal = new ThreadLocal<>();
private final ObjectMapper objectMapper;
private final String headerType = "X-Forwarded-For";
public IpSensor(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
String ip = request.getHeader(headerType);
clientIPThreadLocal.set(ip);
return true;
}
@Override
public void afterCompletion(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex)
throws Exception {
clientIPThreadLocal.remove();
}
public String getClientIP() {
return clientIPThreadLocal.get();
}
}
|
# Nuxt 3 Minimal Starter
Look at the [Nuxt 3 documentation](https://nuxt.com/docs/getting-started/introduction) to learn more.
## Setup
Make sure to install the dependencies:
```bash
# npm
npm install
# pnpm
pnpm install
# yarn
yarn install
# bun
bun install
```
## Development Server
Start the development server on `http://localhost:3000`:
```bash
# npm
npm run dev
# pnpm
pnpm run dev
# yarn
yarn dev
# bun
bun run dev
```
## Production
Build the application for production:
```bash
# npm
npm run build
# pnpm
pnpm run build
# yarn
yarn build
# bun
bun run build
```
Locally preview production build:
```bash
# npm
npm run preview
# pnpm
pnpm run preview
# yarn
yarn preview
# bun
bun run preview
```
## Benefit in Nuxtjs
- 內建 Dev Tool 協助開發
- 內建具備 `vite-plugin-pages`, `vite-plugin-vue-layouts`, `unplugin-vue-router`, `unplugin-vue-components` 等套件功能
- 提供常用元件以及組合函式 `NuxtPage`, `NuxtLink`, `NuxtLayout`, `NuxtPicture` 等,詳細請見[官方文件](https://nuxt.com/docs/api/components/)
- 使用已包裝過的 `@nuxtjs/tailwindcss`,並藉由 `tailwind-config-viewer` 提供視覺化文件供開發使用
- 除了 components 自動載入,另外 Vue3 的函式,如;`ref`, `computed`,`lifecycle hooks` 以及 `/composable` 目錄內的組合函式也都自動載入
- 完善的 error handle 機制
- Layout 實作方式為一般 component ,不同於 `vite-plugin-vue-layouts` 修改路由的方式處理
Check out the [deployment documentation](https://nuxt.com/docs/getting-started/deployment) for more information.
|
// SPDX-License-Identifier: GPL-3.0
/*
Balancer V2 mixins for the Enzyme Protocol.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@enzymefinance/contracts/release/utils/AssetHelpers.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "hardhat/console.sol";
import "./interfaces/IBalancerV2Vault.sol";
/// @title BalancerV2ActionsMixin Contract
/// @author JustSomeGeeks Hackathon Team <https://github.com/justsomegeeks>
/// @notice Mixin contract for interacting with BalancerV2
abstract contract BalancerV2ActionsMixin is AssetHelpers {
address private immutable BALANCER_V2_VAULT;
constructor(address _balancerV2Vault) public {
BALANCER_V2_VAULT = _balancerV2Vault;
}
/// @dev Helper to do batch swap using batch steps provided by off-chain Balancer SOR
function __balancerV2BatchSwap(
IBalancerV2Vault.SwapKind _swapKind,
IBalancerV2Vault.BatchSwapStep[] memory _swaps,
address[] memory _assets,
IBalancerV2Vault.FundManagement memory _funds,
int256[] memory _limits,
uint256 _deadline
) internal {
__approveAssetMaxAsNeeded(_assets[0], BALANCER_V2_VAULT, _swaps[0].amount);
IBalancerV2Vault(BALANCER_V2_VAULT).batchSwap(
_swapKind,
_swaps,
_assets,
_funds,
_limits,
_deadline
);
}
/// @dev Helper to add liquidity
function __balancerV2Lend(
bytes32 _poolId,
address _sender,
address _recipient,
IBalancerV2Vault.JoinPoolRequest memory _request
) internal {
__approveAssetMaxAsNeeded(_request.assets[0], BALANCER_V2_VAULT, _request.maxAmountsIn[0]);
__approveAssetMaxAsNeeded(_request.assets[1], BALANCER_V2_VAULT, _request.maxAmountsIn[1]);
IBalancerV2Vault(BALANCER_V2_VAULT).joinPool(_poolId, _sender, _recipient, _request);
}
/// @dev Helper to remove liquidity
function __balancerV2Redeem(
bytes32 _poolId,
address _sender,
address payable _recipient,
IBalancerV2Vault.ExitPoolRequest memory _request
) internal {
__approveAssetMaxAsNeeded(
_request.assets[0],
BALANCER_V2_VAULT,
_request.minAmountsOut[0]
);
IBalancerV2Vault(BALANCER_V2_VAULT).exitPool(_poolId, _sender, _recipient, _request);
}
// STATE GETTERS //
/// @notice Gets the `BALANCER_V2_VAULT` variable
/// @return balancerV2Vault_ The `BALANCER_V2_VAULT` variable value
function getBalancerV2Vault() public view returns (address balancerV2Vault_) {
return BALANCER_V2_VAULT;
}
}
|
"use client";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { ENDDATE } from "@/features/questions/constants";
import { Loader2 } from "lucide-react";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useRef, useState, useTransition } from "react";
import { setHomeworkAnswer } from "../services/actions";
type Props = {
answer: string;
index: number;
collection: string;
refreshOpticalAnswers: () => void;
};
type State = {
input: string;
disabled: boolean;
};
const INITIAL_STATE: State = { disabled: true, input: "" };
const HomeworkAnswerForm = ({
index,
answer,
collection,
refreshOpticalAnswers,
}: Props) => {
const disabled = useMemo(() => new Date(ENDDATE) < new Date(), []);
const pathname = usePathname();
const form = useRef<null | HTMLFormElement>(null);
const textarea = useRef<null | HTMLTextAreaElement>(null);
const [isPending, startTransition] = useTransition();
const [props, setProps] = useState(INITIAL_STATE);
useEffect(() => {
setProps((prev) => ({ ...prev, input: answer }));
if (!textarea.current) return;
textarea.current.value = answer;
}, [answer]);
const handleChange = () => {
if (!form.current) return;
const formData = new FormData(form.current);
const input = formData.get("input")?.toString() || "";
const disabled = input === answer;
setProps({ input, disabled });
};
const action = async () => {
startTransition(async () => {
try {
await setHomeworkAnswer(collection, index, props.input, pathname);
form.current!.reset();
refreshOpticalAnswers(); // <- これがなかったら optimistic の値が更新されない
setProps((prev) => ({ ...prev, disabled: true }));
} catch (error) {
console.log(error);
}
});
};
return (
<form
className="space-y-2"
ref={form}
onChange={handleChange}
action={action}
>
<Textarea
ref={textarea}
name="input"
className="bg-white text-xs font-extralight"
placeholder="請輸入答案"
disabled={disabled}
/>
<Button
className="flex w-full items-center gap-2"
disabled={isPending || props.disabled || disabled}
>
<span>{answer ? "更新" : "送出"}</span>
{isPending ? <Loader2 className="animate-spin" /> : null}
</Button>
</form>
);
};
export default HomeworkAnswerForm;
|
import Image from "next/image";
import React from "react";
interface CertificateCardProps {
title: string;
issuedBy: string;
issueDate: string;
description: string;
pdfLink: string;
imageUrl: string;
}
const CertificateCard = ({
title,
issuedBy,
issueDate,
description,
pdfLink,
imageUrl,
}: CertificateCardProps) => {
return (
<div className="max-w-md mx-auto h-full border-2 rounded-md border-input bg-card shadow-sm hover:text-accent-foreground overflow-hidden p-4 hover:border-blue-500 transition-colors duration-300 flex flex-col">
<div className="flex-grow">
<Image
src={imageUrl}
alt={`${title} preview`}
width={480}
height={360}
className="w-full object-cover"
/>
<div className="p-4">
<h2 className="text-xl font-bold text-card-foreground">{title}</h2>
<p className="text-sm text-gray-600">Issued by: {issuedBy}</p>
<p className="text-sm text-gray-600">Issue Date: {issueDate}</p>
<p className="mt-2 text-gray-600">{description}</p>
</div>
</div>
<div className="mt-auto">
<a
href={pdfLink}
target="_blank"
rel="noopener noreferrer"
className="text-blue-500 hover:underline block"
>
View Full Certificate
</a>
</div>
</div>
);
};
export default CertificateCard;
|
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* The path to the "home" route for your application.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
$this->mapAbnermoukeProConsoleRoutes();
$this->mapWhatsAppRoutes();
$this->mapToolRoutes();
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
/**
* Define the "abnermouke/pros" console routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapAbnermoukeProConsoleRoutes()
{
Route::middleware('abnermouke.pros.console')
->namespace('App\Interfaces\Pros\Console\Controllers')
->group(base_path('routes/abnermouke/pros/console.php'));
}
protected function mapWhatsAppRoutes()
{
Route::middleware('abnermouke.pros.console')
->namespace('App\Interfaces\Pros\WhatsApp\Controllers')
->group(base_path('routes/whatsapp/console.php'));
}
protected function mapToolRoutes()
{
Route::middleware('abnermouke.pros.console')
->namespace('App\Interfaces\Tool\Jump\Controllers')
->group(base_path('routes/whatsapp/tool.php'));
}
}
|
/**
* @file Fish.h
* @author Bryce Cooperkawa
*
*
*/
#ifndef AQUARIUM_FISH_H
#define AQUARIUM_FISH_H
#include "Item.h"
#include <wx/dc.h>
/**
* Base class for a fish
* This applies to all of the fish, but not the decor
* items in the aquarium.
*/
class Fish : public Item {
private:
/// Fish speed in the X direction
/// in pixels per second
double mSpeedX;
/// Fish speed in the Y direction
/// in pixels per second
double mSpeedY;
protected:
Fish(Aquarium *aquarium, const std::wstring &filename);
public:
/// Default constructor (disabled)
Fish() = delete;
/// Copy constructor (disabled)
Fish(const Fish &) = delete;
/// Assignment operator
void operator=(const Fish &) = delete;
void Update(double elapsed);
/// Gets the X speed
double GetSpeedX() {return mSpeedX;}
/// Gets the Y speed
double GetSpeedY() {return mSpeedY;}
virtual int Custom()=0;
};
#endif //AQUARIUM_FISH_H
|
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, regexp_replace, current_timestamp, current_date, length
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, TimestampType, DoubleType
spark = SparkSession.builder \
.appName('comments_medallion_tables_creation') \
.getOrCreate()
bucket_name = "yt_statistics"
path = f"gs://{bucket_name}/comments.csv"
schema = StructType([\
StructField("number", IntegerType()), \
StructField("video_id", StringType()), \
StructField("comment", StringType()), \
StructField("likes", DoubleType()), \
StructField("sentiment", DoubleType()), \
])
# original CSV with 18409 number of rows but some rows have a bad format and add more rows after reading with Spark
landing_table = spark.read.csv(path, header=True, schema=schema, multiLine=True)
# 18920 | 518 rows added (1036 rows with null values if we are adding one extra row for every bad formatted row)
# print("landing_table_count:", landing_table.count())
spark.sql('''
CREATE TABLE IF NOT EXISTS comments_bronze (
number INTEGER,
video_id STRING,
comment STRING,
likes INTEGER,
sentiment INTEGER,
ingested_datetime TIMESTAMP,
ingested_date DATE
)
USING PARQUET
PARTITIONED BY (ingested_date)
''')
bronze = landing_table.withColumn("ingested_datetime", current_timestamp()) \
.withColumn("ingested_date", current_date())
bronze.write.insertInto("comments_bronze", overwrite=True)
# spark.sql("SELECT * FROM comments_bronze").show(30)
# creation of silver table
spark.sql('''
CREATE TABLE IF NOT EXISTS comments_silver (
number INTEGER,
video_id STRING,
comment STRING,
likes INTEGER,
sentiment INTEGER,
ingested_datetime TIMESTAMP,
ingested_date DATE
)
USING PARQUET
PARTITIONED BY (ingested_date)
''')
silver = bronze.dropna()
# identify row with special characters
# silver_special_chars = silver.filter(silver.comment.rlike("[^\x00-\x7F]|[\n]"))
# removing special characters
silver = silver.withColumn("comment", regexp_replace("comment", "[^\x00-\x7F]|[\n]", ""))
# silver = silver.filter(length(col("comment")) < 10)
# 17487 | 1433 row dropedd, probably we are having 397 row with null values without considering with the bad format
# print("silver_count:", silver.count())
# create the dead letter table (dead letter: this concept is more related to streaming processing)
dead_letter_table = bronze.filter(col("number").isNull() | col("video_id").isNull() | col("comment").isNull() | col("likes").isNull() | col("sentiment").isNull())
silver.write.insertInto("comments_silver", overwrite=True)
# spark.sql("SELECT * FROM comments_silver").show(30)
# creation of gold table for videos with possitive sentiment count
spark.sql('''
CREATE TABLE IF NOT EXISTS gold_videos_with_possitive_sentiment_count (
video_id STRING,
count INTEGER
)
USING PARQUET
''')
gold_videos_with_possitive_sentiment_count = silver.filter(col("sentiment") == 2.0).select(col("video_id")).groupBy("video_id").count()
gold_videos_with_possitive_sentiment_count.write.insertInto("gold_videos_with_possitive_sentiment_count", overwrite=True)
# spark.sql("SELECT * FROM gold_videos_with_possitive_sentiment_count").show(30)
|
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { startFetchAllPurchaseOrdersByType } from "../../actions/usersActions";
import PurchaseOrderItem from "./PurchaseOrderItem";
const PurchaseOrderList = ({ type }) => {
const { id } = useSelector((state) => state.auth);
const [orderList, setOrderList] = useState([]);
useEffect(() => {
if (type === "BUY") {
startFetchAllPurchaseOrdersByType("BUY", id).then((result) => {
setOrderList(result);
});
}
if (type === "SELL") {
startFetchAllPurchaseOrdersByType("SELL", id).then((result) => {
setOrderList(result);
});
}
}, []);
return (
<div className="purchase-order__list-container">
{orderList.length === 0 && (
<h3 className="purchase-order__no-order-title">
No hay ordenes de {type === "BUY" ? "compra" : "venta"} de aquí
</h3>
)}
{orderList?.map((orderItem) => (
<PurchaseOrderItem {...orderItem} type={type} />
))}
</div>
);
};
export default PurchaseOrderList;
|
"""
Properties:
-> dict store the data in form of key value pair
- dict is mutable data type, we can modify at any point of time
- dict only store unique keys, duplicate keys are not allowed.
- Only immutable data type can be key in the dict, int, float, string, tuple, boolean
- All type of data can be value in the dict.
"""
dict1 = {'a' : 3456, 'b' : 167}
print(dict1, type(dict1))
# {'a': 3456, 'b': 167} <class 'dict'>
dict1['c'] = 500
print(dict1) # {'a': 3456, 'b': 167, 'c': 500}
# duplicate keys are not allowed, if user set the duplicate keys then will overwrite the previous value.
dict2 = {'a' : 111, 'b': 222, 'c' : 333, 'a' : 666}
print("dict2 :", dict2) # {'a': 666, 'b': 222, 'c': 333}
####### add all possible keys ##########
dict3 = {}
dict3[5] = 500
dict3[4.5] = "Hello"
dict3['Python'] = "Programming"
dict3[(3, 5, 7)] = [4, 6, 8, 22, 33]
dict3[True] = (82, 33, 44)
print(dict3)
# {5: 500, 4.5: 'Hello', 'Python': 'Programming', (3, 5, 7): [4, 6, 8, 22, 33], True: (82, 33, 44)}
#dict3[[5, 6, 8]] = 654654
#print(dict3)
# TypeError: unhashable type: 'list'
# Get any value with the help of keys.
print(dict3['Python']) #Programming
print("_"*50)
dict4 = {5: 500, 4.5: 'Hello', 'Python': 'Programming', (3, 5, 7): [4, 6, 8, 22, 33], True: (82, 33, 44)}
for val in dict4.items():
print(val)
print("_"*50)
for k1, v1 in dict4.items():
print("key :", k1)
print("value :", v1)
print("_"*5)
################################## Dictionary Methods #################
print(dir(dict))
# 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'
|
package project_5.android_activities;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import project_5.ru_cafe.Coffee;
import project_5.ru_cafe.MenuItem;
import project_5.ru_cafe.Order;
import project_5.ru_cafe.Donut;
import java.util.ArrayList;
/**
The CurrentOrderDetailActivity class handles user input for viewing the current order via an Android Activity.
CurrentOrderDetailActivity is linked to the current_order_detail.xml file which CurrentOrderDetailActivity's methods control.
It takes in commands from the user, and then calls the appropriate methods in order to carry out the
task inputted by the user.
@author Anthony Hebert, Jacob Cuison
*/
public class CurrentOrderDetailActivity extends AppCompatActivity {
private Order order;
private ArrayList<MenuItem> orderItems;
private static MenuItem selectedItem;
private static int itemPosition;
private ListView currentOrderListView;
private TextView currentOrderSubtotalTextView, currentOrderTaxTextView, currentOrderTotalTextView;
private ArrayAdapter adapter;
private static final int INVALID = -1;
private static final double SALES_TAX = 0.06625;
private static final String ZERO_BALANCE = "0.00";
private static final String NEGATIVE_ZERO_BALANCE = "-0.00";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.current_order_detail);
currentOrderListView = findViewById(R.id.currentOrderListView);
currentOrderSubtotalTextView = findViewById(R.id.currentOrderSubtotalTextView);
currentOrderTaxTextView = findViewById(R.id.currentOrderTaxTextView);
currentOrderTotalTextView = findViewById(R.id.currentOrderTotalTextView);
order = MainMenuActivity.getOrder();
orderItems = order.getOrderItems();
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, orderItems);
currentOrderListView.setAdapter(adapter);
currentOrderListView.setOnItemClickListener(new currentOrderOnClickListener());
setSubtotalFields();
}
/**
Adds the order to MainMenuActivity.storeOrders and notifies the user the order has been placed via a Toast.
@param view is the View that triggers this method
*/
public void placeOrder(View view) {
if (order.getOrderItems().size() == 0){
Toast.makeText(getApplicationContext(), R.string.no_items_added, Toast.LENGTH_SHORT).show();
return;
}
MainMenuActivity.addOrderToStoreOrders(order);
Toast.makeText(getApplicationContext(), R.string.order_placed, Toast.LENGTH_SHORT).show();
finish();
}
/**
Removes the selected item from currentOrderListView.
@param view is the View that triggers this method
*/
public void removeItem(View view) {
if (selectedItem instanceof Coffee){
Coffee coffeeToRemove = (Coffee) selectedItem;
adapter.remove(itemPosition);
currentOrderListView.invalidateViews();
orderItems.remove(coffeeToRemove);
order.setOrderSubtotal(order.getOrderSubtotal() - coffeeToRemove.getPrice());
setSubtotalFields();
}
else if (selectedItem instanceof Donut){
Donut donutToRemove = (Donut) selectedItem;
adapter.remove(itemPosition);
currentOrderListView.invalidateViews();
orderItems.remove(donutToRemove);
order.setOrderSubtotal(order.getOrderSubtotal() - donutToRemove.getPrice());
setSubtotalFields();
}
selectedItem = null;
itemPosition = INVALID;
Toast.makeText(getApplicationContext(), R.string.item_removed, Toast.LENGTH_SHORT).show();
}
/**
Calculates and sets the values for subtotalTextField, salesTaxTextField, and orderTotalTextField by calling the
appropriate methods in main_menu.mainController and ru_cafe.Order.
*/
private void setSubtotalFields(){
currentOrderSubtotalTextView.setText(MainMenuActivity.moneyFormat.format(order.getOrderSubtotal()));
currentOrderTaxTextView.setText(MainMenuActivity.moneyFormat.format(order.getOrderSubtotal() * SALES_TAX));
currentOrderTotalTextView.setText(MainMenuActivity.moneyFormat.format(order.getOrderSubtotal() + (order.getOrderSubtotal() * SALES_TAX)));
if (currentOrderSubtotalTextView.getText().equals(NEGATIVE_ZERO_BALANCE)){
currentOrderSubtotalTextView.setText(ZERO_BALANCE);
currentOrderTaxTextView.setText(ZERO_BALANCE);
currentOrderTotalTextView.setText(ZERO_BALANCE);
}
}
/**
Sets the CurrentOrderDetailActivity.selectedItem and CurrentOrderDetailActivity.itemPosition values.
@param selectedItemFromClick is the user-selected item
@param position is the position of the user-selected item
*/
public static void setSelectedItem(MenuItem selectedItemFromClick, int position) {
selectedItem = selectedItemFromClick;
itemPosition = position;
}
}
|
<template>
<div class="container" :style="{flex:flex}">
<div class="header">
<el-image class="image" :src="playlist.coverImgUrl"></el-image>
<div class="info">
<div class="info-title">
<span class="title">{{ playlist.name }}</span>
<span class="updatetime">( {{ $utils.formartDate(playlist.updateTime,'MM月dd日') }} 更新 )</span>
</div>
<div class="time" v-if="playlist.creator">
<el-image class="time-image" :src="playlist.creator.avatarUrl"></el-image>
<span class="name">{{ playlist.creator.nickname }}</span>
<span class="time-time">{{ $utils.formartDate(playlist.createTime,'yyyy-MM-dd') }}</span>
</div>
<div class="digital">
<span class="playCount"><i class="iconfont icon-playnum"></i> {{ $utils.calculationNum(playlist.playCount) }}次</span>
<span class="collect"><i class="iconfont icon-collect"></i> {{ $utils.calculationNum(playlist.subscribedCount) }}</span>
<span class="comment"><i class="iconfont icon-comment"></i> {{ $utils.calculationNum(playlist.commentCount) }}</span>
</div>
<div class="descs">
<div class="desc">歌单简介</div>
<div class="desc-text">{{ playlist.description }}</div>
</div>
</div>
</div>
<div class="main">
<div class="song">
<div class="song-title">
<span class="title">歌曲列表</span>
<span class="count">{{total}}首歌</span>
</div>
<div class="song-but">
<el-button round @click="wholePlay()"><i class="iconfont icon-audio-play"></i> 播放全部</el-button>
<el-button round><i class="iconfont icon-collect"></i> 收藏</el-button>
</div>
</div>
<songs-list :limit="limit" :offset="page - 1" :songList="list.slice((page - 1) * limit , page * limit)" :loading='loading'></songs-list>
<div class="PlayLogin" v-if="isPlayLogin" @click="onpeLogin">登录后查看全部歌曲</div>
<div v-if="total>limit">
<el-pagination
:page-size="limit"
@current-change='currentChange'
:pager-count="5"
:curren-page='page'
layout="prev, pager, next"
:total="total"
/>
</div>
</div>
</div>
</template>
<script>
import SongsList from '@/components/SongsList'
import { useStore } from 'vuex'
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
export default {
components: { SongsList },
props:{
flex:{ //设置容器大小
type:Number,
default:0,
},
list:{ //歌曲数据
type:Array,
default:new Array
},
playlist:{ //歌单数据
type:Array,
default:new Array
},
limit:{
type:Number,
default:12
},
total:{
type:Number,
default:0
},
loading:{
type:Boolean,
default:true,
}
},
setup(props){
const page = ref(1)
const store = useStore()
const route = useRoute()
const isPlayLogin = computed(()=>{
if(route.fullPath.indexOf("playlist") >= 0){
if(!store.getters.isLogin){
return true
}
}
return false
})
const onpeLogin = ()=>{
store.commit('setloginDialog',true)
}
const currentChange = pageIndex=>{
page.value = pageIndex
}
const wholePlay = ()=>{
store.commit("setPlayList",props.list)
store.commit("setPlayIndex",0)
store.commit("setIsPlay",true)
}
return{
page,
isPlayLogin,
currentChange,
wholePlay,
onpeLogin,
}
}
}
</script>
<style lang="less" scoped>
.header{
display: flex;
flex-direction: row;
margin-bottom: 40px;
.image{
flex: 3;
border-radius: 10px;
}
.info{
flex: 9;
margin-left: 20px;
background-color: #fff;
border-radius: 10px;
padding: 30px 20px 20px 20px;
display: flex;
flex-direction: column;
justify-content: space-between;
.info-title{
.title{
color: var(--color-text-main);
font-size: 25px;
font-weight: 400;
}
.updatetime{
margin-left: 10px;
color: var(--color-text);
font-size: 80%;
}
}
.time{
display: flex;
justify-content: left;
align-items: center;
gap: 20px;
font-size: 90%;
.time-image{
flex: 1;
border-radius: 50%;
}
.name{
flex: 2;
}
.time-time{
flex: 13;
}
}
.digital{
.collect,.comment{
margin-left: 2%;
}
}
.descs{
font-size: 90%;
.desc{
color: var(--color-text-main);
}
.text{
color: var(--color-text);
}
}
}
}
.main{
background-color: #fff;
border-radius: 10px;
padding: 40px 20px 20px 20px;
.song{
display: flex;
flex-direction: row;
justify-content: space-between;
.song-title{
display: flex;
flex-direction: row;
justify-content: left;
align-items: flex-end;
gap: 20px;
.title{
color: var(--color-text-main);
font-size: 25px;
}
.count{
font-size: 90%;
color: var(--color-text);
}
}
}
}
.desc-text{
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
color: var(--color-text);
}
.PlayLogin{
display: block;
width: 100%;
height: 30px;
line-height: 30px;
text-align: center;
background: #ff641e;
color: #fff;
font-size: 14px;
border-radius: 50px;
cursor: pointer;
}
</style>
|
import { useSelector } from "react-redux";
import { CardBody, Col, Row } from "reactstrap";
const Details = () => {
const { showData } = useSelector((state) => state.batchList);
return (
<CardBody>
<Row className="p-1 pt-0">
<Col md="1">
<b>**Route:</b>{" "}
</Col>
<Col md="9">
{showData?.batch?.route && (
<span>
<span>
{showData?.batch?.route?.batch_code}{" / "}
{showData?.batch?.route?.batch_route_name}
{" => "}
{showData?.stations}
</span>
</span>
)}
</Col>
<Col md="2">
{showData?.batch?.route?.template ? (
<span>
{showData?.batch?.route?.template?.template_name} Template
</span>
) : (
<span>No Template</span>
)}
</Col>
</Row>
<Row className="p-1 pt-0">
<Col md="1">
<b>Created:</b>
</Col>
<Col md="3">{showData?.batch?.creation_date}</Col>
<Col md="1">
<b>Last Scan:</b>
</Col>
<Col md="3">
{showData?.last_scan?.date
? showData?.last_scan?.date + " by " + showData?.last_scan?.username
: showData?.batch?.change_date}
</Col>
<Col md="1">
<b>Station:</b>
</Col>
<Col md="3">
{showData?.batch?.station
? showData?.batch?.station?.station_name +
" => " +
showData?.batch?.station?.station_description
: "Station Not Found"}
</Col>
</Row>
<Row className="p-1 pt-0">
<Col md="1">
<b>Export:</b>
</Col>
<Col md="3">
{showData?.batch?.export_date ? (
showData?.batch?.export_count == 1 ? (
<span>
Exported {showData?.batch?.export_count} time{" "}
{showData?.batch?.export_date}
</span>
) : (
<span>
Exported {showData?.batch?.export_count} times Last export{" "}
{showData?.batch?.export_date}
</span>
)
) : (
"Not Exported"
)}
</Col>
<Col md="4">{showData?.batch?.csv_found != 0 && "CSV File Found"}</Col>
</Row>
<Row className="p-1 pt-0">
<Col md="1">
<b>Summary:</b>
</Col>
{showData?.batch?.summary_date ? (
<Col md="6">
<Row>
<Col md="6">Printed {showData?.batch?.summary_date}</Col>
<Col md="6">
{showData?.batch?.summary_count} printed - last by{" "}
{showData?.batch?.summary_user?.username}
</Col>
</Row>
</Col>
) : (
<Col md="6">Not Printed</Col>
)}
</Row>
<Row className="p-1 pt-0">
<Col md="1">
<b>Graphic:</b>
</Col>
<Col md="3">{showData?.batch?.graphic_found}</Col>
{showData?.batch?.to_printer != "0" && (
<Col md="4">
<Row>
<Col md="3">
<b>Printed:</b>
</Col>
<Col md="9">
{showData?.batch?.to_printer} -{" "}
{showData?.batch?.to_printer_date}
</Col>
</Row>
</Col>
)}
</Row>
{showData?.related?.length > 0 && (
<Row className="p-1 pt-0">
<Col md="1">
<b>Related:</b>
</Col>
<Col md="3">
{showData?.related?.map((item) => {
return <span>{item} </span>;
})}
</Col>
</Row>
)}
</CardBody>
);
};
export default Details;
|
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
//import 'package:travel_agency/constant/app_colors.dart';
import 'package:get/get.dart';
import 'package:travel_agency/constant/app_colors.dart';
//import 'package:velocity_x/velocity_x.dart';
import '../../../constant/app_strings.dart';
class FaqScreen extends StatelessWidget {
const FaqScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.black,
),
onPressed: () => Get.back(),
),
),
body: Padding(
padding: EdgeInsets.all(18.h),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Text(
'Faq',
style: TextStyle(
fontSize: 28.sp,
fontWeight: FontWeight.w500,
color: Colors.blue,
),
),
),
SizedBox(height: 40.h,),
customExpansionTile(
title: faqTitle1.tr, description: faqDescription1.tr),
SizedBox(height: 5.h,),
Divider(),
SizedBox(height: 5.h,),
customExpansionTile(
title: faqTitle2.tr, description: faqDescription2.tr),
SizedBox(height: 5.h,),
Divider(),
SizedBox(height: 5.h,),
customExpansionTile(
title: faqTitle3.tr, description: faqDescription3.tr),
SizedBox(height: 5.h,),
Divider(),
SizedBox(height: 5.h,),
customExpansionTile(
title: faqTitle4.tr, description: faqDescription4.tr),
SizedBox(height: 5.h,),
Divider(),
SizedBox(height: 5.h,),
customExpansionTile(
title: faqTitle5.tr, description: faqDescription5.tr),
],
),
),
),
);
}
ExpansionTile customExpansionTile(
{required String title, required String description}) {
return ExpansionTile(
backgroundColor: AppColors.scaffoldColor,
collapsedTextColor: AppColors.textColor,
iconColor: AppColors.textColor,
textColor: AppColors.textColor,
childrenPadding: EdgeInsets.all(10.h),
title: Text(title),
children: [
Text(description,style: TextStyle(color: Colors.black),)
],
);
}
}
|
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
Cypress.Commands.add('login', () => {
cy.fixture('userData').then(userFixture => {
cy.request({
url: "https://practice.expandtesting.com/notes/api/users/login",
method: "POST",
body: userFixture
})
})
.then( (response) => {
let token = response.body.data.token
Cypress.env('token', token)
expect(response.status).to.eq(200)
})
})
Cypress.Commands.add("delete", (id) => {
const authToken = {
"x-auth-token": Cypress.env('token')
}
cy.request({
url: `https://practice.expandtesting.com/notes/api/notes/${id}`,
method: "Delete",
headers: authToken
})
})
|
export type CloneObj = { [key: string | number | symbol]: CloneVal }
export type CloneArr = Array<CloneVal>
export type CloneVal = CloneObj | CloneArr | string | number | boolean | symbol | null
// Support json data types and symbol
export function deepClone<T extends CloneVal> (val: T): T {
if (typeof val !== 'object' || val === null) return val
if (Array.isArray(val)) {
return val.map(item => deepClone(item)) as T
}
const obj: CloneObj = {}
for (const key of Reflect.ownKeys(val)) {
obj[key] = deepClone(val[key])
}
return obj as T
}
|
import React, { useState, useContext } from "react";
import { signInWithEmailAndPassword } from "firebase/auth";
import AuthContext from "../context/AuthContext";
import "../styles/Auth.css";
import { auth } from "../firebase/firebase";
import { useNavigate } from "react-router-dom";
const LoginForm = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const { setIsLoggedIn } = useContext(AuthContext);
const { setUserToken } = useContext(AuthContext);
const navigate = useNavigate();
const handleEmailChange = (event) => {
setEmail(event.target.value);
};
const handlePasswordChange = (event) => {
setPassword(event.target.value);
};
const handleFormSubmit = async (event) => {
event.preventDefault();
signInWithEmailAndPassword(auth, email, password)
.then(async (userCredential) => {
const userToken = await userCredential.user.getIdToken();
setIsLoggedIn(true);
setUserToken(userToken);
localStorage.setItem("userToken", JSON.stringify(userToken));
navigate("/Admin");
})
.catch(() => {
alert("Email o contraseña incorrectos");
});
};
return (
<form onSubmit={handleFormSubmit} className="logInForm">
<div className="inputsLogIn">
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
value={email}
onChange={handleEmailChange}
className="inputLogIn"
/>
<label htmlFor="password">Password:</label>
<input
type="password"
id="password"
value={password}
onChange={handlePasswordChange}
className="inputLogIn"
/>
</div>
<button type="submit">Log In</button>
</form>
);
};
export default LoginForm;
|
package at.plieschn.tsis;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
public class PreferencesActivity extends PreferenceActivity {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
findPreference("upload_interval").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
try {
Integer.parseInt((String) newValue);
return true;
} catch(NumberFormatException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(PreferencesActivity.this);
builder.setMessage(R.string.upload_interval_not_numeric_title)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return false;
}
}
});
findPreference("max_accuracy").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
try {
Float.parseFloat((String) newValue);
return true;
} catch(NumberFormatException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(PreferencesActivity.this);
builder.setMessage(R.string.max_accuracy_not_numeric_title)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return false;
}
}
});
findPreference("minimum_time_difference").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
try {
Integer.parseInt((String) newValue);
return true;
} catch(NumberFormatException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(PreferencesActivity.this);
builder.setMessage(R.string.minimum_time_difference_not_numeric_title)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return false;
}
}
});
findPreference("minimum_distance_difference").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
try {
Integer.parseInt((String) newValue);
return true;
} catch(NumberFormatException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(PreferencesActivity.this);
builder.setMessage(R.string.minimum_distance_difference_not_numeric_title)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return false;
}
}
});
findPreference("host").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
try {
new URL((String) newValue);
return true;
} catch(MalformedURLException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(PreferencesActivity.this);
builder.setMessage(R.string.host_not_url_title)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return false;
}
}
});
findPreference("username").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(((String) newValue).length() <= 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(PreferencesActivity.this);
builder.setMessage(R.string.username_required_title)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return false;
} else {
return true;
}
}
});
findPreference("password").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(((String) newValue).length() <= 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(PreferencesActivity.this);
builder.setMessage(R.string.password_required_title)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return false;
} else {
return true;
}
}
});
}
}
|
//var - ela fica solta no código, mas é perigoso usar, uma boa prática é declarar antes - não se usa mais
// var altura = 5;
// var comprimento = 7;
// area = altura * comprimento;
// console.log (area);
// var area;
// let - precisa iniciar antes do código
// let forma = "retângulo";
// let altura = 5;
// let comprimento = 7;
// let area;
// if (forma === "retângulo") {
// area = altura * comprimento;
// } else {
// area = (altura * comprimento) / 2;
// }
// console.log (area);
// const - tem que ter um valor para começar, por se tratar de uma constante
const forma = 'triangulo';
const altura = 5;
const comprimento = 7;
let area;
if (forma === 'quadrado'){
area = altura * comprimento;
}else {
area = (altura * comprimento) / 2;
}
console.log (area);
|
// 全局守卫
import router from './index'
import store from '@/store/index'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
const whiteList = ['/login'] // 排除路径
router.beforeEach(async (to, from, next) => {
// 获取令牌判定用户是否登录
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') {
// 已登录重定向到首页
next({ path: '/' })
} else {
// 若用户角色已附加则说明动态路由已经添加
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if (hasRoles) {
next()
} else {
try {
//先请求获取用户角色
const { roles } = await store.dispatch('user/getInfo')
// 根据当前用户角色动态生成路由
const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
// 添加这些路由至路由器
accessRoutes.forEach(route => {
router.addRoute(route)
})
// 继续路由切换,确保addRoutes完成
next({ ...to, replace: true })
} catch (error) {
// 出错需要重置令牌并重新登陆(令牌过期,网络错误等原因)
await store.dispatch('user/resetToken')
Message.error(error || "网络错误")
next(`/login?redirect=${to.path}`)
}
}
}
} else {
// 用户无令牌
if (whiteList.indexOf(to.path) !== -1) {
//白名单路由放过
next()
} else {
// 重定向至登录页
next(`/login?redirect=${to.path}`)
}
}
})
|
package it.polito.wa2.g05.server.authentication.dtos
import jakarta.validation.Valid
import jakarta.validation.constraints.*
data class UserFormDTO<T : UserDetailsDTO>(
@field:NotBlank
val username: String,
@field:Email
@field:NotBlank
val email: String,
@field:NotBlank
@field:Pattern(
regexp = "^(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&.])[A-Za-z\\d@$!%*?&.]{8,}$",
message = "Invalid password format"
)
val password: String,
@field:Valid
val details: T
)
|
var numNameFields = 1;
function addNameField() {
var nameContainer = document.getElementById("name-container");
var nameFieldContainer = document.createElement("div");
nameFieldContainer.className = "presciption_classification"; // Added 'input-group' class to ensure proper alignment
var newInput = document.createElement("input");
newInput.className = "input--style-1";
newInput.type = "text";
newInput.name = "name";
newInput.id = "name-" + numNameFields;
newInput.value = "";
newInput.placeholder = "NAME OF THE DRUG e.g:NAPA";
newInput.required = true;
newInput.oninput = function(event) {
showWordRecommendations(event, numNameFields);
};
var deleteButton = document.createElement("button");
deleteButton.type = "button";
deleteButton.className = "btn btn-danger";
deleteButton.textContent = "Remove";
deleteButton.onclick = function() {
removeNameField(newInput.id);
};
nameFieldContainer.appendChild(newInput);
nameFieldContainer.appendChild(deleteButton);
nameContainer.appendChild(nameFieldContainer);
numNameFields++;
}
// Function to remove the clicked name field
function removeNameField(inputId) {
var nameContainer = document.getElementById("name-container");
var inputToRemove = document.getElementById(inputId);
nameContainer.removeChild(inputToRemove.parentElement); // Remove the parent div containing the input and delete button
}
// Global variable to store timeout references for each name field
var timeouts = {};
var recommendationsHtml = "<select class=' my-custom-input-group form-select' aria-label='Default select example' onchange='selectRecommendation()'>";
recommendationsHtml += '<option value="">USE A PROPER BRAND NAME</option>';
document.getElementById("wordRecommendations").innerHTML = recommendationsHtml;
function showWordRecommendations(event, fieldNum) {
var input = event.target.value.trim();
// Clear previous timeout, if any
clearTimeout(timeouts[fieldNum]);
timeouts[fieldNum] = setTimeout(function() {
// Make an AJAX call to fetch word recommendations based on the input
var xhr = new XMLHttpRequest();
xhr.open('GET', '/get_word_recommendations/?input=' + encodeURIComponent(input), true);
xhr.onload = function() {
if (xhr.status === 200) {
var wordRecommendations = JSON.parse(xhr.responseText);
// Display word recommendations in a list
var recommendationsHtml = "<select class=' my-custom-input-group form-select' aria-label='Default select example' onchange='selectRecommendation()'>";
if (wordRecommendations.length !== 0) {
for (var i = 0; i < wordRecommendations.length; i++) {
var word = wordRecommendations[i];
recommendationsHtml += '<option value="' + word + '">' + word + '</option>';
}
} else {
recommendationsHtml += '<option value="">USE A PROPER BRAND NAME</option>';
}
recommendationsHtml += "</select>";
document.getElementById("wordRecommendations").innerHTML = recommendationsHtml;
}
else {
console.error('Request failed. Status:', xhr.status);
// Display no recommendations for error cases
document.getElementById("wordRecommendations").innerHTML = "";
}
};
xhr.onerror = function() {
console.error('Request failed. Network error');
// Display no recommendations for network errors
document.getElementById("wordRecommendations").innerHTML = "";
};
xhr.send();
}, 300); // Adjust the delay as needed (in milliseconds)
}
// Function to select a word recommendation and populate the input field with it
function selectRecommendation() {
var selectElement = document.querySelector("select");
var selectedOption = selectElement.options[selectElement.selectedIndex].value;
document.getElementById("name-" + (numNameFields - 1)).value = selectedOption;
}
function handleFormSubmit(event) {
event.preventDefault(); // Prevent the form from being submitted traditionally
handleSelectionChange();
}
function handleSelectionChange() {
var nameInputs = document.querySelectorAll("#name-container input");
var drugNames = [];
for (var i = 0; i < nameInputs.length; i++) {
drugNames.push(encodeURIComponent(nameInputs[i].value));
}
// Construct the URL with query parameters
var queryParams = '?name=' + drugNames;
// You can add more parameters if needed like this: '¶m1=value1¶m2=value2'
// Redirect to the target HTML page with the query parameters
window.location.href = '/presciption_classification_beta_results/' + queryParams;
}
// Attach the handleFormSubmission function to the form's submit event
document.getElementById("med_search_form").addEventListener("submit", handleFormSubmit);
|
import {useState, useEffect} from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error,setError] = useState(null);
useEffect(() =>{
const abortCont = new AbortController();
setTimeout(() => { // setTimeout only implemented to simulate real world waiting
fetch(url,{signal:abortCont.signal})
.then(res => {
if(!res.ok){
throw Error('could not fetch the data')
}
return res.json()
})
.then(data => {
setData(data);
setIsPending(false);
setError(null);
})
.catch(err => {
if(err.name === 'AbortError'){
console.log('fetch was aborted');
}else{
setError(err.message);
setIsPending(false);
}
})
}, 1000)
return () => abortCont.abort();
},[url]);
return {data, isPending, error}
}
export default useFetch;
|
# Style Guidelines
Please ensure that your code adheres to the following style guidelines:
## Ruby Style
- Follow the conventions defined by RuboCop for Ruby code.
- Make sure there are no RuboCop offenses in your code. You can run `rubocop -A` locally to check for offenses and fix them before submitting your pull request.
## Security
- Check for security vulnerabilities using `bundle audit` and `brakeman`.
- Ensure there are no critical security issues reported by these tools in your changes.
- If any security issues are found, address them before submitting your pull request.
## Testing
- Add tests to cover your changes and make sure that existing tests pass.
- Run the test suite locally to verify that your changes do not introduce new test failures.
## Documentation
- Update documentation as needed to reflect any changes in behavior or functionality.
- Ensure that code comments are clear and helpful, especially in complex or non-obvious sections of the code.
## Code Cleanliness
- Keep your code clean and organized.
- Follow the Single Responsibility Principle (SRP) and keep methods and classes focused on doing one thing well.
- Use meaningful variable and method names.
- Avoid unnecessary duplication.
- Remove commented-out code and debug statements.
## Commit Messages
- Write clear and descriptive commit messages that explain the purpose of each commit.
- Use meaningful commit message prefixes such as "Fix," "Feature," "Refactor," or "Docs."
## Code Review
- Be open to feedback during the code review process.
- Respond promptly to comments and questions from reviewers.
- Address any concerns or suggestions raised by reviewers.
By following these style guidelines, you help maintain code quality, security, and readability in our project.
Thank you for your contributions! :heart: :heart:
|
var siteName = document.getElementById("site-name");
var siteLink = document.getElementById("site-link");
var errorPopup = document.getElementById("error");
var addSiteBtn = document.getElementById("add-book");
var nameStatus = document.getElementById("name-status");
var linkStatus = document.getElementById("link-status");
var errorModal = new bootstrap.Modal("#error");
var siteList;
if (JSON.parse(localStorage.getItem("bookmarks"))) siteList = JSON.parse(localStorage.getItem("bookmarks"));
else siteList = [];
display(siteList);
// apply add site action in submit button click
addSiteBtn.addEventListener("click", function (e) {
e.preventDefault();
if (checkName() && checkLink()) {
addSite();
} else {
showPopup();
}
});
// add new bookmark site to the siteList
function addSite() {
var site = {
name: siteName.value,
link: siteLink.value,
};
siteList.push(site);
localStorage.setItem("bookmarks", JSON.stringify(siteList));
siteName.value = "";
siteLink.value = "";
nameStatus.innerHTML = "";
linkStatus.innerHTML = "";
siteName.classList.remove("correct-focus");
siteName.classList.remove("wrong-focus");
siteLink.classList.remove("correct-focus");
siteLink.classList.remove("wrong-focus");
display(siteList);
}
// delete an entire bookmarked site row
function deleteSite(index) {
siteList.splice(index, 1);
localStorage.setItem("bookmarks", JSON.stringify(siteList));
display(siteList);
}
// display the bookmared sites in the table
function display(list) {
var bookSites = "";
for (var site of list) {
bookSites += `
<tr>
<td>${list.indexOf(site) + 1}</td>
<td>${site.name}</td>
<td>
<a target="_blank" href="${site.link.toLowerCase()}">
<button type="button" class="btn btn-warning btn-sm px-3 py-1">
<i class="fa-solid fa-eye me-1"></i>
Visit
</button>
</a>
</td>
<td>
<button type="button" class="btn btn-danger btn-sm px-3 py-1" onclick="deleteSite(${list.indexOf(site)})">
<i class="fa-solid fa-trash-can me-1"></i>
Delete
</button>
</td>
</tr>
`;
}
document.querySelector("#site-tbl tbody").innerHTML = bookSites;
}
// check if website name is valid
function checkName() {
var isNameValid = /^[A-Z]\w{2,}/;
if (isNameValid.test(siteName.value)) return true;
else return false;
}
// check if website url is valid
function checkLink() {
var isLinkValid = /^(http(s):\/\/.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/i;
if (isLinkValid.test(siteLink.value)) return true;
else return false;
}
// error popup for incorrect input
function showPopup() {
errorModal.show();
if (!checkName() && !checkLink()) {
document.getElementById("error-title").innerHTML = `Incorrect Bookmark Name & Website URL`;
document.getElementById("error-content").innerHTML = `
<ul class="list-group">
<li class="list-group-item border-0 px-0 py-1 text-body-secondary"><i class="fa-regular fa-circle-xmark me-1"></i>Site name must contain <strong>at least 3 characters</strong> and should begin with a <strong>Capital</strong>
letter!</li>
<li class="list-group-item border-0 px-0 py-1 text-body-secondary"><i class="fa-regular fa-circle-xmark me-1"></i>Site URL must be a <strong>valid</strong> one!</li>
</ul>
`;
} else if (!checkName()) {
document.getElementById("error-title").innerHTML = `Incorrect Bookmark Name`;
document.getElementById(
"error-content"
).innerHTML = `<i class="fa-regular fa-circle-xmark me-1"></i>Site name must contain <strong>at least 3 characters</strong> and should begin with a <strong>Capital</strong>
letter!`;
} else if (!checkLink()) {
document.getElementById("error-title").innerHTML = `Incorrect Website URL`;
document.getElementById(
"error-content"
).innerHTML = `<i class="fa-regular fa-circle-xmark me-1"></i>Site URL must be a <strong>valid</strong> one!`;
}
}
// check if website name is being entered correctly
siteName.addEventListener("input", function (e) {
if (!e.target.value) {
e.target.classList.remove("correct-focus");
e.target.classList.remove("wrong-focus");
nameStatus.innerHTML = "";
} else if (e.target.value && checkName()) {
e.target.classList.add("correct-focus");
e.target.classList.remove("wrong-focus");
nameStatus.innerHTML = `<i class="fa-solid fa-circle-check text-correct"></i>`;
} else {
e.target.classList.add("wrong-focus");
e.target.classList.remove("correct-focus");
nameStatus.innerHTML = `<i class="fa-solid fa-circle-exclamation text-wrong"></i>`;
}
});
// check if website link is being entered correctly
siteLink.addEventListener("input", function (e) {
if (!e.target.value) {
e.target.classList.remove("correct-focus");
e.target.classList.remove("wrong-focus");
linkStatus.innerHTML = "";
} else if (e.target.value && checkLink()) {
e.target.classList.add("correct-focus");
e.target.classList.remove("wrong-focus");
linkStatus.innerHTML = `<i class="fa-solid fa-circle-check text-correct"></i>`;
} else {
e.target.classList.add("wrong-focus");
e.target.classList.remove("correct-focus");
linkStatus.innerHTML = `<i class="fa-solid fa-circle-exclamation text-wrong"></i>`;
}
});
|
//
// ATArrowConstant.swift
// PlotlineTooltips
//
// Created by Agrim Srivastava on 18/08/23.
//
import Foundation
import SwiftUI
struct TooltipShape: InsettableShape {
let axisMode: ATAxisMode
let cornerRadius: CGFloat
let arrowWidth: CGFloat
let arrowHeight: CGFloat
var arrowPosition: CGFloat
var amount: CGFloat = 0
var animatableData: CGFloat {
get { arrowPosition }
set {
arrowPosition = newValue
}
}
func path(in rect: CGRect) -> Path {
switch axisMode {
case .top: return arrowBottom(rect.size)
case .bottom: return arrowTop(rect.size)
case .leading: return arrowTrailing(rect.size)
case .trailing: return arrowLeading(rect.size)
}
}
private func arrowTop(_ size: CGSize) -> Path {
var path = Path()
let x = limitX(size.width)
path.move(to: CGPoint(x: x - arrowWidth , y: 0))
path.addLine(to: CGPoint(x: x , y: -arrowHeight))
path.addLine(to: CGPoint(x: x + arrowWidth , y: 0))
path.addArc(center: CGPoint(x: size.width - cornerRadius + amount, y: cornerRadius + amount),
radius: cornerRadius,
startAngle: Angle(degrees: -90),
endAngle: Angle(degrees: 0),
clockwise: false)
path.addArc(center: CGPoint(x: size.width - cornerRadius + amount, y: size.height - cornerRadius + amount),
radius: cornerRadius,
startAngle: Angle(degrees: 0),
endAngle: Angle(degrees: 90),
clockwise: false)
path.addArc(center: CGPoint(x: cornerRadius + amount, y: size.height - cornerRadius + amount),
radius: cornerRadius, startAngle: Angle(degrees: 90),
endAngle: Angle(degrees: 180),
clockwise: false)
path.addArc(center: CGPoint(x: cornerRadius + amount, y: cornerRadius + amount),
radius: cornerRadius,
startAngle: Angle(degrees: 180),
endAngle: Angle(degrees: 270),
clockwise: false)
path.closeSubpath()
return path
}
private func arrowBottom(_ size: CGSize) -> Path {
var path = Path()
let x = limitX(size.width)
path.move(to: CGPoint(x: cornerRadius , y: 0))
path.addArc(center: CGPoint(x: size.width - cornerRadius + amount, y: cornerRadius + amount),
radius: cornerRadius,
startAngle: Angle(degrees: -90),
endAngle: Angle(degrees: 0),
clockwise: false)
path.addArc(center: CGPoint(x: size.width - cornerRadius + amount, y: size.height - cornerRadius + amount),
radius: cornerRadius,
startAngle: Angle(degrees: 0),
endAngle: Angle(degrees: 90),
clockwise: false)
path.addLine(to: CGPoint(x: x + arrowWidth , y: size.height))
path.addLine(to: CGPoint(x: x, y: size.height + arrowHeight))
path.addLine(to: CGPoint(x: x - arrowWidth , y: size.height))
path.addArc(center: CGPoint(x: cornerRadius + amount, y: size.height - cornerRadius + amount),
radius: cornerRadius, startAngle: Angle(degrees: 90),
endAngle: Angle(degrees: 180),
clockwise: false)
path.addArc(center: CGPoint(x: cornerRadius + amount, y: cornerRadius + amount),
radius: cornerRadius,
startAngle: Angle(degrees: 180),
endAngle: Angle(degrees: 270),
clockwise: false)
path.closeSubpath()
return path
}
private func arrowLeading(_ size: CGSize) -> Path {
var path = Path()
let y = limitY(size.height)
path.move(to: CGPoint(x: cornerRadius , y: 0))
path.addArc(center: CGPoint(x: size.width - cornerRadius + amount, y: cornerRadius + amount),
radius: cornerRadius,
startAngle: Angle(degrees: -90),
endAngle: Angle(degrees: 0),
clockwise: false)
path.addArc(center: CGPoint(x: size.width - cornerRadius + amount, y: size.height - cornerRadius + amount),
radius: cornerRadius,
startAngle: Angle(degrees: 0),
endAngle: Angle(degrees: 90),
clockwise: false)
path.addArc(center: CGPoint(x: cornerRadius + amount, y: size.height - cornerRadius + amount),
radius: cornerRadius, startAngle: Angle(degrees: 90),
endAngle: Angle(degrees: 180),
clockwise: false)
path.addLine(to: CGPoint(x: 0 , y: y + arrowWidth))
path.addLine(to: CGPoint(x: 0 - arrowHeight, y: y))
path.addLine(to: CGPoint(x: 0 , y: y - arrowWidth))
path.addArc(center: CGPoint(x: cornerRadius + amount, y: cornerRadius + amount),
radius: cornerRadius,
startAngle: Angle(degrees: 180),
endAngle: Angle(degrees: 270),
clockwise: false)
path.closeSubpath()
return path
}
private func arrowTrailing(_ size: CGSize) -> Path {
var path = Path()
let y = limitY(size.height)
path.move(to: CGPoint(x: cornerRadius , y: 0))
path.addArc(center: CGPoint(x: size.width - cornerRadius + amount, y: cornerRadius + amount),
radius: cornerRadius,
startAngle: Angle(degrees: -90),
endAngle: Angle(degrees: 0),
clockwise: false)
path.addLine(to: CGPoint(x: size.width , y: y - arrowWidth))
path.addLine(to: CGPoint(x: size.width + arrowHeight, y: y))
path.addLine(to: CGPoint(x: size.width , y: y + arrowWidth))
path.addArc(center: CGPoint(x: size.width - cornerRadius + amount, y: size.height - cornerRadius + amount),
radius: cornerRadius,
startAngle: Angle(degrees: 0),
endAngle: Angle(degrees: 90),
clockwise: false)
path.addArc(center: CGPoint(x: cornerRadius + amount, y: size.height - cornerRadius + amount),
radius: cornerRadius, startAngle: Angle(degrees: 90),
endAngle: Angle(degrees: 180),
clockwise: false)
path.addArc(center: CGPoint(x: cornerRadius + amount, y: cornerRadius + amount),
radius: cornerRadius,
startAngle: Angle(degrees: 180),
endAngle: Angle(degrees: 270),
clockwise: false)
path.closeSubpath()
return path
}
func inset(by amount: CGFloat) -> some InsettableShape {
var shape = self
shape.amount += amount
return shape
}
private func limitX(_ w: CGFloat) -> CGFloat {
var x = arrowPosition
let cornerArrowWidth = cornerRadius + arrowWidth
if arrowPosition >= (w - cornerArrowWidth) {
x = w - cornerArrowWidth
}else if arrowPosition <= cornerArrowWidth {
x = cornerArrowWidth
}
return x
}
private func limitY(_ h: CGFloat) -> CGFloat {
var y = arrowPosition
let cornerArrowWidth = cornerRadius + arrowWidth
if arrowPosition >= (h - cornerArrowWidth) {
y = h - cornerArrowWidth
}else if arrowPosition <= cornerArrowWidth {
y = cornerArrowWidth
}
return y
}
}
struct TooltipShape_Previews: PreviewProvider {
static var previews: some View {
VStack {
TooltipShape(axisMode: .leading, cornerRadius: 30, arrowWidth: 20, arrowHeight: 20, arrowPosition: 120)
.stroke()
.font(.callout)
.padding()
.frame(width: 200)
Spacer()
TooltipShape(axisMode: .trailing, cornerRadius: 60, arrowWidth: 20, arrowHeight: 20, arrowPosition: 0)
.stroke()
.fill(Color.blue)
.frame(width: 260, height: 260)
}
}
}
|
// RADIO.CPP
// Radio class implementation
#include "radio.h"
// Constructor for radio object
Radio::Radio()
:Power(OFF), Volume(1,10), Frequency(1,103)
{
}
// Method to update the status of the radio object
void Radio::Update()
{
if(Power.CurrentState() == OFF)
{ // If power is off, make sure each component is off
MyAmp.Off();
MyTuner.Off();
MyDisplay.Off();
}
else
{ // If power is on, make sure each component is on
MyAmp.On();
MyTuner.On();
MyDisplay.On();
// Set volume to the current volume knob position
MyAmp.Volume(Volume.CurrentPosition());
// Set frequency to the current tuner knob position
MyTuner.Frequency( (Frequency.CurrentPosition() * 0.2) + 87.3 );
// Set display message to reflect current frequency
MyDisplay.FrequencyToDisplay( MyTuner.CurrentFrequency());
}
}
// Method to display the current status of the radio
void Radio::DisplayStatus(ostream & out)
{
Update(); // Execute Update method to ensure that all
// components are operating at current knob settings.
if(Power.CurrentState() == OFF)
{ // If power is off,
out << "Radio:" << endl // display message indicating
<< "------" << endl // that the power is off.
<< "Power: OFF" << endl
<< endl;
}
else
{
out.setf(ios::fixed); // If power is on,
out << "Radio:" << endl // display current settings.
<< "------" << endl
<< "Power: ON" << endl
<< "Volume: " << MyAmp.CurrentVolume() << endl
<< "Frequency: " << setprecision(1) << MyTuner.CurrentFrequency()
<< endl << "Display: [ ";
out.unsetf(ios::fixed);
MyDisplay.DisplayMessage(cout); // Activate the radio's display
out << " ]" << endl << endl;
}
}
|
package org.funql.ri.exec.clause;
/*
Copyright (C) 2011, Hans Marggraff and other copyright owners as documented in the project's IP log.
This program and the accompanying materials are made available under the terms of the Eclipse Distribution License
v1.0 which accompanies this distribution, is reproduced below, and is available at http://www.eclipse
.org/org/documents/edl-v10.php
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
- Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.funql.ri.data.FqlDataException;
import org.funql.ri.data.FqlIterator;
import org.funql.ri.data.NamedValues;
import org.funql.ri.exec.FqlStatement;
import org.funql.ri.exec.RunEnv;
import org.funql.ri.exec.node.FqlNodeInterface;
import org.funql.ri.util.NamedValuesImpl;
import java.util.ArrayList;
import java.util.HashSet;
/**
* Implements the select clause
* User: hmf
* Date: 07.03.11
*/
public class SelectClause implements FqlStatement {
private final ArrayList<FqlNodeInterface> fieldList;
String[] fieldNames;
public SelectClause(ArrayList<FqlNodeInterface> fieldList) {
this.fieldList = fieldList;
fieldNames = new String[fieldList.size()];
HashSet<String> usednames = new HashSet<>();
for (int i = 0; i < fieldList.size(); i++) {
String fieldName = buildFieldName(fieldList.get(i), usednames);
fieldNames[i] = fieldName;
}
}
private String buildFieldName(FqlNodeInterface node, HashSet<String> usednames) {
final String result;
int i = 1;
String ret;
StringBuffer fieldNameBuffer = new StringBuffer();
node.buildMemberName(fieldNameBuffer);
if (fieldNameBuffer.length() > 0) {
result = fieldNameBuffer.toString();
ret = result;
} else if (fieldList.size() == 1)
return "f";
else {
result = "f";
ret = result + i;
}
while (usednames.contains(ret)) {
ret = result + i;
i++;
}
usednames.add(ret);
return ret;
}
public FqlIterator execute(final RunEnv env, final FqlIterator precedent) throws FqlDataException {
return new FqlIterator() {
@Override
public NamedValues next() {
final Object parent = precedent.next();
if (parent == FqlIterator.sentinel)
return FqlIterator.sentinel;
Object[] fields = new Object[fieldList.size()];
try {
env.pushObject(parent);
for (int i = 0; i < fieldList.size(); i++) {
FqlNodeInterface node = fieldList.get(i);
Object value = node.getValue(env, parent);
fields[i] = value;
}
} finally {
env.popObject();
}
return new NamedValuesImpl(fieldNames, fields);
}
};
}
public String[] getFieldNames() {
return fieldNames;
}
}
|
import React from "react";
import styled from "styled-components";
import { useDispatch } from "react-redux";
import ui from "../reducers/ui";
const Category = ({ categoryName }) => {
const dispatch = useDispatch();
const sortOnClick = () => {
categoryName === "all items"
? dispatch(ui.actions.setFilter(""))
: dispatch(ui.actions.setFilter(categoryName));
dispatch(ui.actions.closeCategories());
};
return (
<CategoryLink>
<Button type='button' aria-label={categoryName} onClick={sortOnClick}>
<Span>⋆</Span>
{categoryName}
</Button>
</CategoryLink>
);
};
export default Category;
const CategoryLink = styled.li`
list-style-type: none;
margin: 0.714em;
font-size: 1rem;
`;
const Button = styled.button`
background: transparent;
color: var(--quaternary-font-color);
text-transform: uppercase;
&:hover {
font-weight: bold;
}
`;
const Span = styled.span`
margin-right: 0.714em;
`;
|
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
class NoteEdit extends StatefulWidget {
final int index;
const NoteEdit({super.key, required this.index});
@override
State<NoteEdit> createState() => _NoteEditState();
}
class _NoteEditState extends State<NoteEdit> {
late TextEditingController textEditingController;
@override
void initState() {
super.initState();
textEditingController = TextEditingController(
text: Hive.box('notesBox').getAt(widget.index).toString());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Note Edit'),
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 25),
child: TextField(
maxLines: null,
controller: textEditingController,
decoration: const InputDecoration(hintText: 'Edit Note'),
),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.edit_note),
onPressed: () {
if (textEditingController.text.isNotEmpty) {
Hive.box('notesBox')
.putAt(widget.index, textEditingController.text);
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.green,
content: Text('Note updated successfully')));
Navigator.pop(context);
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.red,
content: Text('Please enter a note')));
}
},
),
);
}
}
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0 <0.9.0;
import "./helpers.sol";
contract Invoicing {
struct Invoice {
address sender;
string description;
string category;
uint256 amount;
string tokenId;
// bool status;
}
mapping(string => Invoice) invoiceMapping;
// mapping(string=>bool) invoiceStatus;
Invoice[] allInvoices;
Invoice[] allUnpaidInvoices;
function addInvoice(Invoice memory newInvoice, string memory invoiceId)
public
returns (bool)
{
if (invoiceMapping[invoiceId].sender != newInvoice.sender) {
// Doesnt exists, add
invoiceMapping[invoiceId] = newInvoice;
// invoiceStatus[invoiceId]=false;
allInvoices.push(newInvoice);
return true;
}
return false;
}
function getInvoice(string memory invoiceId)
public
view
returns (Invoice memory)
{
return invoiceMapping[invoiceId];
}
// function setInvoicePaid(string memory invoiceId) public returns (bool)
// {
// if(invoiceMapping[invoiceId].status==false)
// {invoiceMapping[invoiceId].status=true;
// return true;}
// return false;
// }
function getAllInvoices() public view returns (Invoice[] memory) {
return allInvoices;
}
function payInvoice(string memory invoiceId) public returns (bool) {
Invoice memory tobePaidInvoice = invoiceMapping[invoiceId];
int256 status=tokenTransfer(tobePaidInvoice.tokenId, this.address, tobePaidInvoice.sender, tobePaidInvoice.amount);
if(status==HederaResponseCodes.SUCCESS)
{return true;}
}
}
|
import OurTable, { ButtonColumn } from "main/components/OurTable"
import { useBackendMutation } from "main/utils/useBackend";
export default function UsersTable({ users}) {
function cellToAxiosParamsToggleAdmin(cell) {
return {
url: "/api/admin/users/toggleAdmin",
method: "POST",
params: {
id: cell.row.values.id
}
}
}
// toggleDriver return
function cellToAxiosParamsToggleDriver(cell){
return {
url: "/api/admin/users/toggleDriver",
method: "POST",
params: {
id: cell.row.values.id
}
}
}
// Stryker disable all : hard to test for query caching
const toggleAdminMutation = useBackendMutation(
cellToAxiosParamsToggleAdmin,
{},
["/api/admin/users"]
);
const toggleDriverMutation = useBackendMutation(
cellToAxiosParamsToggleDriver,
{},
["/api/admin/users"]
);
// Stryker restore all
const toggleAdminCallback = async (cell) => { toggleAdminMutation.mutate(cell); }
const toggleDriverCallback = async (cell) => { toggleDriverMutation.mutate(cell); }
const columns = [
{
Header: 'id',
accessor: 'id',
},
{
Header: 'First Name',
accessor: 'givenName',
},
{
Header: 'Last Name',
accessor: 'familyName',
},
{
Header: 'Email',
accessor: 'email',
},
{
Header: 'Admin',
id: 'admin',
accessor: (row, _rowIndex) => String(row.admin) // hack needed for boolean values to show up
},
{
Header: 'Driver',
id: 'driver',
accessor: (row, _rowIndex) => String(row.driver)
}
];
const buttonColumn = [
// shows all the text columns, and then the button columns
...columns,
ButtonColumn("toggle-admin", "primary", toggleAdminCallback, "UsersTable"),
ButtonColumn("toggle-driver", "primary", toggleDriverCallback, "UsersTable"),
]
return <OurTable
data={users}
columns={buttonColumn}
testid={"UsersTable"}
/>;
};
|
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthorizationService } from '../services';
@Injectable({
providedIn: 'root'
})
export class DisableLoginGuard implements CanActivate {
private userIsLogin: boolean = false;
constructor(
private router: Router,
private authService: AuthorizationService
) {
this.authService.isAuthorized()
.subscribe((isPermitted: any) => {
if (!!isPermitted) {
this.userIsLogin = false;
this.router.navigate(['']);
return;
}
this.userIsLogin = true;
this.router.navigate(['login']);
});
}
canActivate(): Observable<boolean> | boolean {
return this.userIsLogin;
}
}
|
package multithreading.section_3.thread_termination.long_computation;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new LongComputation(new BigInteger("200000"), new BigInteger("10000000")));
thread.setDaemon(true);
thread.start();
Thread.sleep(100);
thread.interrupt();
}
private static class LongComputation implements Runnable{
private BigInteger power;
private BigInteger base;
public LongComputation(BigInteger base,BigInteger power) {
this.base = base;
this.power = power;
}
private BigInteger pow(BigInteger base, BigInteger power){
BigInteger result = BigInteger.ONE;
for(BigInteger i = BigInteger.ZERO ; i.compareTo(power)!=0; i=i.add(BigInteger.ONE)){
// if(Thread.currentThread().isInterrupted()){
// System.out.println("Prematurely interupted computatuin");
// return BigInteger.ZERO;
// }
result=result.multiply(base);
}
return result;
}
@Override
public void run() {
System.out.println(base+"^"+power+" = "+pow(base,power));
}
}
}
|
import {User} from "../models/user.js"
import {Chat} from "../models/chat.js"
import { sendToken , cookieOptions } from "../utils/token.js";
import { compare } from "bcrypt";
import { ErrorHandler } from "../middleware/errorHandler.js";
import { Request } from "../models/request.js";
import {emitEvent} from "../utils/features.js"
import {NEW_REQUEST , REFETCH_CHATS} from "../constants/events.js"
import { uploadFilesToCloudinary } from "../utils/cloudinary.js";
// const cookieOptions = {
// maxAge: 30 * 24 * 60 * 60 * 1000,
// sameSite: "none",
// httpOnly: true,
// secure: true,
// };
//create new user, save to database, create and save cookie
const register = async (req,res,next) => {
try{
const {name, username, password, bio} = req.body;
const file = req.file;
console.log("file",file);
if (!file) return next(new ErrorHandler("Please Upload Avatar"));
const result = await uploadFilesToCloudinary([file]);
const avatar = {
public_id: result[0].public_id,
url: result[0].url,
}
const user = await User.create({
name,
username,
password,
bio,
avatar
});
// const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET);
// console.log(token);
// return res.status(201).cookie("wechat_token", token, cookieOptions).json({
// success: true,
// user,
// message: "User created successfully",
// });
sendToken(res, user, 201, "User created successfully");
}catch(err){
next(err);
}
//res.status(201).json({message: "User created successfully"});
};
const login = async (req,res,next) => {
try{
const {username , password} = req.body;
const user = await User.findOne({username}).select("+password");
//if(!user) return res.status(400).json({message: "Invalid userId or password"});
if(!user) return next(new ErrorHandler("Invalid Username or Password",404));
const checkPass = await compare(password, user.password);
//if(!checkPass) {return res.status(400).json({message: "Invalid userId or password"});}
if(!checkPass) return next(new ErrorHandler("Invalid Username or Password",404));
console.log("It is reaching till here");
// const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET);
// console.log(token);
// console,log(process.env.JWT_SECRET);
// return res.status(201).cookie("wechat_token", token, cookieOptions).json({
// success: true,
// user,
// message: `Welcome Back, ${user.name}`
// });
sendToken(res, user, 200, `Welcome Back, ${user.name}`);
}catch(err){
next(err);
}
};
const getMyProfile = async(req,res,next)=>{
try{
const user = await User.findById(req.userId);
if(!user) return next(new ErrorHandler("User not found", 404));
res.status(200).json({
success: true,
user,
//message: "u son of a bitch im in"
});
}catch(err){
next(err);
}
};
const getFriendProfile = async(req,res,next)=>{
try{
const user = await User.findById(req.params.id);
if(!user) return next(new ErrorHandler("User not found", 404));
res.status(200).json({
success: true,
user,
//message: "u son of a bitch im in"
});
}catch(err){
next(err);
}
};
const logout = async(req,res,next)=>{
try{
return res.status(200)
.cookie("wechat_token", "", { ...cookieOptions, maxAge: 0 })
.json({
success: true,
message: "Logged out successfully",
});
}catch(err){
next(err);
}
};
const searchUser = async(req,res,next) => {
try{
//console.log(req);
const {name = ""} = req.query;
const user = await User.findById(req.userId).populate('friends');
const allUsers = await User.find({
_id: { $ne: req.userId },
name: { $regex: name, $options: "i" },
});
//console.log(allUsers);
const friendsIds = user.friends.map(friend => friend._id.toString());
const usersNotInFriends = allUsers.filter(user => !friendsIds.includes(user._id.toString()));
const onlyReqDetails = usersNotInFriends.map(({ _id, name, avatar })=>({
_id,
name,
avatar: avatar.url,
}));
return res.status(200).json({
success: true,
onlyReqDetails,
message: name,
})
}catch(err){
next(err);
}
};
const sendRequest = async(req,res,next) => {
try{
const currUser=req.userId;
const {userId}=req.body;
if(userId === currUser) return next(new ErrorHandler("You cannot be friends with yourself. -WeChat 2024", 400));
const request = await Request.findOne({
$or:[
{ sender: currUser, receiver: userId },
{ sender: userId, receiver: currUser },
]
});
if (request) return next(new ErrorHandler("Request already sent. Check inbox.", 400));
await Request.create({
sender: currUser,
receiver: userId,
});
emitEvent(req, NEW_REQUEST, [userId]);
return res.status(200).json({
success: true,
message: "Friend Request Sent",
});
}catch(err){
next(err);
}
};
const acceptRequest = async(req,res,next) => {
try{
//const currUser=req.userId;
const {requestId, accept}=req.body;
const request = await Request.findById(requestId)
.populate("sender")
.populate("receiver");
if (!request) return next(new ErrorHandler("Send a request first!", 400));
if (request.receiver._id.toString() !== req.userId.toString()) return next(new ErrorHandler("You cannot accept this request", 401));
if(!accept){
await request.deleteOne();
return res.status(200).json({
success: true,
message: "Friend Request Rejected",
});
};
//console.log(request);
const senderId = request.sender._id;
const receiverId = request.receiver._id;
const members = [senderId, receiverId];
await Promise.all([
User.updateOne(
{_id: senderId},
{$push: {friends: receiverId}}
),
User.updateOne(
{_id: receiverId},
{$push: {friends: senderId}}
),
Chat.create({
members,
name: `${request.sender.name}-${request.receiver.name}`,
}),
request.deleteOne(),
]);
//update friends of both users
emitEvent(req, REFETCH_CHATS, members);
return res.status(200).json({
success: true,
message: "Friend Request Accepted",
senderId
});
}catch(err){
next(err);
}
};
const getMyNotifs = async(req,res,next)=>{
try{
const requests = await Request
.find({receiver: req.userId })
.populate("sender", "name avatar");
//console.log(requests);
const allRequests = requests.map(({_id, sender})=>({
_id,
sender: {
_id: sender._id,
name: sender.name,
avatar: sender.avatar.url
},
}));
return res.status(200).json({
success: true,
allRequests,
});
}catch(err){
next(err);
}
};
const getMyFriends = async(req,res,next)=>{
try{
const userId = req.userId;
const chatId = req.query.chatId;
const {friends} = await User.findById(userId).populate("friends");
//console.log(friends);
const friendsDto = friends.map(({_id,name,avatar})=>({
_id,
name,
avatar: avatar.url
}));
if(chatId){
const chat = await Chat.findById(chatId);
const friendsNotYetAdded = friendsDto.filter(
(friend)=>!chat.members.includes(friend._id)
);
return res.status(200).json({
success: true,
friends: friendsNotYetAdded,
});
}else{
return res.status(200).json({
success: true,
friends: friendsDto,
});
}
}catch(err){
next(err);
}
};
export {login, register, getMyProfile, logout , searchUser, sendRequest, acceptRequest, getMyNotifs, getMyFriends, getFriendProfile};
|
import { useMutation } from 'react-query';
import axios from 'axios';
const singUpUser = async (userData) => {
const response = await axios.post('https://jumi-api.youchu.io/v1/signup', userData);
return response.data;
};
export function useSignupMutation(onSuccess, onError){
return useMutation(singUpUser, {
onSuccess,
onError
});
}
const loginUser = async (userData) => {
const response = await axios.post('https://jumi-api.youchu.io/v1/login', userData);
return response.data;
};
export function useLoginMutation(onSuccess, onError){
return useMutation(loginUser, {
onSuccess,
onError
});
}
const uploadImage = async (formData) => {
const token = localStorage.getItem('id_token');
const response = await axios.post(
'https://jumi-api.youchu.io/v1/image-upload',
formData,
{
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`,
'accept': 'application/json',
},
}
);
return response.data;
};
export function useImageUploadMutation(onSuccess, onError){
return useMutation(uploadImage, {
onSuccess,
onError
});
}
const businessCreate = async (businessData) => {
const token = localStorage.getItem('id_token');
const headers = {
'Authorization': `Bearer ${token}`,
'accept': 'application/json',
};
const response = await axios.post('https://jumi-api.youchu.io/v1/business', businessData, { headers });
return response.data;
};
export function useBusinessCreateMutation(onSuccess, onError){
return useMutation(businessCreate, {
onSuccess,
onError
});
}
export const fetchBusinessList = async () => {
const token = localStorage.getItem('id_token')
const headers = {
'Authorization' : `Bearer ${token}`
};
const response = await axios.get(`https://jumi-api.youchu.io/v1/business`, { headers });
return response.data;
}
export const fetchUserInfo = async () => {
const token = localStorage.getItem('id_token');
const headers = {
'Authorization': `Bearer ${token}`,
};
const response = await axios.get('https://jumi-api.youchu.io/v1/me', { headers });
return response.data;
};
//회사 정보 가져오기
export const fetchBusinessInfo = async () => {
const token = localStorage.getItem('id_token')
const company_id = localStorage.getItem('company_id')
const headers = {
'Authorization' : `Bearer ${token}`
};
if (!token || !company_id) {
console.log('Token 또는 company_id가 없습니다.');
return null; // 또는 적절한 에러 처리
}
const response = await axios.get(`https://jumi-api.youchu.io/v1/business/${company_id}`, { headers });
return response.data;
}
export const fetchBusinessItemsInfo = async () => {
const token = localStorage.getItem('id_token')
const company_id = localStorage.getItem('company_id')
const headers = {
'Authorization' : `Bearer ${token}`
};
const response = await axios.get(`https://jumi-api.youchu.io/v1/business/${company_id}/items`, { headers });
return response.data;
}
// 매장 업데이트
const businessUpdate = async (businessData) => {
const token = localStorage.getItem('id_token');
const company_id = localStorage.getItem('company_id')
const headers = {
'Authorization': `Bearer ${token}`,
'accept': 'application/json',
};
const response = await axios.put(`https://jumi-api.youchu.io/v1/business/${company_id}`, businessData, { headers });
return response.data;
};
export function useBusinessUpdateMutation(onSuccess, onError){
return useMutation(businessUpdate, {
onSuccess,
onError
});
}
const businessItemsUpdate = async (businessItemsData) => {
const token = localStorage.getItem('id_token');
const company_id = localStorage.getItem('company_id')
const headers = {
'Authorization': `Bearer ${token}`,
'accept': 'application/json',
};
const response = await axios.post(`https://jumi-api.youchu.io/v1/business/${company_id}/items`, businessItemsData, { headers });
return response.data;
};
export function useBusinessItemsUpdateMutation(onSuccess, onError){
return useMutation(businessItemsUpdate, {
onSuccess,
onError
});
}
// gpt 사용해보기
const GPTChat = async (prompt) => {
const response = await axios.post('https://jumi-gpt.youchu.io/prompt', prompt);
return response.data;
};
export function useGPTChatMutation(onSuccess, onError){
return useMutation(GPTChat, {
onSuccess,
onError
});
}
export const fetchBusinessPromptInfo = async () => {
const token = localStorage.getItem('id_token')
const company_id = localStorage.getItem('company_id')
const headers = {
'Authorization' : `Bearer ${token}`
};
const response = await axios.get(`https://jumi-api.youchu.io/v1/business/${company_id}/prompt`, { headers });
return response.data;
}
const promptCreate = async (promptData) => {
const token = localStorage.getItem('id_token');
const company_id = localStorage.getItem('company_id')
const headers = {
'Authorization': `Bearer ${token}`
};
const response = await axios.post(`https://jumi-api.youchu.io/v1/business/${company_id}/prompt`, promptData, { headers });
return response.data;
};
export function usePromptCreateMutation(onSuccess, onError){
return useMutation(promptCreate, {
onSuccess,
onError
});
}
const promptUpdate = async (props) => {
const token = localStorage.getItem('id_token');
const company_id = localStorage.getItem('company_id')
const headers = {
'Authorization': `Bearer ${token}`
};
const response = await axios.put(`https://jumi-api.youchu.io/v1/business/${company_id}/prompt/${props.id}`, {question : props.question, answer: props.answer, items:props.items}, { headers });
return response.data;
};
export function usePromptUpdateMutation(onSuccess, onError){
return useMutation(promptUpdate, {
onSuccess,
onError
});
}
|
package study.querydsl;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Commit;
import org.springframework.transaction.annotation.Transactional;
import study.querydsl.entity.Member;
import study.querydsl.entity.Team;
@SpringBootTest
@Transactional
public class MemberTest {
@PersistenceContext
EntityManager em;
@Test
@DisplayName("멤버와 팀은 성공적으로 생성되어야 한다.")
public void 멤버와_팀은_성공적으로_생성되어야_한다() throws Exception {
Team teamA = new Team("teamA");
Team teamB = new Team("teamB");
em.persist(teamA);
em.persist(teamB);
Member member1 = new Member("member1", 10, teamA);
Member member2 = new Member("member2", 20, teamA);
Member member3 = new Member("member3", 30, teamB);
Member member4 = new Member("member4", 40, teamB);
em.persist(member1);
em.persist(member2);
em.persist(member3);
em.persist(member4);
em.flush();
em.clear();
List<Member> members = em.createQuery("select m from Member m", Member.class) // 순수 JPA로 확인!
.getResultList();
for (Member member : members) {
System.out.println("member = " + member);
System.out.println("member.getTeam() = " + member.getTeam());
}
}
}
|
import React, { useState, useEffect } from "react";
import { UilAngleDown, UilMinusSquare } from "@iconscout/react-unicons";
function Navgroup({
text = "",
submenuItems = [],
icon,
selected,
setSelected,
open,
setOpen,
}) {
const Icon = icon ? icon : <UilMinusSquare />;
const [expand, setExpand] = useState(false);
useEffect(() => {
if (!open) {
setExpand(false);
}
}, [open]);
return (
<>
<div
className="relative mt-4 cursor-pointer items-center p-2 text-gray-400 transition-colors duration-200 hover:text-white"
onClick={() => {
setOpen(true);
setExpand(!expand);
}}
>
<div>
{open ? (
<span className="text-md mx-4 cursor-pointer">{text}</span>
) : (
<span className="text-md cursor-pointer">{Icon}</span>
)}
<UilAngleDown
className={`absolute right-3 top-3 duration-500 ${
expand ? "rotate-180" : ""
}`}
/>
</div>
</div>
<div>
{submenuItems.map((item, index) => (
<div
className={`relative flex cursor-pointer items-center rounded-l-lg text-gray-400 transition-all duration-300 ${
selected == item.id ? "bg-white text-black" : "hover:text-white"
}
${expand && open ? "h-fit p-2 opacity-100" : "h-0 p-0 opacity-0"}
`}
key={index}
onClick={() => {
setSelected(item.id);
}}
>
<span
className={`text-md mx-4 ${
expand ? "h-fit opacity-100" : "h-0 opacity-0"
}`}
>
{item.title}
</span>
</div>
))}
</div>
</>
);
}
export default Navgroup;
// ${
// selected
// ? "bg-gray-100 text-gray-800 dark:bg-gray-600 dark:text-gray-100"
// : ""
// }
|
<!DOCTYPE html>
<html>
<head>
<title>Dirr CCID Analyze</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto&display=swap">
</head>
<body>
<h1>Consulta de CCID</h1>
<input type="text" id="ccid" placeholder="Insira o CCID aqui">
<button onclick="getOperator()">Obter Operadora</button>
<p id="result"></p>
<script>
// Função para obter a operadora quando a página é carregada
window.onload = function() {
var ccid = window.location.hash.substring(1); // Remover o '#'
if (ccid) {
document.getElementById('ccid').value = ccid;
getOperator();
}
};
</script>
<script>
// Carregar o JSON
var data = {
"Brazil": "BR",
"operators": [
{
"MCC": "724",
"MNC": "00",
"Brand": "Nextel",
"Operator": "NII Holdings, Inc.",
"Status": "Not Operational",
"Bands (MHz)": "iDEN 850",
"References and notes": "Defunct since March 2018[11]"
},
{
"MCC": "724",
"MNC": "01",
"Brand": "",
"Operator": "SISTEER DO BRASIL TELECOMUNICAÇÔES",
"Status": "Not Operational",
"Bands (MHz)": "MVNO",
"References and notes": "Through Vivo S.A. network[6]"
},
{
"MCC": "724",
"MNC": "02",
"Brand": "TIM",
"Operator": "Telecom Italia Mobile",
"Status": "Operational",
"Bands (MHz)": "GSM 900 / GSM 1800 / UMTS 850 / UMTS 900 / UMTS 2100 / LTE 700 / LTE 1800 / LTE 2100 / LTE 2600 / 5G 700 / 5G 1800 / 5G 2300 / 5G 2600 / 5G 3500",
"References and notes": "[5][3]"
},
{
"MCC": "724",
"MNC": "03",
"Brand": "TIM",
"Operator": "Telecom Italia Mobile",
"Status": "Operational",
"Bands (MHz)": "GSM 900 / GSM 1800 / UMTS 850 / UMTS 900 / UMTS 2100 / LTE 700 / LTE 1800 / LTE 2100 / LTE 2600 / 5G 700 / 5G 1800 / 5G 2300 / 5G 2600 / 5G 3500",
"References and notes": "[5][3]"
},
{
"MCC": "724",
"MNC": "04",
"Brand": "TIM",
"Operator": "Telecom Italia Mobile",
"Status": "Operational",
"Bands (MHz)": "GSM 900 / GSM 1800 / UMTS 850 / UMTS 900 / UMTS 2100 / LTE 700 / LTE 1800 / LTE 2100 / LTE 2600 / 5G 700 / 5G 1800 / 5G 2300 / 5G 2600 / 5G 3500",
"References and notes": "[5][3]"
},
{
"MCC": "724",
"MNC": "05",
"Brand": "Claro",
"Operator": "Claro",
"Status": "Operational",
"Bands (MHz)": "GSM 900 / GSM 1800 / UMTS 850 / UMTS 2100 / LTE 700 / LTE 1800 / LTE 2600 / 5G 2300 / 5G 2600 / 5G 3500",
"References and notes": "[5]"
},
{
"MCC": "724",
"MNC": "06",
"Brand": "Vivo",
"Operator": "Telefônica Brasil S.A.",
"Status": "Operational",
"Bands (MHz)": "GSM 850 / GSM 1800 / UMTS 850 / UMTS 2100 / LTE 700 / LTE 1800 / LTE 2600 / 5G 700 / 5G 1800 / 5G 2300 / 5G 2600 / 5G 3500",
"References and notes": "[12]"
},
{
"MCC": "724",
"MNC": "10",
"Brand": "Vivo",
"Operator": "Telefônica Brasil S.A.",
"Status": "Operational",
"Bands (MHz)": "GSM 850 / GSM 1800 / UMTS 850 / UMTS 2100 / LTE 700 / LTE 1800 / LTE 2600 / 5G 700 / 5G 1800 / 5G 2300 / 5G 2600 / 5G 3500",
"References and notes": "[12]"
},
{
"MCC": "724",
"MNC": "11",
"Brand": "Vivo",
"Operator": "Telefônica Brasil S.A.",
"Status": "Operational",
"Bands (MHz)": "GSM 850 / GSM 1800 / UMTS 850 / UMTS 2100 / LTE 700 / LTE 1800 / LTE 2600 / 5G 700 / 5G 1800 / 5G 2300 / 5G 2600 / 5G 3500",
"References and notes": "[12]"
},
{
"MCC": "724",
"MNC": "12",
"Brand": "Claro",
"Operator": "Claro",
"Status": "Unknown",
"Bands (MHz)": "Unknown",
"References and notes": "Unknown"
},
{
"MCC": "724",
"MNC": "13",
"Brand": "NLT",
"Operator": "NLT Telecom",
"Status": "Operational",
"Bands (MHz)": "MVNO"
},
{
"MCC": "724",
"MNC": "15",
"Brand": "Sercomtel",
"Operator": "Sercomtel Celular",
"Status": "Operational",
"Bands (MHz)": "GSM 900 / GSM 1800 / UMTS 850",
"References and notes": "[6]"
},
{
"MCC": "724",
"MNC": "16",
"Brand": "Brasil Telecom GSM",
"Operator": "Brasil Telecom GSM",
"Status": "Not operational",
"Bands (MHz)": "GSM 1800 / UMTS 2100",
"References and notes": "Acquired by Oi, MNC used for existing Brasil Telecom SIM Cards only"
},
{
"MCC": "724",
"MNC": "17",
"Brand": "Surf Telecom",
"Operator": "Correios Celular[pt]",
"Status": "Operational",
"Bands (MHz)": "MVNO",
"References and notes": "Through TIM network[13]"
},
{
"MCC": "724",
"MNC": "18",
"Brand": "datora",
"Operator": "Datora (Vodafone)",
"Status": "Operational",
"Bands (MHz)": "MVNO",
"References and notes": "Through TIM network[6]"
},
{
"MCC": "724",
"MNC": "21",
"Brand": "LIGUE",
"Operator": "Ligue Telecom",
"Status": "Operational",
"Bands (MHz)": "LTE 2600",
"References and notes": "[14]"
},
{
"MCC": "724",
"MNC": "23",
"Brand": "Vivo",
"Operator": "Telefônica Brasil S.A.",
"Status": "Operational",
"Bands (MHz)": "GSM 850 / GSM 1800 / UMTS 850 / UMTS 2100 / LTE 1800 / LTE 2600",
"References and notes": "Formerly used by the acquired Telemig Celular[12]"
},
{
"MCC": "724",
"MNC": "24",
"Brand": "",
"Operator": "Amazonia Celular",
"Status": "Unknown",
"Bands (MHz)": "Unknown",
"References and notes": "Acquired by Oi[6]"
},
{
"MCC": "724",
"MNC": "28",
"Brand": "No name",
"Operator": "",
"Status": "Operational",
"Bands (MHz)": "Unknown",
"References and notes": "Used for RanSharing control and roaming between Vivo and Claro[15]"
},
{
"MCC": "724",
"MNC": "29",
"Brand": "Unifique",
"Operator": "Unifique Telecomunicações S/A",
"Status": "Operational",
"Bands (MHz)": "5G 3500"
},
{
"MCC": "724",
"MNC": "30",
"Brand": "Oi",
"Operator": "TNL PCS Oi",
"Status": "Not operational",
"Bands (MHz)": "Unknown",
"References and notes": "Liquidated Apr 2022[16]"
},
{
"MCC": "724",
"MNC": "31",
"Brand": "Oi",
"Operator": "TNL PCS Oi",
"Status": "Not operational",
"Bands (MHz)": "GSM 1800 / UMTS 2100 / LTE 1800 / LTE 2100 / LTE 2600 / 5G 2100",
"References and notes": "Liquidated Apr 2022[16]"
},
{
"MCC": "724",
"MNC": "32",
"Brand": "Algar Telecom",
"Operator": "Algar Telecom S.A.",
"Status": "Operational",
"Bands (MHz)": "GSM 900 / GSM 1800 / UMTS 2100 / LTE 700 / LTE 1800 / LTE 2300 / 5G 2300",
"References and notes": "LTE bands 28 / 3 / 40[3]"
},
{
"MCC": "724",
"MNC": "33",
"Brand": "Algar Telecom",
"Operator": "Algar Telecom S.A.",
"Status": "Operational",
"Bands (MHz)": "GSM 900 / GSM 1800 / UMTS 2100 / LTE 700 / LTE 1800 / LTE 2300 / 5G 2300",
"References and notes": "[3]"
},
{
"MCC": "724",
"MNC": "34",
"Brand": "Algar Telecom",
"Operator": "Algar Telecom S.A.",
"Status": "Operational",
"Bands (MHz)": "GSM 900 / GSM 1800 / UMTS 2100 / LTE 700 / LTE 1800 / LTE 2300 / 5G 2300",
"References and notes": "[3]"
},
{
"MCC": "724",
"MNC": "35",
"Brand": "",
"Operator": "Telcom Telecomunicações",
"Status": "Unknown",
"Bands (MHz)": "Unknown",
"References and notes": "[6]"
},
{
"MCC": "724",
"MNC": "36",
"Brand": "",
"Operator": "Options Telecomunicações",
"Status": "Not Operational",
"Bands (MHz)": "MVNO",
"References and notes": "[6]"
},
{
"MCC": "724",
"MNC": "37",
"Brand": "aeiou",
"Operator": "Unicel",
"Status": "Not operational",
"Bands (MHz)": "Unknown",
"References and notes": "Bankruptcy in 2011[6]"
},
{
"MCC": "724",
"MNC": "38",
"Brand": "Claro",
"Operator": "Claro",
"Status": "Operational",
"Bands (MHz)": "GSM 1900",
"References and notes": "Inherited from the old Vesper's WLL licenses. In use for fixed wireless phones."
},
{
"MCC": "724",
"MNC": "39",
"Brand": "Nextel",
"Operator": "NII Holdings, Inc.",
"Status": "Not Operational",
"Bands (MHz)": "UMTS 2100 / LTE 1800 / LTE 2100",
"References and notes": "Merged with Claro in 2020 [5]"
},
{
"MCC": "724",
"MNC": "40",
"Brand": "Telecall",
"Operator": "Telexperts Telecomunicações S.A",
"Status": "Operational",
"Bands (MHz)": "MVNO",
"References and notes": "[citation needed]"
},
{
"MCC": "724",
"MNC": "54",
"Brand": "Conecta",
"Operator": "PORTO SEGURO TELECOMUNICAÇÔES",
"Status": "Not Operational",
"Bands (MHz)": "MVNO",
"References and notes": "Defunct since 2018, clients were transferred to TIM.[6][17]"
},
{
"MCC": "724",
"MNC": "99",
"Brand": "Local",
"Operator": "",
"Status": "Operational",
"Bands (MHz)": "Unknown",
"References and notes": "Used for RanSharing control and roaming between TIM and Oi[6]"
}
]
};
// Função para analisar o CCID
function analyzeCCID(ccid) {
// Extrair o MNC do CCID
var mnc = ccid.substring(4, 6);
// Procurar a operadora correspondente
for (var i = 0; i < data.operators.length; i++) {
if (data.operators[i].MNC === mnc) {
return data.operators[i];
}
}
// Se nenhuma operadora correspondente for encontrada, retorne null
return null;
}
// Função para obter a operadora quando o botão é clicado
function getOperator() {
var ccid = document.getElementById('ccid').value;
var operator = analyzeCCID(ccid);
var result = document.getElementById('result');
if (operator) {
var operatorInfo =
//ccid
"CCID: " + ccid + "<br>" +
"MCC: " + operator.MCC + "<br>" +
"MNC: " + operator.MNC + "<br>" +
"Marca: " + operator.Brand + "<br>" +
"Operadora: " + operator.Operator + "<br>" +
"Status: " + operator.Status + "<br>" +
"Bandas de frequência LTE (MHz): " + operator["Bands (MHz)"] + "<br>";
result.innerHTML = operatorInfo;
} else {
result.textContent = "Nenhuma operadora encontrada para o CCID fornecido.";
}
}
</script>
</body>
</html>
|
<div class="container-fluid" style="width:90%;">
<div class="row">
<div class="col-md-5">
<h2 class="mt-4">{{'UpcomingTasks' | translate}}</h2>
<div *ngFor="let task of activeTasks | slice:0:3; ">
<div class="card mt-4 w-75" style="width: 18rem;">
<div class="card-body"
[ngClass]="{'bg-success-subtle': task.state == 3, 'bg-warning-subtle': task.state == 2, 'bg-danger-subtle': task.state == 1}">
<div class=" d-flex card-title">
<h5 class="card-title">{{task.name}} </h5>
<button class="ms-auto btn btn-outline-dark" data-bs-toggle="modal" data-bs-target="#taskModal"
(click)="selectTask(task)">{{'Open' | translate}}</button>
</div>
{{task.deadline | date}}
<hr>
<p class="card-text">{{task.status}}</p>
<div class=" d-flex">
<h5 class="ms-0 text-muted fst-italic">
{{task.deadline | daysAgo}}
</h5>
<h4 class="ms-auto">
<i *ngIf="task.state==3" class="bi bi-check-circle-fill text-success"></i>
<i *ngIf="task.state==2" class="bi bi-hourglass-split text-warning"></i>
<i *ngIf="task.state==1" class="bi bi-x-circle-fill text-danger"></i>
</h4>
</div>
</div>
</div>
</div>
</div>
<div class=" col-md-7">
<h2 class="mt-4">{{'MyTasks' | translate}}</h2>
<div class=" row gx-4">
<div class="col-md-6 mt-4">
<label for="state">{{'State' | translate}}</label>
<select ngModel (ngModelChange)="myStateSelectHandler($event)" name="" id="state" class="form-select mt-1">
<option value="all">{{'All' | translate}}</option>
<option value="notStarted">{{'NotStarted' | translate}}</option>
<option value="pending">{{'Pending' | translate}}</option>
<option value="completed">{{'Complete' | translate}}</option>
</select>
</div>
<div class="col-md-6 mt-4">
<label for="sort">{{'SortBy' | translate}}</label>
<select ngModel (ngModelChange)="mySelectHandler($event)" name="sort" id="sort" class="form-select mt-1">
<option value="deadline" (click)="sortByDeadline()">{{'Deadline' | translate}}</option>
<option value="name" (click)="sortByName()">{{'Name' | translate}}</option>
<option value="projectName" (click)="sortByProjectName()">{{'Project' | translate}}</option>
</select>
</div>
</div>
<div class=" row gx-5 ms-2 mt-4">
<div class="col-md-1 fw-bold">
ID
</div>
<div class="col-md-3 fw-bold">
{{'Name' | translate}}
</div>
<div class="col-md-3 fw-bold">
{{'Project' | translate}}
</div>
<div class="col-md-3 fw-bold">
{{'Deadline' | translate}}
</div>
<div class="col-md-2 fw-bold">
</div>
</div>
<div *ngFor="let task of tasksToShow">
<div class=" row gx-5 mt-4 ms-1 me-1 pt-4 pb-3 rounded-4 shadow-sm"
[ngClass]="task.state==1 ? 'bg-danger-subtle' : task.state==2 ? 'bg-warning-subtle' : 'bg-success-subtle' ">
<div class="col-md-1">
{{task.id}}
</div>
<div class="col-md-3">
{{task.name}}
</div>
<div class="col-md-3">
{{task.projectAssociatedTo?.name}}
</div>
<div class="col-md-3">
{{task.deadline | date}}
</div>
<div class="col-md-2">
<button type="button" (click)="selectTask(task)" data-toggle="modal"
data-target="#taskModal" class="btn btn-outline-dark w-100">{{'Open' | translate}} </button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal for task details -->
<div id="taskModal" class="modal fade">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<!-- Header -->
<div class="modal-header"
[ngClass]="selectedTask?.state==1 ? 'bg-danger-subtle' : selectedTask?.state==2 ? 'bg-warning-subtle' : 'bg-success-subtle'">
<h2 class="ms-3 mt-3">{{selectedTask?.name}} </h2>
<button type="button" class="btn-close me-3" aria-label="Close" data-dismiss="modal"></button>
</div>
<!-- Body -->
<div class="modal-body ms-3">
<h4 class=" text-muted">{{selectedTask?.description}}</h4>
<div class=" row mt-3">
<div class="col-md-6">
{{'Project' | translate}} :<h4 class="">{{selectedTask?.projectAssociatedTo?.name}}</h4>
<hr class=" mt-2">
{{'Deadline' | translate}} :<h4 class=""> {{'DueIn' | translate}} {{selectedTask?.deadline | daysAgo}}</h4>
<h5 class=" fst-italic text-muted">{{selectedTask?.deadline | date}}</h5>
{{'State' | translate}} :<h4 *ngIf="selectedTask?.state==3" class=" text-success mt-3">{{'Complete' | translate}}</h4>
<h4 *ngIf="selectedTask?.state==2" class=" text-warning">{{'Pending' | translate}}</h4>
<h4 *ngIf="selectedTask?.state==1" class=" text-danger">{{'NotStarted' | translate}}</h4>
</div>
<div class="col-md-2">
</div>
<div class="col-md-4">
<div class="row mt-4 w-75">
<button (click)="setTaskState(selectedTask,2)" *ngIf="selectedTask?.state != 2"
class="btn btn-warning">{{'MarkAsPending' | translate}}</button>
</div>
<div class="row mt-4 w-75">
<button (click)="setTaskState(selectedTask,3)" *ngIf="selectedTask?.state != 3"
class="btn btn-success">{{'MarkAsComplete' | translate}}</button>
</div>
</div>
</div>
</div>
</div>
<!-- Footer -->
</div>
</div>
|
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
UseGuards,
Req,
BadRequestException,
} from '@nestjs/common';
import { PostsService } from './posts.service';
import { CreatePostDto } from './dto/create-post.dto';
import { UpdatePostDto } from './dto/update-post.dto';
import { ApiTags, ApiCreatedResponse, ApiOkResponse } from '@nestjs/swagger';
import { Post as PostEntity } from './entities/post.entity';
import { GetPostDto } from './dto/get-post.dto';
import { AuthGuard } from '../auth/auth.guard';
import { CustomRequest } from '../common/requests/custom-request';
@Controller('posts')
@ApiTags('posts')
@UseGuards(AuthGuard)
export class PostsController {
constructor(private readonly postsService: PostsService) {}
@Post()
@ApiCreatedResponse({
description: 'The post has been successfully created.',
type: PostEntity,
})
async create(@Body() postData: CreatePostDto, @Req() request: CustomRequest) {
const user = request?.user;
if (user.sub !== postData.author) {
throw new BadRequestException('Invalid request parameters');
}
return await this.postsService.create(postData);
}
@Get()
@ApiOkResponse({
description: 'The posts have been successfully retrieved.',
type: GetPostDto,
isArray: true,
})
async findAll(@Req() request: CustomRequest) {
console.log(request?.user);
return await this.postsService.findAll();
}
@Get(':id')
@ApiOkResponse({
description: 'The post has been successfully retrieved.',
type: GetPostDto,
})
async findOne(@Param('id') id: string, @Req() request: CustomRequest) {
console.log(request?.user);
return await this.postsService.findOne(+id);
}
@Patch(':id')
@ApiOkResponse({
description: 'The post has been successfully updated.',
type: PostEntity,
})
async update(@Param('id') id: string, @Body() updatePostDto: UpdatePostDto) {
return await this.postsService.update(+id, updatePostDto);
}
@Delete(':id')
@ApiOkResponse({
description: 'The post has been successfully removed.',
type: PostEntity,
})
async remove(@Param('id') id: string) {
return await this.postsService.remove(+id);
}
}
|
class Node:
def __init__(self, data) -> None:
self.data = data
self.next = None
class LinkedList:
def __init__(self, node) -> None:
self.head = Node(node) # 전체 리스트의 첫 번째 원소
def add(self, data):
if self.head is None:
self.head = Node(data)
else:
node = self.head
while node.next: # 끝까지 이동
node = node.next
node.next = Node(data) # 새 노드 연결
def delete(self, data): # data가진 node 삭제해라
if self.head is None:
return
node = self.head # 첫번째 node부터 탐색
if node.data == data: # head가 대상이면, 새로운 head 지정
self.head = node.next
del node
else: # singly linked list -> 삭제 시 이전 노드의 link가 삭제노드의 다음 노드 가리켜야 함
while node.next: # 다음 노드 탐색
temp = node.next # node:이전 노드, temp:삭제 노드
if temp.data == data:
node.next = temp.next #이전노드가 삭제노드의 다음 가리킴
del temp
return
else:
node = temp
def search(self, data):
node = self.head
while node:
if node.data == data:
return node
node = node.next
|
import type { SerializedStyles } from '@emotion/react'
import { css } from '@emotion/react'
import { Player } from '@lottiefiles/react-lottie-player'
import LoadingAnimation from '../../assets/animations/loading.json'
import { theme } from '../../utils/theme'
import { SVGType } from '../../utils/types'
type ButtonType = 'filled' | 'outlined' | 'ghost'
const buttonStyle = css`
padding: 0.5rem 1rem;
width: fit-content;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
gap: 0.4rem;
font-family: Rubik;
font-size: 1.125rem;
font-weight: 500;
border-radius: 0.25rem;
border-width: 1px;
border-style: solid;
border-color: grey;
:hover {
cursor: pointer;
}
`
const filledStyle = css`
background-color: ${theme.primary[500]};
border-color: ${theme.primary[500]};
color: white;
`
const outlinedStyle = css`
background-color: transparent;
border-color: ${theme.primary[500]};
color: ${theme.primary[500]};
`
const ghostStyle = css`
background-color: transparent;
border-color: transparent;
color: ${theme.primary[500]};
`
const loadingStyle = css`
background-color: transparent;
border-color: transparent;
:hover {
cursor: default;
}
`
const loadingAnimationStyle = css`
width: 1.2em;
height: 1.2em;
`
const iconStyle = css`
height: 1.125rem;
width: 1.125rem;
`
interface ButtonProps {
label: string
type: ButtonType
loading?: boolean
onClick: () => unknown
style?: SerializedStyles
LeftIcon?: SVGType
}
export const Button = (props: ButtonProps) => {
const { label, type = 'filled', loading = false, style, onClick, LeftIcon } = props
return (
<button
onClick={!loading ? onClick : undefined}
css={[
buttonStyle,
type === 'filled' ? filledStyle : type === 'outlined' ? outlinedStyle : ghostStyle,
loading && loadingStyle,
style,
]}
>
{loading ? (
<Player src={LoadingAnimation} autoplay loop css={loadingAnimationStyle} />
) : (
<>
{LeftIcon && <LeftIcon css={iconStyle} />}
{label}
</>
)}
</button>
)
}
|
<?php
namespace Database\Factories;
use App\Models\Pedido;
use App\Models\PedidoProducto;
use App\Models\Producto;
use Illuminate\Database\Eloquent\Factories\Factory;
class PedidoProductoFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = PedidoProducto::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
$producto_id = Producto::all()->random()->id;
$precio = Producto::where('id', '=', $producto_id)->first();
return [
'cantidad' => random_int(1,10),
'precio' => $precio->precio,
'producto_id' => $producto_id,
'pedido_id' => Pedido::all()->random()->id,
];
}
}
|
type PaymentBalance = {
name: string;
balance: number;
};
type Payment = {
from: string;
to: string;
amount: number;
};
export function consolidatePayments(paymentBalances: PaymentBalance[]) {
// throw error if balance do not add to zero
const total = paymentBalances.reduce((acc, pb) => pb.balance + acc, 0);
if (total !== 0) {
throw new Error("Expected balances to equal 0");
}
paymentBalances.sort((a, b) => a.balance - b.balance);
let payments: Payment[] = [];
// splice out 0 balance values
paymentBalances = paymentBalances.filter((pb) => pb.balance !== 0);
// Check if there are any items that match in size
while (paymentBalances.length > 0) {
let { equalPayments, pbs } = getEqualBalances(paymentBalances);
paymentBalances = pbs;
payments = payments.concat(equalPayments);
if (equalPayments.length) {
continue;
}
let result = findThreePersonPayment(paymentBalances);
if (result) {
payments = payments.concat(result.payments);
paymentBalances = result.rest;
continue;
}
// Check for ways to set up a payment/clear a payment
// cycle through payment balances for any one balance clearing items
let { nextPayments, rest } = getNextPayment(paymentBalances);
paymentBalances = rest;
payments = payments.concat(nextPayments);
}
return payments;
}
export function findThreePersonPayment(paymentBalances: PaymentBalance[]) {
let pbs = structuredClone(paymentBalances);
let pb: PaymentBalance;
let items: [number, number] | null = null;
for (let i = 0; i < pbs.length; i++) {
pb = pbs[i];
// @ts-ignore
const rest: PaymentBalance[] = pbs.toSpliced(i, 1);
items = findTwoEquallingValues(rest, pb.balance);
if (!items) continue;
// create payments
let payments: Payment[];
if (pb.balance < 0) {
payments = items.map((item) => ({
to: pb.name,
from: rest[item].name,
amount: rest[item].balance,
}));
} else {
payments = items.map((item) => ({
from: pb.name,
to: rest[item].name,
amount: rest[item].balance,
}));
}
// splice rest
for (const item of items.reverse()) {
rest.splice(item, 1);
}
// return
return { payments, rest };
}
return null;
}
export function findTwoEquallingValues(
paymentBalances: PaymentBalance[],
value: number,
// TS won't infer a tuple, just a num[]
): [number, number] | null {
for (let i = 0; i < paymentBalances.length; i++) {
for (let j = 0; j < paymentBalances.length; j++) {
if (i === j) continue;
const totalTogether =
paymentBalances[i].balance + paymentBalances[j].balance;
if (Math.abs(totalTogether) === Math.abs(value)) {
return [i, j];
}
}
}
return null;
}
export function getNextPayment(paymentBalances: PaymentBalance[]) {
const pbs = structuredClone(paymentBalances);
let [first, ...rest] = pbs;
if (first.balance >= 0) {
throw new Error("Expected balance of first item to be negative");
}
let payment: Payment | null = null;
for (let i = rest.length - 1; i >= 0; i--) {
const item = rest[i];
if (Math.abs(first.balance) < item.balance) {
continue;
}
payment = {
from: item.name,
to: first.name,
amount: item.balance,
};
first.balance = first.balance + item.balance;
rest.splice(i, 1);
break;
}
if (!payment) {
throw new Error("Could not find a suitable payment");
}
return { nextPayments: [payment], rest: [first, ...rest] };
}
export function getEqualBalances(paymentBalances: PaymentBalance[]) {
// Returns an array of equal payments and a spliced payment balance array
const pbs = structuredClone(paymentBalances);
let left = 0;
let right = pbs.length - 1;
const equalPayments: PaymentBalance[][] = [];
while (left < right) {
const rightItem = pbs[right];
const leftItem = pbs[left];
if (rightItem.balance + leftItem.balance === 0) {
equalPayments.push([leftItem, rightItem]);
pbs.splice(right, 1);
pbs.splice(left, 1);
// if (right >= pbs.length) {
right = right - 2;
// }
continue;
}
if (Math.abs(leftItem.balance) > Math.abs(rightItem.balance)) {
right--;
continue;
}
if (Math.abs(rightItem.balance) > Math.abs(leftItem.balance)) {
left++;
continue;
}
}
// convert equalPayments to a payments object
// {from: string; to: string, amount: number}
const payments = equalPayments.map((ePayment) => ({
from: ePayment[1].name,
to: ePayment[0].name,
amount: ePayment[1].balance, // May need a math.abs here
}));
return { equalPayments: payments, pbs };
}
|
/**
* @class Ext.tux.plugin.TouchTimeout
* @extend Ext.Evented
* @author Andrea Cammarata
* @docauthor Andrea Cammarata
* @aside example touch-timeout
*/
Ext.define('Ext.tux.plugin.TouchTimeout', {
extend: 'Ext.Evented',
alias: 'plugin.touchtimeout',
requires: ['Ext.tux.progressbar.Radial'],
config: {
/**
* @cfg {Ext.Component} component
* The component to which this plugin is connected.
* This will usually by set automatically when configuring the component with this plugin.
* @accessor
*/
component: null,
/**
* @cfg {Object} progressBar
* The radial progressbar configuration.
*/
progressBar: {
ui: 'dark'
}
},
/**
* The default configuration object that
* will be used to create the timeout ProgressBar.
* @private
*/
defaultProgressBarConfig: {
showValue: false,
cls: 'x-floating',
hideAnimation: 'popOut',
showAnimation: 'popIn'
},
/**
* @private
* Sets up all of the references the plugin needs
*/
init: function(component) {
component.element.on({
taphold: 'onTaphHold',
touchend: 'onTouchEnd',
touchmove: 'onTouchMove',
scope: this
});
this.setComponent(component);
},
// @private
onTaphHold: function(event){
var progressbar = this.getProgressBar();
progressbar.show();
progressbar.setValue(100);
this.onTouchMove(event);
},
// @private
onTouchEnd: function(){
var progressbar = this.getProgressBar();
progressbar.setValue(0);
progressbar.hide();
},
// @private
onTouchMove: function(event){
var progressbar = this.getProgressBar(),
box = progressbar.element.getBox(),
top = event.pageY - (box.height / 2),
left = event.pageX - (box.width / 2);
progressbar.setTop(top);
progressbar.setLeft(left);
},
/**
* Create the radial progressbar and update the getProgressBar reference.
* @param {Object} config The configuration used to create the progressbar.
* @private
*/
applyProgressBar: function(config) {
Ext.applyIf(config, this.defaultProgressBarConfig);
return Ext.factory(config, Ext.tux.progressbar.Radial, this.getProgressBar());
},
/**
* Update the ProgressBar creating the new one and destroying
* the old one if any.
* @param {Ext.tux.progressbar.Radial} newProgressBar The new created progressbar.
* @param {Ext.tux.progressbar.Radial} oldProgressBar The old progressbar that eventually already exists.
* @private
*/
updateProgressBar: function(newProgressBar, oldProgressBar){
if(newProgressBar){
newProgressBar.setTop(0);
newProgressBar.setLeft(0);
newProgressBar.on('complete', 'fireEvent', this);
}
if(oldProgressBar) {
oldProgressBar.destroy();
}
},
// @private
fireEvent: function(progressbar){
var component = this.getComponent();
progressbar.setValue(0);
progressbar.hide();
component.fireEvent('timeout', this, component, progressbar);
}
});
|
package com.esgc.Dashboard.UI.Tests;
import com.esgc.Base.TestBases.UITestBase;
import com.esgc.Dashboard.UI.Pages.DashboardPage;
import com.esgc.PortfolioAnalysis.UI.Pages.ResearchLinePage;
import com.esgc.Utilities.BrowserUtils;
import com.esgc.Utilities.Xray;
import org.testng.annotations.Test;
import static com.esgc.Utilities.Groups.*;
public class EntityHyperlinksTests extends UITestBase {
@Test(groups = {REGRESSION, DASHBOARD, UI})
@Xray(test = {4329, 4922, 3829})
public void verifyDashboardHyperlinks() {
test.info("Navigate to Dashboard page");
DashboardPage dashboardPage = new DashboardPage();
dashboardPage.navigateToPageFromMenu("Climate Dashboard");
dashboardPage.selectSamplePortfolioFromPortfolioSelectionModal();
test.info("Verify view companies link");
dashboardPage.viewAllCompaniesButton.click();
String expPanelTitle = "Companies in " + dashboardPage.selectPortfolioButton.getText();
String actPanelTitle = dashboardPage.summaryCompaniesPanelTitle.getText();
assertTestCase.assertEquals(actPanelTitle, expPanelTitle,
"Panel title is verified as Companies in <portfolio name>");
dashboardPage.closePortfolioExportDrawer();
BrowserUtils.wait(10);
assertTestCase.assertTrue(dashboardPage.verifyDashboardHyperlinks("Portfolio Monitoring", 3),
"Portfolio Monitoring - Verify Controversy Link");
assertTestCase.assertTrue(dashboardPage.verifyDashboardHyperlinks("Portfolio Monitoring", 4),
"Portfolio Monitoring - Verify Entity Hyperlink");
assertTestCase.assertTrue(dashboardPage.verifyDashboardHyperlinks("Performance: Largest Holdings, Leaders, Laggards", 1),
"Portfolio Monitoring - Verify Largest Holdings Company Hyperlink");
dashboardPage.tabPerformanceLeaders.click();
assertTestCase.assertTrue(dashboardPage.verifyDashboardHyperlinks("Performance: Largest Holdings, Leaders, Laggards", 1),
"Portfolio Monitoring - Verify Performance Leaders Company Hyperlink");
dashboardPage.tabPerformanceLaggards.click();
assertTestCase.assertTrue(dashboardPage.verifyDashboardHyperlinks("Performance: Largest Holdings, Leaders, Laggards", 1),
"Portfolio Monitoring - Verify Performance Laggards Company Hyperlink");
//TODO Geomap is de-scoped until an update from business
// ArrayList<String> GeographicRisks = new ArrayList<>();
// GeographicRisks.add("Market Risk");
// GeographicRisks.add("Operations Risk");
// GeographicRisks.add("Supply Chain Risk");
// GeographicRisks.add("Temperature Alignment");
// GeographicRisks.add("Carbon Footprint");
// GeographicRisks.add("Green Share Assessment");
// GeographicRisks.add("Brown Share Assessment");
//
// for (String risk : GeographicRisks) {
// dashboardPage.selectResearchLineFromGeographicRiskMapDropDown(risk);
// System.out.println("Geographic Risk = " + risk);
// assertTestCase.assertTrue(dashboardPage.verifyGeographicRiskHyperlink(),
// "Geographic Risk Distribution - " + risk + ": Verify Entity Hyperlink");
// }
//TODO webelement is failing
assertTestCase.assertTrue(dashboardPage.verifyHeatMapHyperlink(),
"Heatmap: Verify Entity Hyperlink");
}
//TODO all researchline data provider
@Test(groups = {REGRESSION, DASHBOARD, UI})
@Xray(test = {4494, 3829})
public void verifyPortfolioAnalysisHyperlinks() {
ResearchLinePage researchLinePage = new ResearchLinePage();
test.info("Navigate to Portfolio Analysis page");
researchLinePage.navigateToPageFromMenu("Climate Portfolio Analysis");
DashboardPage dashboardPage = new DashboardPage();
researchLinePage.selectSamplePortfolioFromPortfolioSelectionModal();
researchLinePage.waitForDataLoadCompletion();
assertTestCase.assertTrue(dashboardPage.verifyPortfolioAnalysisHyperlinks("Updates", 1),
"Portfolio Analysis - Verify Updates Hyperlink");
assertTestCase.assertTrue(dashboardPage.verifyPortfolioAnalysisHyperlinks("Positive impact based on investment and score", 1),
"Portfolio Analysis - Verify Positive impact based on investment and score Hyperlink");
assertTestCase.assertTrue(dashboardPage.verifyPortfolioAnalysisHyperlinks("Negative impact based on investment and score", 1),
"Portfolio Analysis - Verify Negative impact based on investment and score Hyperlink");
//TODO webelement is failing
assertTestCase.assertTrue(dashboardPage.verifyPortfolioAnalysisHyperlinks("Leaders by Score", 2),
"Portfolio Analysis - Verify Leaders by Score Hyperlink");
assertTestCase.assertTrue(dashboardPage.verifyPortfolioAnalysisHyperlinks("Laggards by Score", 2),
"Portfolio Analysis - Verify Laggards by Score Hyperlink");
assertTestCase.assertTrue(dashboardPage.verifyRegionAndCountryHyperlinks("Europe, Middle East & Africa", 1),
"Portfolio Analysis - Verify Europe, Middle East & Africa Entity Hyperlink");
BrowserUtils.wait(10);
assertTestCase.assertTrue(dashboardPage.verifyRegionAndCountryHyperlinks("Basic Materials", 1),
"Portfolio Analysis - Verify Basic Materials Entity Hyperlink");
}
}
|
import json
from googleapiclient.discovery import build
from youtube_transcript_api import YouTubeTranscriptApi
from pytube import extract
import os
import openai
DEVELOPER_KEY = "AIzaSyComDNKoDV8ODeb2PJ8a7y-IErz732PuTQ"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
openai.organization = "org-T6bYvYJr8ulggtQqe0MnmbmL"
openai.api_key = "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"
def get_authenticated_service():
return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
def transcribe_video(video_id):
transcript_data = YouTubeTranscriptApi.get_transcript(video_id)
transcript_words = [i["text"].replace("\xa0", "").replace("\n", " ") for i in transcript_data]
truncated_transcript = " ".join(transcript_words[:1000]) # Take the first 1000 words
return truncated_transcript # Truncate after 1000 words
def main():
# Load playlists
with open('playlists.json', 'r') as file:
playlists = json.load(file)
training_data = []
youtube = get_authenticated_service()
for playlist in playlists:
playlist_id = playlist["Playlist ID"]
# Print playlist name
print(f"Playlist name: {playlist['Playlist Name']}")
# Get videos from playlist
request = youtube.playlistItems().list(
part='snippet',
maxResults=50,
playlistId=playlist_id
)
response = request.execute()
for item in response['items']:
video_id = item['snippet']['resourceId']['videoId']
# # Print video title
# print(f"Video title: {item['snippet']['title']}")
# Transcribe the video
try:
transcription = transcribe_video(video_id)
# Summarize the transcription using the OpenAI API
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo-16k-0613",
messages=[
{"role": "system", "content": "You will provided the first 1000 words of a Youtube video transcription. Please create a short summary of the video."},
{"role": "user", "content": transcription},
]
)
summary = completion.choices[0].message["content"]
except:
summary = "No summary available."
# Video description
description_text = item['snippet']['description']
description = " ".join(description_text.split()[:500])
# Append to training data
training_data.append({
"prompt": {
"Video Name": item['snippet']['title'],
"Creator": item['snippet']['videoOwnerChannelTitle'],
"Description": description,
"Summary": summary
},
"completion": playlist['Playlist Name']
})
print(training_data)
# # Save training data
# with open('training-data.txt', 'w') as file:
# for item in training_data:
# file.write(json.dumps(item) + '\n')
# print("Training data has been saved.")
if __name__ == "__main__":
main()
|
/* eslint-disable max-len */
import Model from '../Model/model';
import View from '../View/view';
interface IPresenterOptions {
step?: number;
minValue?: number;
maxValue?: number;
startSelectedValue?: number;
isVertical?: boolean;
hasScale?: boolean;
scalePoints?: number;
}
class Presenter {
$rootElement: HTMLElement;
model: Model;
view: View;
constructor($rootElement: HTMLElement, options: IPresenterOptions) {
this.$rootElement = $rootElement;
this.model = new Model({
minValue: options.minValue,
maxValue: options.maxValue,
startSelectedValue: options.startSelectedValue,
step: options.step,
});
this.view = new View({
$rootElement,
isVertical: options.isVertical,
hasScale: options.hasScale,
scalePoints: options.scalePoints,
});
this.model.subscribe(this);
this.view.subscribe(this);
this.setInitialViewValues();
}
setInitialViewValues() {
const startSelectedValue = this.model.getStartSelectedValue();
const endSelectedValue = this.model.getEndSelectedValue();
this.view.setStartPointPosition(this._transformModelValueToViewPercent(startSelectedValue));
this.view.setStartTipValue(startSelectedValue);
this.view.setStartLimitValue(this.model.getMinValue());
this.view.setEndPointPosition(this._transformModelValueToViewPercent(endSelectedValue));
this.view.setEndTipValue(100 - endSelectedValue);
this.view.setEndLimitValue(this.model.getMaxValue());
this.view.setScaleValues(this.calculateScaleValues());
}
calculateScaleValues() {
const scaleValues = [];
const minValue = this.model.getMinValue();
const maxValue = this.model.getMaxValue();
const range = maxValue - minValue;
const scalePoints = this.view.getScalePoints();
const scaleDelta = range / (scalePoints - 1);
for (let valueIndex = 0; valueIndex < scalePoints; valueIndex += 1) {
const scaleValue = minValue + valueIndex * scaleDelta;
scaleValues.push(parseFloat(scaleValue.toFixed(2)));
}
return scaleValues;
}
// eslint-disable-next-line class-methods-use-this
_transformViewPercentToModelValue(percents: number) {
return ((percents * this.model.getRange()) / 100) + this.model.getMinValue();
}
// eslint-disable-next-line class-methods-use-this
_transformModelValueToViewPercent(value: number) {
return ((value - this.model.getMinValue()) * 100) / this.model.getRange();
}
update(action: {type: string, data: number}) {
switch (action.type) {
case 'sliderClickedCloserToStartPoint': {
const newValue = this._transformViewPercentToModelValue(action.data);
this.model.setStartSelectedValue(newValue);
break;
}
case 'sliderClickedCloserToEndPoint': {
const newValue = this._transformViewPercentToModelValue(action.data);
this.model.setEndSelectedValue(newValue);
break;
}
case 'modelUpdatedStartSelectedValue': {
const newValue = this._transformModelValueToViewPercent(action.data);
this.view.setStartPointPosition(newValue);
this.view.setStartTipValue(action.data);
break;
}
case 'modelUpdatedEndSelectedValue': {
const newValue = this._transformModelValueToViewPercent(action.data);
this.view.setEndPointPosition(newValue);
this.view.setEndTipValue(100 - action.data);
break;
}
case 'startPointMoved': {
const newValue = this._transformViewPercentToModelValue(action.data);
this.model.setStartSelectedValue(newValue);
break;
}
case 'endPointMoved': {
const newValue = this._transformViewPercentToModelValue(action.data);
this.model.setEndSelectedValue(newValue);
break;
}
case 'modelUpdatedMinValue': {
this.view.setStartLimitValue(action.data);
this.view.setScaleValues(this.calculateScaleValues());
break;
}
case 'modelUpdatedMaxValue': {
this.view.setEndLimitValue(action.data);
this.view.setScaleValues(this.calculateScaleValues());
break;
}
default:
console.log('Unknown action type');
break;
}
}
}
export default Presenter;
|
<template>
<div>
<!-- 导航栏 -->
<div class="navbar">
<van-nav-bar title="商品评论" left-text="返回" left-arrow @click-left="onClickLeft()"
style="background-color: rgba(152, 230, 240, 0.6);" />
</div>
<!-- 评论 -->
<div v-for="item in commonts" :key="item.id">
<div style="margin-top:10px;">
<!-- 头像 -->
<van-image round width="5rem" height="5rem" :src="utils.getImage(item.userImg)" />
<!-- 点赞与评论 -->
<van-icon :name="isGive ? 'like' : 'like-o'" style="position: relative;top: -65px;left: 120px;" size="25px"
@click="changeGive(item.id, item.giveLike)">{{ item.giveLike
}}</van-icon>
<van-icon name="chat-o" style="position: relative;top: -65px;right: -160px;" size="25px"
@click="lookSonComment(item.id)">{{ item.sonComments
}}</van-icon>
<!-- 评论用户名 -->
<div style="margin: -90px 0px 10px 100px;">{{ item.userName }}</div>
<!-- 内容 -->
<div style="margin: 0px 0px 50px 100px;">{{ item.content }}</div>
<!-- 图片 -->
<van-grid :column-num="3" style="width: 80%;margin:auto;" gutter="5">
<van-grid-item v-for="(i, index) in item.commentImgs" :key="index">
<van-image width="100%" height="100%" :src="utils.getImage(i)" />
</van-grid-item>
</van-grid>
<!-- 评分 -->
<van-rate style="margin: 20px 0px 0px 90px;" v-model="item.score" />
<!-- 时间 -->
<div style="margin: -20px 0px 0px 200px;">{{ utils.timestampToTime(item.createTime) }}</div>
<hr>
</div>
</div>
<!-- 子评论弹出层 -->
<van-popup v-model="commentShow" overlay round close-on-popstate safe-area-inset-bottom position="bottom"
:style="{ height: '60%' }" style="background-color: rgba(152, 230, 240, 0.8);">
<van-row type="flex" justify="end" style="height: 20px;text-align: center;">
<van-col span="8">评论</van-col>
<van-col span="8" @click="addCommentShow = true">发布评论</van-col>
</van-row>
<div v-if="sonComments.length !== 0">
<van-cell v-for="item in sonComments" :key="item.id" style="background-color: rgba(152, 230, 240, 0.8);">
<div style="margin-top:40px;width: 70%;">
<div style="display: flex;width: 100%;">
<!-- 头像 -->
<div style="margin-right: 20px;">
<van-image round width="5rem" height="5rem" :src="utils.getImage(item.userImg)" />
</div>
<!-- 评论用户名 -->
<div style="margin-right: 50px;">{{ item.userName }}</div>
<!-- 商铺名 -->
<div style="color: aqua;">{{ item.shopName }}</div>
</div>
<!-- 时间 -->
<div style="margin:-60px 0px 0px 100px;color: cadetblue;">
{{ utils.timestampToTime(item.createTime) }}</div>
<!-- 内容 -->
<div style="margin:10px 0px 20px 100px;font-size: 18px;">{{ item.content }}</div>
</div>
<!-- 点赞评论 -->
<div style="display: flex;">
<!-- 评分 -->
<div style="width: 50%;"><van-rate v-model="item.score" /></div>
</div>
</van-cell>
</div>
<div v-else><van-empty description="暂无评论" /></div>
</van-popup>
<!-- 发布评论弹出框 -->
<van-popup v-model="addCommentShow" position="bottom" style="background-color: rgba(152, 230, 240, 0.8);" round
safe-area-inset-bottom :style="{ height: '70%' }" closeable>
<van-row type="flex" justify="end" style="height: 40px;text-align: center;">
<van-col span="24">评价</van-col>
</van-row>
<!-- 内容 -->
<van-field v-model="comment.content" rows="3" autosize type="textarea" maxlength="50" placeholder="请评论"
show-word-limit />
<div style="height: 30px;line-height: 30px;display: flex;width: 100%;margin:20px 0px;">
<span style="margin: 10px 150px 10px 10px;">请评分</span>
<div style="margin: 15px;"><van-rate v-model="comment.score" icon="like" void-icon="like-o"
void-color="gray" /></div>
</div>
<van-button type="danger" size="large" round @click="addNoHeadComment">发布评论</van-button>
</van-popup>
</div>
</template>
<script>
import axios from 'axios'
import { Toast } from 'vant'
import utils from '@/utils'
export default {
name: 'comment',
data() {
return {
goodsId: this.$route.query.goodsId,
commonts: '',
sonComments: '',
commentShow: false,
addCommentShow: false,
isGive: false,
comment: {
shopId: this.$route.query.shopId,
content: '',
score: 0,
goodsId: '',
orderId: null,
userId: window.sessionStorage.getItem('token.id'),
isHead: 0,
headCommentId: ''
}
}
},
created() {
this.getCommont()
},
methods: {
addNoHeadComment() {
this.comment.goodsId = this.goodsId;
axios.post('/goods/comment', this.comment).then(res => {
if (res.data.flag) {
Toast('评论成功')
this.getCommont()
this.addCommentShow = false
this.commentShow = false
}
})
},
changeGive(id, giveLike) {
if (!this.isGive) {
giveLike += 1
} else {
giveLike -= 1
}
axios.put('/goods/comment/give/' + id + '/' + giveLike).then(res => {
if (res.data.flag) {
if (!this.isGive) {
Toast('点赞成功')
} else {
Toast('取消点赞')
}
this.getCommont()
this.isGive = !this.isGive
}
})
},
onLoad() {
},
lookSonComment(id) {
this.commentShow = true
this.comment.headCommentId = id
axios.get('/goods/comment/notHead/' + this.goodsId + '/' + id).then(res => {
if (res.data.flag) {
this.sonComments = res.data.data
this.sonComImgs = res.data.data.img.split(',')
this.sonComImgs.splice(this.sonComImgs.length - 1, 1)
console.log(this.sonComImgs)
}
})
},
getCommont() {
axios.get('/goods/comment/head/' + this.goodsId).then(res => {
if (res.data.flag) {
this.commonts = res.data.data
}
})
},
onClickLeft() {
this.$router.back()
},
}
}
</script>
<style></style>
|
// Подсистема "Логирование". (Интерфейсный модуль логирования)
//
#Область ИнтерфейсныеПроцедуры
// Функция - получает основной обработчик записи логов в зависимости от контекста
//
// Параметры:
// ИмяЛога - Строка - имя лога
// ПараметрыЗаписи - Структура - параметры записи лога
//
// Возвращаемое значение:
// ОбработкаОбъект.ктв_Логирование - обработка или форма, выполняющая обработку вывода логов
// УправляемаяФорма
//
Функция ПолучитьЛог(ИмяЛога, ПараметрыЗаписи = Неопределено) Экспорт
Лог = Неопределено;
#Если Сервер ИЛИ ВнешнееСоединение Тогда
Лог = Обработки.ктв_Логирование.Создать();
#Иначе
Лог = ПолучитьФорму("Обработка.ктв_Логирование.Форма");
#КонецЕсли
Лог.ИмяЛога(ИмяЛога);
Лог.ПараметрыЗаписи(ПараметрыЗаписи);
Возврат Лог;
КонецФункции //ПолучитьЛог()
// Функция - фозвращает структуру доступных уровней лога
//
// Возвращаемое значение:
// ФиксированнаяСтруктура - доступнуе уровни лога
//
Функция УровниЛога() Экспорт
УровниЛога = Новый Структура;
УровниЛога.Вставить("Отладка" , 0);
УровниЛога.Вставить("Информация" , 1);
УровниЛога.Вставить("Предупреждение" , 2);
УровниЛога.Вставить("Ошибка" , 3);
УровниЛога.Вставить("КритичнаяОшибка", 4);
УровниЛога.Вставить("Отключить" , 5);
Возврат Новый ФиксированнаяСтруктура(УровниЛога);
КонецФункции //УровниЛога()
// Процедура выполняет запись в лог по всем способам логирования
//
// Параметры:
// ИмяЛога - Строка - имя лога
// Текст - Строка - текст выводимого сообщения
// УровеньЛога - Число - уровень лога: Отладка, Информация, ошибка и т.п.
// ПараметрыЗаписи - Структура - дополнительные параметры записи информации в лог
//
Процедура ЗаписатьВЛог(ИмяЛога, Текст, УровеньЛога = 1, ПараметрыЗаписи = Неопределено) Экспорт
Если НЕ ТипЗнч(ПараметрыЗаписи) = Тип("Структура") Тогда
ПараметрыЗаписи = Новый Структура();
КонецЕсли;
ПараметрыЗаписи.Вставить("ИмяЛога" , ИмяЛога);
ПараметрыЗаписи.Вставить("УровеньЛога" , УровеньЛога);
СпособыЛогирования = ктв_ЛогированиеВызовСервера.ПолучитьСпособыЛогирования(ИмяЛога);
Для Каждого ТекСпособ Из СпособыЛогирования Цикл
#Если НЕ (Сервер ИЛИ ВнешнееСоединение) Тогда
ктв_ЛогированиеКлиент.ЗаписатьВЛог(Текст, ТекСпособ, ПараметрыЗаписи);
#КонецЕсли
ктв_ЛогированиеВызовСервера.ЗаписатьВЛог(Текст, ТекСпособ, ПараметрыЗаписи);
КонецЦикла;
КонецПроцедуры //ЗаписатьВЛог()
#КонецОбласти
|
(ns minecraft-web.app
(:require
[reagent.core :as reagent]
[reagent.dom :as rdom]
[minecraft-web.util :as util]
[minecraft-web.game :as game])
(:import [socket io-client])
)
(def key-code->block-type {
1 "blue"; 86
2 "yellow"; 87
3 "green";88
4 "orange";89
5 "purple";90
6 "red";91
})
(def socket (io-client/io.))
(def g (game/create))
;(.. g -controls target -avatar -position toArray)
;(game/add-block! g [1 1 1] "blue")
(defn ^:dev/before-load stop []
(js/console.log "stop"))
(try
(.parse js/JSON "[1]")
(catch js/Error e
(prn "no parse")))
(def connected (atom false))
(def game-obj (atom nil))
(def game-state (atom nil))
(def history (reagent/atom []))
(def current-model (reagent/atom nil))
;(def prev-utterances (reagent/atom []))
(defn add-block-to-game! [g party position block-type]
(swap! history conj {:type :action :src party :data [position block-type "putdown"]})
(game/add-block! g position block-type))
(defn remove-block-from-game! [g party position]
(swap! history conj {:type :action :src party :data [position "pickup"]})
(game/remove-block! g position))
;(.. g -opts)
;(.. g -opts -container)
(defn is-utterance? [h]
(= :utterance (h :type)))
(defn encoded-game-state []
(let [dialog (into [] (comp (filter is-utterance?) (map :data)) @history)
actions (into [] (comp (remove is-utterance?) (map :data)) @history)
payload {:actions actions :dialog dialog :model @current-model}]
(->> payload
(clj->js)
(.stringify js/JSON))))
(defn send-update! []
(let [encoded-state (encoded-game-state)]
(.log js/console "sending" encoded-state)
(.emit socket "update-game" encoded-state)))
(defn game []
(reagent/create-class ;; <-- expects a map of functions
{:display-name "voxel-game" ;; for more helpful warnings & errors
:component-will-unmount
(fn [this]
(.destroy g)
;(.remove (util/$ "#stats"))
)
:component-did-mount ;; the name of a lifecycle function
(fn [this]
(let [
;container (.appendChild (util/$ "div#game") (util/createEl "div"))
container (util/$ "div#game")
; g (game/create ;{:container container}
;)
]
(game/add-to-dom g container)
(game/setup! g game-state)
(util/on-keypress js/window (fn [ev]
(when-let [block-type (->> ev
(.-key)
(js/parseInt)
(get key-code->block-type))]
(when-let [position (game/raycast-adjacent g)]
(add-block-to-game! g "Architect" position block-type)))))
;(prn (.playerPosition game))
(reset! game-obj g)
)
) ;; your implementation
:reagent-render ;; Note: is not :render
(fn [] ;; remember to repeat parameters
[:div#game {:style {:height "100vh"}}])}))
(defn add-random-block []
(.log js/console (.-createBlock @game-obj))
(.createBlock @game-obj [1 63 1] 86))
;(.setBlock @game-obj [0 63 0] 86;)
(defn input-field [state]
[:input {:type "text"
:value @state
:on-change (fn [event]
(reset! state (-> event .-target .-value)))}])
(defn chat-history [utterances]
; [:p (str utterances)]
[:ul (for [[i {:keys [src data]}] (map-indexed vector utterances)]
^{:key i} [:li [:b (str "<" src ">: ")] (str data)])])
;)
(defn select [properties values]
[:select properties
(for [[k v] values]
^{:key k} [:option {:value k} v])])
(def models
{:collaborative "Collaborative"
:learn_to_ask "LearnToAsk"})
(defn chat []
(let [current-utterance (reagent/atom "")
]
(fn []
[:div
[chat-history @history]
[:div
[input-field current-utterance]
[:button {
:disabled (empty? @current-utterance)
:on-click
(fn []
(swap! history conj {:type :utterance :src "Architect" :data @current-utterance})
(reset! current-utterance "")
(send-update!))} "send"]
[select {:name :model
:ref (fn [el] (when (some? el) (reset! current-model (. el -value))))
:on-change (fn [ev] (reset! current-model (.. ev -target -value)))} models]
]])))
(defn root []
[:div.container>div.row
[:div.col-sm-3
[:h1 "Chat"]
[chat]]
[:div.col-sm-9
[game]]
])
(defn mount-root []
(rdom/render [root] (.getElementById js/document "root")))
(defn ^:dev/after-load start []
(js/console.log "start")
(mount-root))
(defn decode-game-state [state]
(as-> state m
(js->clj m :keywordize-keys true)
(:actions m)
; (map (fn [[k v]] (vector k v)) m)
; (into {} m)
))
(defn socket-receive [data]
(.log js/console "ssocket receive new game state" data)
(.log js/console "ssocket receive new game state, decoded" (decode-game-state data))
(let [new-actions (map (fn [data] {:type :action :src "Builder" :data data}) data)]
(doseq [[coord color pickup-or-putdown] (decode-game-state data)]
(case pickup-or-putdown
"putdown" (add-block-to-game! g "Builder" coord color)
"pickup" (remove-block-from-game! g "Builder" coord)
(.log js/console (str "no action for \"" pickup-or-putdown "\""))))
;(swap! history concat new-actions)
;(let [new-game-state (merge (decode-game-state data) @game-state)]
;(reset! game-state new-game-state)))
))
(defn init []
(js/console.log "init")
(let []
(.on socket "update-game" socket-receive)
(.on socket "disconnect" #(reset! connected false))
(.on socket "connect"
(fn []
(reset! connected true)
(.log js/console "connected!")
))
(mount-root)))
;
(comment (prn "hello world"))
;(prn @game-state)
(comment (swap! game-state assoc [2 63 -4] 86))
(comment (swap! game-state dissoc [2 63 -3] 86))
;(swap! game-state assoc [2 63 -4] 86)
|
import turtle & math libraries
set the colormode to 255
create the panel (size = screen size, color = black)
change the turtle color (80, 80, 200)
set turtle speed to fastest (10)
pick pen up
# Circle spiro
define variable int - inc (the angle between circles = 10)
define variable int - numIt (number of iterations needed to complete the spiro = int(360/inc) = 36)
define variable int - innerCirc (the radius of the inner circle = 2)
define variable int - radius (the radius of the circles within the spiro = 50)
move turtle to the center of the spiro (150, 150)
for iteration in range(numIt):
put pen down
draw a circle with radius, (variable) radius (50)
move the turtle forward to the next circle starting point (move by int innerCirc (2))
turn turtle to the right by angle, (variable) degrees (10) (rotate to where the next circle should start to cause the circles to create a spirograph)
pick pen up
# Polygon spiro
define variable int - size (how big the polygon is = 50)
define variable int - sides (how many sides the polygon will have = 4)
define variable int/float - angle (the internal angles of the shape = 360/sides = 90)
define variable int - inc (the angle between polygons = 10)
define variable int - numIt (number of iterations needed to complete the spiro = int(360/inc) = 36)
define variable int - innerCirc (the radius of the inner circle = 20)
move turtle to the center of the spiro (-100, -50)
for iteration2 in range(numIt):
put the pen down
for iteration1 in range(sides):
move the turtle forward by size (draw side of polygon)
turn turtle to the right by angle (turn into direction of where next side will go)
pick the pen up
move the turtle forward by innerCirc (move to where the next polygon will start)
turn turtle to the right by inc (rotate to where the next polygon should start to cause the polygons to move into a circle (spirograph))
turtle.done()
|
import React from 'react';
type CategoriesProps = {
value: number;
onClickCategory: (index: number) => void;
};
export const Categories: React.FC<CategoriesProps> = ({ value, onClickCategory }) => {
const categories = ['Все', 'Офисный', 'Игровой', 'Универсальный', 'Смартбук', 'Ультрабук'];
return (
<div className="categories">
<ul>
{categories.map((category, i) => (
<li key={i} onClick={() => onClickCategory(i)} className={value === i ? 'active' : ''}>
{category}
</li>
))}
</ul>
</div>
);
};
|
import React from 'react'
import { Box, Button, Heading, Image, Input, Spacer, Text } from '@chakra-ui/react';
import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
const Signin = () => {
const navigate = useNavigate()
const [user, setUser] = useState({
name: "", email: "", password: "", phone: "", address: "", city: "", state: "", pincode: ""
})
console.log(user.phone.length);
let name, value
const handle = (e) => {
name = e.target.name;
value = e.target.value;
setUser({ ...user, [name]: value })
}
// console.log(user);
const PostData = async (e) => {
e.preventDefault();
const { name, email, password, phone, address, city, state, pincode } = user;
console.log(phone.length);
if (phone.length !== 10) {
alert("Phone number is not valid")
}
else {
const data =
await fetch("https://kfcbackendproject.herokuapp.com/signup",
{
method: "POST",
headers: {
"Content-Type": "application/json"
// 'Access-Control-Allow-Origin': "*",
},
body: JSON.stringify({
name, email, password, phone, address, city, state, pincode
})
})
const res = await data.json();
console.log(data.status);
if (data.status === 401 || !res) {
window.alert("Phone no. or Email is already exist, please use differnt phone number")
// console.log("invalid registration");
}
else if (data.status === 451) {
window.alert("Please fill all filled")
// navigate("/login", { replace: true })
}
else if (data.status === 200) {
window.alert("OPT is send to your number");
setTimeout(() => {
window.alert("please wait we are verifying your OTP");
}, 2000);
setTimeout(() => {
navigate("/login", { replace: true })
}, 2000);
}
}
}
return (
<div>
<Box w='100%' p={4} color='white' >
<form method='POST'>
<Box w='35%' h="500px" color='black' margin={"auto"} textAlign="center">
<Box w='100%' p={4} color='black' margin={"auto"}>
<Heading as='h6' size='xs'>
Sign In / Sign Up
</Heading>
</Box>
<Box w='100%' p={4} color='black' margin={"auto"}>
<Text margin={"auto"} marginLeft={"210px"}>
<Image src="https://online.kfc.co.in/static/media/kfcLogo.492728c6.svg" alt='kfc' />
</Text>
</Box>
<Box w='100%' p={4} color='black' margin={"auto"}>
<Heading as='h5' size='md'>
LET’S SIGN IN OR CREATE ACCOUNT WITH YOUR PHONE NUMBER!
</Heading>
</Box>
<Box w='100%' p={4} color='black' margin={"auto"}>
<Input name='name' value={user.name} variant='flushed' placeholder='Name*' onChange={handle} />
<Input name='email' value={user.email} variant='flushed' placeholder='Email*' onChange={handle} />
<Input name='password' value={user.password} variant='flushed' placeholder='Password*' onChange={handle} />
<Input name='phone' value={user.phone} variant='flushed' placeholder='Phone Number*' onChange={handle} />
<Input name='address' value={user.address} variant='flushed' placeholder='Address' onChange={handle} />
<Box display={"flex"}>
<Input name='city' value={user.city} variant='flushed' placeholder='City' onChange={handle} />
<Input name='state' value={user.state} variant='flushed' placeholder='State' onChange={handle} />
</Box>
<Input name='pincode' value={user.pincode} variant='flushed' placeholder='Pin Code' onChange={handle} />
</Box>
<Box w='100%' p={4} color='black' margin={"auto"}>
<Text fontSize='sm'>By “logging in to KFC”, you agree to our Privacy Policy and Terms & Conditions.</Text>
</Box>
<Button onClick={PostData} marginTop={"10px"} borderRadius={"50px"} bg={"black"} color={"white"}>Send Me a Code</Button>
<Box marginTop={"10px"} display={"flex"}>
<Box borderTop={"1px solid rgb(68,68,68)"} w="45%" marginTop={"10px"}></Box>
<Spacer />
<Box>Or</Box>
<Spacer />
<Box borderTop={"1px solid rgb(68,68,68)"} w="45%" marginTop={"10px"}></Box>
</Box>
<Link to={"/menu"}>
<Button marginTop={"10px"} borderRadius={"50px"} border={"1px solid black"} color={"black"} w="90%" bg={"white"}>Skip, Continue As guest</Button>
</Link>
</Box>
</form>
</Box>
</div>
)
}
export default Signin
|
import os
import pandas as pd
from docx import Document
from docx.shared import Pt
# def extract_data_from_excell(file_name: str, sheet_name: str) -> None:
# result = []
# df = pd.read_excel(file_name, sheet_name=sheet_name)
# for main_row_index in range(3, len(df), 9):
# main_index, main_row = tuple(df.iterrows())[main_row_index]
# pds_no = tuple(main_row.items())[1][1]
# product_name = tuple(main_row.items())[2][1]
# product_description = tuple(main_row.items())[3][1]
# benefits = tuple(main_row.items())[5][1]
# benefits = benefits.split('\n')
# sae_grade = tuple(main_row.items())[7][1]
# api = tuple(main_row.items())[8][1]
# ilsac = tuple(main_row.items())[9][1]
# acea = tuple(main_row.items())[10][1]
# oem_claims = tuple(main_row.items())[11][1]
# recommendations = tuple(main_row.items())[12][1]
# performance_claims = get_performance_claims(api, ilsac, acea, oem_claims, recommendations)
# row_item = {
# 'pds_no': pds_no,
# 'product_name': product_name,
# 'product_description': product_description,
# 'benefits': benefits,
# 'sae_grade': sae_grade,
# 'performance_claims': performance_claims,
# }
# result.append(row_item)
# return result
# def get_performance_claims(
# api: str,
# ilsac: str,
# acea: str,
# oem_claims: str,
# recommendations: str
# ) -> list:
# result = []
# if api not in ['Not available', 'Not applicable', '', None]:
# result.append(f'API {api}')
# if ilsac not in ['Not available', 'Not applicable', '', None]:
# result.append(f'ILSAC {ilsac}')
# if acea not in ['Not available', 'Not applicable', '', None]:
# result.append(f'ACEA {acea}')
# if oem_claims not in ['Not available', 'Not applicable', '', None]:
# if ',' in oem_claims:
# oem_claims = oem_claims.split(',')
# else:
# oem_claims = oem_claims.split('\n')
# result.extend([item.strip() for item in oem_claims])
# if recommendations not in ['Not available', 'Not applicable', '', None]:
# if ',' in recommendations:
# recommendations = recommendations.split(',')
# else:
# recommendations = recommendations.split('\n')
# result.extend([item.strip() for item in recommendations])
# return result
# def generate_docx(
# template_name: str,
# pds_no: str,
# product_name: str,
# product_description: str,
# fetaures: list,
# sae_grade: str,
# oil_type: str,
# performance_claims: list,
# ) -> None:
# doc = Document(template_name)
# product_name_place = "Product-name"
# product_description_place = "Prod-desc"
# fetaures_place = "Features-benefits"
# performance_claims_place = "Performance-claim"
# performance_claims_title = "Performance claims"
# oil_type_place = "Oil-type"
# for paragraph in doc.paragraphs:
# if fetaures_place in paragraph.text:
# paragraph.clear()
# paragraph.text = "\n".join([f"• {item}" for item in fetaures])
# for run in paragraph.runs:
# run.font.name = "Arial"
# if performance_claims_place in paragraph.text:
# paragraph.clear()
# if performance_claims:
# paragraph.text = "\n".join([f"• {item}" for item in performance_claims])
# for run in paragraph.runs:
# run.font.name = "Arial"
# else:
# for paragraph_inner in doc.paragraphs:
# if performance_claims_title in paragraph_inner.text:
# paragraph_inner.clear()
# if product_name_place in paragraph.text:
# paragraph.text = paragraph.text.replace(
# product_name_place, product_name
# )
# for run in paragraph.runs:
# run.font.name = "Arial"
# run.font.size = Pt(16)
# run.bold = True
# if product_description_place in paragraph.text:
# paragraph.text = paragraph.text.replace(
# product_description_place, product_description
# )
# for run in paragraph.runs:
# run.font.name = "Arial"
# if oil_type_place in paragraph.text:
# paragraph.text = paragraph.text.replace(oil_type_place, oil_type)
# for run in paragraph.runs:
# run.font.name = "Arial"
# save_folder = r"engine"
# product_folder = product_name.replace("/", "-")
# for i in range(1, 4):
# for section in doc.sections:
# header = section.header
# header.paragraphs[4].text = f"PDS No.: {pds_no}/0{i}"
# for run in header.paragraphs[4].runs:
# run.font.name = "Arial"
# run.font.size = Pt(9)
# if not os.path.exists(f'{save_folder}/{product_folder}'):
# os.makedirs(f'{save_folder}/{product_folder}')
# doc.save(
# f'{save_folder}/{product_folder}/{product_folder}_{sae_grade}_0{i}_eng.docx'
# )
def extract_data_from_excell(file_name: str, sheet_name: str) -> None:
result = []
df = pd.read_excel(file_name, sheet_name=sheet_name)
for main_row_index in range(3, len(df), 9):
main_index, main_row = tuple(df.iterrows())[main_row_index]
pds_no = tuple(main_row.items())[1][1]
product_name = tuple(main_row.items())[2][1]
product_description = tuple(main_row.items())[3][1]
benefits = tuple(main_row.items())[5][1]
benefits = benefits.split('\n')
# sae_grade_value = tuple(main_row.items())[6][1]
# sae_grade = sae_grade_value if sae_grade_value != 'Not available' else ''
api = tuple(main_row.items())[7][1]
# oem_claims = tuple(main_row.items())[6][1]
specifications = tuple(main_row.items())[8][1]
print(main_index, pds_no)
performance_claims = get_performance_claims(api, specifications)
row_item = {
'pds_no': pds_no,
'product_name': product_name,
'product_description': product_description,
'benefits': benefits,
# 'sae_grade': sae_grade,
'performance_claims': performance_claims,
}
result.append(row_item)
return result
def get_performance_claims(
# oem_claims: str,
api: str,
specifications: str
) -> list:
result = []
if api not in ['Not available', 'Not applicable', '', None]:
result.append(f'API {api}')
# if oem_claims not in ['Not available', 'Not applicable', '', None]:
# if ',' in oem_claims:
# oem_claims = oem_claims.split(',')
# else:
# oem_claims = oem_claims.split('\n')
# result.extend([item.strip() for item in oem_claims if item])
if specifications not in ['Not available', 'Not applicable', '', None]:
if ',' in specifications:
specifications = specifications.split(',')
else:
specifications = specifications.split('\n')
result.extend([item.strip() for item in specifications if item])
return result
def generate_docx(
template_name: str,
pds_no: str,
product_name: str,
product_description: str,
fetaures: list,
oil_type: str,
performance_claims: list,
) -> None:
doc = Document(template_name)
product_name_place = "Product-name"
product_description_place = "Prod-desc"
fetaures_place = "Features-benefits"
performance_claims_place = "Performance-claim"
performance_claims_title = "Performance claims"
oil_type_place = "Oil-type"
for paragraph in doc.paragraphs:
if fetaures_place in paragraph.text:
paragraph.clear()
paragraph.text = "\n".join([f"• {item}" for item in fetaures])
for run in paragraph.runs:
run.font.name = "Arial"
if performance_claims_place in paragraph.text:
paragraph.clear()
if performance_claims:
paragraph.text = "\n".join([f"• {item}" for item in performance_claims])
for run in paragraph.runs:
run.font.name = "Arial"
else:
for paragraph_inner in doc.paragraphs:
if performance_claims_title in paragraph_inner.text:
paragraph_inner.clear()
if product_name_place in paragraph.text:
paragraph.text = paragraph.text.replace(
product_name_place, product_name
)
for run in paragraph.runs:
run.font.name = "Arial"
run.font.size = Pt(16)
run.bold = True
if product_description_place in paragraph.text:
paragraph.text = paragraph.text.replace(
product_description_place, product_description
)
for run in paragraph.runs:
run.font.name = "Arial"
if oil_type_place in paragraph.text:
paragraph.text = paragraph.text.replace(oil_type_place, oil_type)
for run in paragraph.runs:
run.font.name = "Arial"
save_folder = r"Transmission"
product_folder = product_name.replace("/", "-").strip()
for i in range(1, 4):
for section in doc.sections:
header = section.header
header.paragraphs[4].text = f"PDS No.: {pds_no}/0{i}"
for run in header.paragraphs[4].runs:
run.font.name = "Arial"
run.font.size = Pt(9)
if not os.path.exists(f'{save_folder}/{product_folder}'):
os.makedirs(f'{save_folder}/{product_folder}')
doc.save(
f'{save_folder}/{product_folder}/{product_folder}_0{i}_eng.docx'
)
excell_files = extract_data_from_excell('excell_temp.xlsx', 'Transmission oil')
for _ in excell_files:
generate_docx(
'atf_temp.docx',
_['pds_no'],
_['product_name'],
_['product_description'],
_['benefits'],
'Transmission oil',
_['performance_claims'],
)
|
export default class Slider {
/**
* Initializes a slider component.
* @param {HTMLElement} container - The container element for the slider.
* @param {number} minBound - The minimum value of the slider.
* @param {number} maxBound - The maximum value of the slider.
* @param {Function} onChange - The function to call when the slider value changes.
*/
constructor(container, minBound, maxBound, onChange) {
this.container = container;
this.onChange = onChange;
this.minBound = minBound;
this.maxBound = maxBound;
this.initializeSlider();
}
/**
* Initializes the slider DOM elements.
*/
initializeSlider() {
// Create slider DOM element for the range
this.slider = document.createElement('input');
this.slider.type = 'range';
this.slider.min = this.minBound;
this.slider.max = this.maxBound;
this.slider.value = (this.minBound + this.maxBound) / 2;
console.log("slider value" + this.slider.value)
const minLabel = document.createElement('span');
minLabel.textContent = this.minBound;
minLabel.classList.add('slider-label', 'min-label');
const maxLabel = document.createElement('span');
maxLabel.textContent = this.maxBound;
maxLabel.classList.add('slider-label', 'max-label');
const valueLabel = document.createElement('span');
valueLabel.classList.add('slider-value-label');
valueLabel.textContent = this.slider.value;
// Assign ID based on container ID
if (this.container.id === 'slider-entrance-fee-container') {
this.slider.id = 'slider-entrance-fee';
} else if (this.container.id === 'slider-rating-container') {
this.slider.id = 'slider-rating';
}
// Calculate step size based on the range of values
const range = this.maxBound - this.minBound;
this.slider.step = range / 100; // Adjust 100 according to your preference
// Add event listener to slider
this.slider.addEventListener('input', (event) => {
// Check if the event was triggered by the slider associated with this instance
if (event.target === this.slider) {
// Update the value of this slider
const value = parseFloat(this.slider.value);
this.onChange(value);
valueLabel.textContent = value;
// Update the CSS for the slider track
const thumbPosition = (value - this.slider.min) / (this.slider.max - this.slider.min);
const leftWidth = thumbPosition * 100;
const rightWidth = 100 - leftWidth;
document.styleSheets[0].addRule(`#${this.slider.id}::before`, `width: ${leftWidth}%;`);
document.styleSheets[0].addRule(`#${this.slider.id}::after`, `width: ${rightWidth}%;`);
}
});
this.container.appendChild(minLabel);
this.container.appendChild(this.slider);
this.container.appendChild(maxLabel);
this.container.appendChild(valueLabel);
valueLabel.style.paddingLeft = '71px';
// Explicitly set the position of maxLabel
maxLabel.style.position = 'absolute';
maxLabel.style.right = '-10';
}
/**
* Sets the value of the slider.
** @param {number} value - The value to set for the slider.
*/
setValue(value) {
this.slider.value = value;
}
/**
* Retrieves the current value of the slider.
* @returns {number} The current value of the slider.
*/
getValues() {
return this.slider.value;
}
}
|
<style>
.bg {
background-image: url(assets/login/simaflor.png);
background-position: center center;
}
</style>
<br>
<div class="container w-75 mt-5 rounded shadow">
<div class="row align-items-stretch">
<div class="col bg d-none d-lg-block col-md-5 col-lg-5 col-xl-6 rounded"></div>
<div class="col p-5 rounded-end">
<div class="text-end">
<img src="assets/login/simaflor.png" width="48" alt="">
</div>
<h2 class="fw-bold text-center py-5">Bienvenido</h2>
<form action="#">
<div class="mb-4">
<label for="email" class="form-label">Usuario</label>
<input type="email" class="form-control" name="email" [formControl]="usuario"
[ngClass]="{ 'is-invalid': usuario.invalid && (usuario.dirty || usuario.touched), 'is-valid': usuario.valid && (usuario.dirty || usuario.touched) }"
pattern="[a-zA-Z0-9]*">
<div class="invalid-feedback" *ngIf="usuario.errors && (usuario.dirty || usuario.touched)">
<div *ngIf="usuario.errors['required']">Este campo es requerido.</div>
<div *ngIf="usuario.errors['pattern']">Solo se permiten letras y números.</div>
<div *ngIf="usuario.errors['minlength']">Al menos 6 caracteres.</div>
<div *ngIf="usuario.errors['maxlength']">Máximo 50 caracteres.</div>
</div>
</div>
<div class="mb-4">
<label for="password" class="form-label">Contraseña</label>
<input type="password" class="form-control" name="password" [formControl]="contrasena"
[ngClass]="{ 'is-invalid': contrasena.invalid && (contrasena.dirty || contrasena.touched), 'is-valid': contrasena.valid && (contrasena.dirty || contrasena.touched) }">
<div class="invalid-feedback" *ngIf="contrasena.errors && (contrasena.dirty || contrasena.touched)">
<div *ngIf="contrasena.errors['required']">Este campo es requerido.</div>
<div *ngIf="contrasena.errors['minlength']">Al menos 6 caracteres.</div>
<div *ngIf="contrasena.errors['maxlength']">Máximo 30 caracteres.</div>
</div>
</div>
<div class="mb-4 form-check">
<input type="checkbox" name="connected" class="form-check-input">
<label for="connected" class="form-check-label">Mantener conectado</label>
</div>
<div class="d-grid">
<button type="submit" (click)="login($event)" class="btn btn-dark"
[disabled]="!usuario.valid || !contrasena.valid">Iniciar sesión</button>
</div>
<div class="my-3">
<span>¿Aun no tienes cuenta? <a href="./register">Registrate</a></span>
</div>
</form>
</div>
</div>
</div>
|
import { Image, StyleSheet, View } from 'react-native';
import React from 'react';
import Text from '../../components/Text/Text';
import BadgeStatus from '../../components/BadgeStatus/BadgeStatus';
import DashedLine from 'react-native-dashed-line';
import { colors } from '../../assets/colors/colors';
import dayjs from 'dayjs';
import icons from '../../assets/icons';
import { HistoryDataType } from '../../entities/historyTypes';
interface Props {
orderDetail: HistoryDataType;
}
export default function HeaderSlip({ orderDetail }: Props) {
return (
<View style={styles.card}>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}}>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
}}>
<Image
source={icons.invoice}
style={{
width: 24,
height: 24,
marginRight: 8,
}}
/>
<Text bold fontFamily="NotoSans">
{orderDetail?.orderNo}
</Text>
</View>
<BadgeStatus status={orderDetail?.status || ''} />
</View>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
}}>
<View
style={{
width: 24,
marginRight: 8,
}}
/>
<Text fontSize={14} color="text3" fontFamily="NotoSans">
ส่งคำสั่งซื้อ
</Text>
</View>
<DashedLine
dashColor={colors.border1}
dashGap={6}
dashLength={8}
style={{
marginVertical: 16,
}}
/>
<View
style={{
marginTop: 16,
}}>
<Text
fontSize={14}
color="text3"
semiBold
fontFamily="NotoSans"
style={{
marginBottom: 8,
}}>
ออเดอร์ของ
</Text>
<Text fontSize={18} semiBold fontFamily="NotoSans">
{orderDetail?.customerName}
</Text>
</View>
<View
style={{
marginTop: 16,
}}>
<Text
fontSize={14}
color="text3"
semiBold
fontFamily="NotoSans"
style={{
marginBottom: 8,
}}>
เขต
</Text>
<Text fontSize={18} semiBold fontFamily="NotoSans">
{orderDetail?.customerZone}
</Text>
</View>
<View
style={{
marginTop: 16,
}}>
<Text
fontSize={14}
color="text3"
semiBold
fontFamily="NotoSans"
style={{
marginBottom: 8,
}}>
เวลาที่เปิดออเดอร์
</Text>
<Text fontSize={18} semiBold fontFamily="NotoSans">
{dayjs(orderDetail?.createAt).format('DD MMM BBBB , HH:mm น.')}
</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
card: {
width: '100%',
minHeight: 200,
padding: 16,
},
});
|
/**
* Opens a closed task.
*
* @author Vladimir Florentino
* @package Taskmill
* @since 0.1.0
* @begin 2009.6.8
*/
class OpenTaskAction(jig) from Action(jig)
//! Set the controller this action will use.
static controller = 'MemberController'
//! Set the allowed request type.
static requestMethod = 2 // Action.POST
/**
* Verify this action.
*
* Check the form fields of the task page.
*
* @override
* @public
* @return boolean
*/
function verify()
task = Model.statically('Task')
// Make sure task exist.
if not task.exists(self.arg('taskId'))
Mistake.push(Lang('MISTAKES', 'invalidValue', Lang('CAPTIONS', 'taskId')))
end
// Make sure there's an open status to set.
if not self.arg('openStatus') or self.arg('openStatus') == '0'
Mistake.push(Lang('MISTAKES', 'invalidValue', Lang('DetailsTemplate', 'openStatus')), 'openStatus')
end
return Mistake.empty()
end
/**
* Handles a failed verification.
*
* @override
* @public
* @return nil
*/
function failure()
// Back to the create task screen.
self.setView('DetailsView')
self.setMistakes(Mistake.getAll())
end
/**
* Handles a successful verification.
*
* Saves the task information and redirects to result page.
*
* @override
* @public
* @return nil
*/
function success()
// Get an instance of a task (if no taskId, it will be empty).
task = Model.instance('Task', self.arg('taskId'))
// Set the task details.
task.statusId = self.arg('openStatus')
// Open the task.
task.commit()
// Redirect to result page.
self.redirect('result', ['code' => 'taskOpened', 'taskId' => self.arg('taskId')])
end
end
|
import {View, Text, StyleSheet} from 'react-native';
import React, {useEffect, useState} from 'react';
import Animated, {
useAnimatedStyle,
useSharedValue,
withTiming,
} from 'react-native-reanimated';
import Toast from 'react-native-toast-message';
interface ResultIndicatorBarProps {
value: number;
lowestLimit: number;
highestLimit: number;
lowThreshold: number;
highThreshold: number;
}
export default function ResultIdicatorBar({
value,
lowestLimit,
highThreshold,
lowThreshold,
highestLimit,
}: ResultIndicatorBarProps) {
const width = useSharedValue(0);
const [invalidTemperatureValue, setinvalidTemperatureValue] = useState(false);
useEffect(() => {
if (value < lowestLimit || value > highestLimit) {
setinvalidTemperatureValue(true);
return;
}
setinvalidTemperatureValue(false);
let percentage;
if (value === 0) percentage = 0;
else
percentage = ((value - lowestLimit) / (highestLimit - lowestLimit)) * 100;
if (percentage < 10) percentage = 10;
width.value = withTiming(percentage, {duration: 1000});
}, [value]);
let color = '#ff4e44';
if (value >= lowThreshold && value <= highThreshold) {
color = '#09d261';
} else if (value >= lowestLimit && value < lowThreshold) {
color = '#ffd279';
}
const barStyle = useAnimatedStyle(() => ({
width: `${width.value}%`,
backgroundColor: color,
}));
return invalidTemperatureValue ? (
<View style={styles.container} className="bg-gray-200">
<Animated.View style={[styles.bar]} />
</View>
) : (
<View style={styles.container} className="bg-gray-200">
<Animated.View style={[styles.bar, barStyle]} />
</View>
);
}
const styles = StyleSheet.create({
container: {
width: '100%',
height: 8,
borderRadius: 10,
overflow: 'hidden',
},
bar: {
height: '100%',
borderRadius: 10,
},
});
|
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/AddTransactionStyle.css">
<link rel="stylesheet" th:href="@{/css/CenterFormStyles.css}">
<title>Expense manager</title>
</head>
<body>
<div id="page" class="container-12">
<nav id="navbar" role="navigation" class="navbar navbar-expand-sm navbar-dark bg-dark"></nav>
<div class="row no-gutters justify-content-center">
<main role="main" class="col-10 col-sm-9 col-md-6 col-lg-4 center-main-content">
<h2 id="header" th:text="${'Add ' + type}"></h2>
<form th:action="@{/transaction/add/{type}(type=${type})}" method="post">
<div th:object="${transaction}">
<div class="form-group">
<label for="category">Category:</label>
<select id="category" name="category" class="form-control">
<option
th:each="category : ${categories}"
th:value="${category.name}"
th:text="${category.name}"></option>
</select>
</div>
<div class="form-group">
<label for="amount">Amount:</label>
<input type="text" id="amount" name="amount" class="form-control" placeholder="amount"
required/>
</div>
<div class="form-group">
<label for="date">Date:</label>
<input type="date" id="date" name="date" class="form-control" placeholder="date" required/>
</div>
<div class="form-group">
<label for="comment">Comment:</label>
<input type="text" maxlength="200" id="comment" name="comment" class="form-control"
placeholder="comment"/>
</div>
<div class="form-group">
<div class="col-sm-6 offset-sm-3">
<input type="submit" class="form-control btn btn-dark" value="Create"/>
</div>
</div>
</div><!-- End of object transaction -->
</form>
</main>
</div><!--End of row -->
</div>
<script th:src="@{/js/navbar.js}"></script>
<script>
window.onload = function () {
printNavbar();
}
</script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
</html>
|
/* eslint @typescript-eslint/no-namespace: "off" */
/**
* HTMLElement that implements the Constraint Validation API
* @see: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#the_constraint_validation_api
*/
type HTMLElement_Validation =
| HTMLButtonElement
| HTMLFieldSetElement
| HTMLInputElement
| HTMLOutputElement
| HTMLSelectElement
| HTMLTextAreaElement;
type HTMLElementEventType = keyof HTMLElementEventMap;
/**
* HTMLElement_Validation `validationMessage` (string)
*/
type validationMessage = HTMLElement_Validation["validationMessage"];
// ********************** //
// *** customValidity *** //
// ********************** //
/**
* validator function
* @param {HTMLElement_Validation} element The element to validate
* @returns {validationMessage|Promise<validationMessage>} Empty string `""` when the element is valid, the i18n custom error `validationMessage` otherwise.
*/
export type validator = (
element: HTMLElement_Validation
) => validationMessage | Promise<validationMessage>;
type validators = validator[];
/**
* Reports an element custom validity
* @async
* @param {HTMLElement_Validation} element The element to report its custom validity
* @param {validators} validators Custom validator functions
* @returns {Promise<boolean>} Whether or not the element is valid
* @fires invalid When the element is invalid
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity#examples
*/
export async function customValidityElement(
element: HTMLElement_Validation,
validators: validators
): Promise<boolean> {
// reset element customValidity
element.setCustomValidity("");
// element has no built in error validationMessage
// check for each custom validationMessage
if (element.validationMessage === "") {
for (const validator of validators) {
const validationMessage = await validator(element);
if (validationMessage !== "") {
// Set the element error validationMessage
element.setCustomValidity(validationMessage);
break;
}
}
}
return element.reportValidity();
}
type customValidityOptions = {
reportOn?: HTMLElementEventType;
};
type customValidityValue = validators | [...validators, customValidityOptions];
declare module "solid-js" {
namespace JSX {
interface DirectiveFunctions {
customValidity: typeof customValidity;
}
}
}
/**
* Whether or not a value is a plain object
* @param {unknown} value The value to check for plain object type
* @returns {boolean} Whether or not the value is a plain object
*/
function isObject(value: unknown): value is "object" {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
import type { Accessor } from "solid-js";
import { onCleanup } from "solid-js";
/**
* Directive to report an element validity
* @param {HTMLElement_Validation} element The element that uses the directive
* @param {Accessor<customValidityValue>} accessor The custom validators, with optional event type
* @example
* - A `validator` must be Type
* ```ts
* (element: HTMLElement_Validation) => string
* ```
* and returns an empty string `""` when the element is `valid`,
* or returns a i18n `validationMessage`
* - With `validator`s only
* ```jsx
* <input use:customValidity={[validator, validator]}>
* ```
* - With `validator`s and options
* ```jsx
* <input use:customValidity={[validator, validator, {
* reportOn: "change" // default
* }]}>
* ```
*/
export function customValidity(
element: HTMLElement_Validation,
accessor: Accessor<customValidityValue>
): void {
const value = accessor();
// extract and removes the last element if it's an options Object
const hasOptions = isObject(value.at(-1));
const options = hasOptions ? (value.pop() as customValidityOptions) : {};
const validators = value as validator[];
const { reportOn = "change" } = options;
const reportListener: EventListener = async () => {
await customValidityElement(element, validators);
};
element.addEventListener(reportOn, reportListener);
onCleanup(() => {
element.removeEventListener(reportOn, reportListener);
});
}
// ************************* //
// *** validationMessage *** //
// ************************* //
/**
* Reset an element validity
* @param element The element to reset the validity
*/
export function resetValidityElement(element: HTMLElement_Validation) {
element.setCustomValidity("");
element.reportValidity();
}
import type { Setter } from "solid-js";
type validationMessageSetter = Setter<validationMessage>;
type validationMessageOptions = {
resetOn?: HTMLElementEventType;
setOn?: HTMLElementEventType;
};
type validationMessageValue =
| validationMessageSetter
| [validationMessageSetter, validationMessageOptions];
declare module "solid-js" {
namespace JSX {
interface DirectiveFunctions {
validationMessage: typeof validationMessage;
}
}
}
/**
* Directive to set an element `validationMessage`
* @param {HTMLElement_Validation} element The element that uses the directive
* @param {Accessor<validationMessageValue>} accessor The `validationMessage` setter, with optional event types
* @example
* - A `validationMessageSetter` must be Type
* ```ts
* Setter<string>
* ```
* - A `validationMessageOptions` must be Type
* ```ts
* {
* resetOn?: keyof HTMLElementEventMap,
* setOn?: keyof HTMLElementEventMap
* }
* ```
* - With `validationMessageSetter` only
* ```jsx
* <input use:validationMessage={validationMessageSetter}>
* ```
* - With `validationMessageSetter` and options
* ```jsx
* <input use:validationMessage={[validationMessageSetter, {
* resetOn?: "change", // default
* setOn?: "invalid" // default
* }]}>
* ```
*/
export function validationMessage(
element: HTMLElement_Validation,
accessor: Accessor<validationMessageValue>
): void {
const value = accessor();
const hasOptions = Array.isArray(value);
const [set, options] = hasOptions ? value : [value, {}];
const { resetOn = "change", setOn = "invalid" } = options;
const setListener: EventListener = () => {
set(element.validationMessage);
};
const resetListener: EventListener = () => {
resetValidityElement(element);
set(element.validationMessage);
};
element.addEventListener(setOn, setListener);
element.addEventListener(resetOn, resetListener);
onCleanup(() => {
element.removeEventListener(setOn, setListener);
element.removeEventListener(resetOn, resetListener);
});
}
// ****************** //
// *** validation *** //
// ****************** //
type validationOptions = validationMessageOptions & customValidityOptions;
type validationValue =
| validationMessageValue
| [validationMessageSetter, validators]
| [validationMessageSetter, validators, validationOptions];
declare module "solid-js" {
namespace JSX {
interface DirectiveFunctions {
validation: typeof validation;
}
}
}
/**
* Directive to check an element validation
* @param {HTMLElement_Validation} element The element that uses the directive
* @param {Accessor<validationValue>} accessor The `validationMessage` setter, with optional event types
* @example
* - A `validationMessageSetter` must be Type
* ```ts
* Setter<string>
* ```
* - A `validator` must be Type
* ```ts
* (element: HTMLElement_Validation) => string
* ```
* and returns an empty string `""` when the element is `valid`,
* or returns a i18n `validationMessage`
* - A `validationOptions` must be Type
* ```ts
* {
* resetOn?: keyof HTMLElementEventMap,
* setOn?: keyof HTMLElementEventMap,
* reportOn?: keyof HTMLElementEventMap,
* }
* ```
* - With `validationMessageSetter` only
* ```jsx
* <input use:validation={validationMessageSetter}>
* ```
* - With `validationMessageSetter` and options
* ```jsx
* <input use:validation={[validationMessageSetter, {
* resetOn?: "change", // default
* setOn?: "invalid", // default
* }]}>
* ```
* - With `validationMessageSetter`, `validator`s and options
* ```jsx
* <input use:validation={[validationMessageSetter, [validator, validator], {
* resetOn?: "change", // default
* setOn?: "invalid", // default
* reportOn?: "change", // default
* }]}>
* ```
*/
export function validation(
element: HTMLElement_Validation,
accessor: Accessor<validationValue>
): void {
const value = accessor();
const hasOptions = Array.isArray(value) && isObject(value.at(-1));
const options = hasOptions ? (value.pop() as validationOptions) : {};
const [set, validators = []] = Array.isArray(value)
? (value as [validationMessageSetter, validators])
: [value];
const { resetOn, setOn, reportOn } = options;
validationMessage(element, () => [set, { resetOn, setOn }]);
customValidity(element, () => [...validators, { reportOn }]);
}
|
<%@ page contentType="text/html;charset=UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<table class="table table-hover">
<c:if test="${empty requestScope.table}">
<tr>
<td>결과가 없습니다.</td>
</tr>
</c:if>
<c:if test="${not empty requestScope.table}">
<thead>
<tr>
<th>순위</th>
<th>팀</th>
<th>경기수</th>
<th>승점</th>
<th>승</th>
<th>무</th>
<th>패</th>
<th>득점</th>
<th>실점</th>
<th>득실차</th>
<th>홈</th>
<th>어웨이</th>
</tr>
</thead>
<tbody>
<c:forEach var="list" items="${requestScope.table}" varStatus="status">
<tr>
<td>${list.rank}</td>
<td><a href="${list.links.team.href}" onclick="page.find(this.href); return false;"><img src="${list.logo}" width="25" height="25"> ${list.teamName}</a></td>
<td>${list.playedGames}</td>
<td>${list.points}</td>
<td>${list.wins}</td>
<td>${list.draws}</td>
<td>${list.losses}</td>
<td>${list.goals}</td>
<td>${list.goalsAgainst}</td>
<td>${list.goalDifference}</td>
<td>${list.home}</td>
<td>${list.away}</td>
</tr>
</c:forEach>
</tbody>
</c:if>
</table>
|
import { useState } from 'react'
import { Tab } from '@headlessui/react'
import TableAdmin from './TableAdmin';
function classNames(...classes) {
return classes.filter(Boolean).join(' ')
}
export default function TableAdminSection() {
let [categories] = useState({
Recent: [
{
id: 1,
title: <TableAdmin/>,
date: '2h ago',
commentCount: 3,
shareCount: 2,
},
],
Popular: [
{
id: 1,
title: 'Is tech making coffee better or worse?',
date: 'Jan 7',
commentCount: 29,
shareCount: 16,
},
{
id: 2,
title: 'The most innovative things happening in coffee',
date: 'Mar 19',
commentCount: 24,
shareCount: 12,
},
],
Trending: [
{
id: 1,
title: 'Ask Me Anything: 10 answers to your questions about coffee',
date: '2d ago',
commentCount: 9,
shareCount: 5,
},
{
id: 2,
title: "The worst advice we've ever heard about coffee",
date: '4d ago',
commentCount: 1,
shareCount: 2,
},
],
})
return (
<div className="w-full max-w-md px-2 py-16 sm:px-0">
<Tab.Group>
<Tab.List className="flex space-x-1 rounded-xl bg-blue-900/20 p-1">
<Tab
className={({ selected }) =>
classNames(
'w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-blue-700',
'ring-white ring-opacity-60 ring-offset-2 ring-offset-blue-400 focus:outline-none focus:ring-2',
selected
? 'bg-white shadow'
: 'text-blue-100 hover:bg-white/[0.12] hover:text-white'
)
}
>
Foods
</Tab>
<Tab
className={({ selected }) =>
classNames(
'w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-blue-700',
'ring-white ring-opacity-60 ring-offset-2 ring-offset-blue-400 focus:outline-none focus:ring-2',
selected
? 'bg-white shadow'
: 'text-blue-100 hover:bg-white/[0.12] hover:text-white'
)
}
>
Menus
</Tab>
<Tab
className={({ selected }) =>
classNames(
'w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-blue-700',
'ring-white ring-opacity-60 ring-offset-2 ring-offset-blue-400 focus:outline-none focus:ring-2',
selected
? 'bg-white shadow'
: 'text-blue-100 hover:bg-white/[0.12] hover:text-white'
)
}
>
Users
</Tab>
</Tab.List>
<Tab.Panels className="mt-2">
{Object.values(categories).map((posts, idx) => (
<Tab.Panel
key={idx}
className={classNames(
'rounded-xl bg-white p-3',
'ring-white ring-opacity-60 ring-offset-2 ring-offset-blue-400 focus:outline-none focus:ring-2'
)}
>
{posts.map((post) => (
<h1 key={post.id}>{post.title}</h1>
))}
</Tab.Panel>
))}
</Tab.Panels>
</Tab.Group>
</div>
)
}
|
<script setup lang="ts">
/**
* There still seems to be an issue with deep nesting where depths > 2 can't find menu items by id.
*
* This could be due to ids being stripped or rewritten as different values, or wrong var references somewhere.
*
* In any case, it works exactly like Brutalism's but with full Typescript support.
*
*
* --
*
* Another issue noticed is that checked property isn't triggering if connected to a computed getter.
* It works fine otherwise, but when linked to a computed getter to simplify a pinia store value,
* it never appears to trigger the modelValue update.
*/
import { generateQuickGuid } from "./mixins";
import { computed, onMounted, watch } from "vue";
import type { Ref } from 'vue'
import type { ContextMenuItem, ContextMenu } from './types'
import type { ContextMenuItemProp, ContextMenuProp } from './types/props'
const emit = defineEmits<{
click: [value: ContextMenuItem | ContextMenuItemProp],
'update:modelValue': [value: ContextMenu | Ref<ContextMenu>],
}>();
export interface Props {
debug?: boolean, // Used to toggle console statements within component for debugging
refresh?: boolean | Ref<boolean>,
modelValue?: ContextMenuItem[] | Ref<ContextMenuItem[]>,
}
const props = withDefaults(defineProps<Props>(), {
refresh: false,
debug: false,
modelValue: () => [] as ContextMenuItem[]
})
const menuBase = computed<ContextMenuItem[] | Ref<ContextMenuItem[]>>({
get(): ContextMenuItem[] | Ref<ContextMenuItem[]> {
return props.modelValue as ContextMenuItem[] | Ref<ContextMenuItem[]>;
},
set(val: ContextMenuItem[] | Ref<ContextMenuItem[]>): void {
emit("update:modelValue", val);
}
});
const menuBaseSanitized = computed(() => {
return sanitizeMenuList((menuBase as Ref<ContextMenu>).value ?? props.modelValue)
})
const sanitizeMenuList = (item: ContextMenu): ContextMenuProp => {
return ((menuBase as Ref<ContextMenu>).value ?? props.modelValue).map((item: ContextMenuItem) =>
sanitizeContextMenuItem(item)
) as ContextMenuProp
}
const desanitizeMenuList = (list: ContextMenuProp, comparator: ContextMenuItem[]): ContextMenuItem[] => {
return list.map((item: ContextMenuItemProp, index: number) => desanitizeMenuItem(item as ContextMenuItemProp, comparator[index]))
}
const desanitizeMenuItem = (item: ContextMenuItemProp, comparator: ContextMenuItem) => {
Object.keys(item).filter((key: string) => !Object.keys(comparator).includes(key)).forEach((key: string) => {
delete item[key as keyof ContextMenuItemProp]
})
if (item.menu && comparator.menu)
desanitizeMenuList(item.menu as ContextMenuProp, comparator.menu)
return item;
}
const menuExtended = computed(() => {
let prepend: ContextMenuItem[] = [];
if ((props.refresh as Ref<boolean>).value ?? props.refresh) {
prepend.push(sanitizeContextMenuItem({ label: 'Refresh panel', callback: () => location.reload() }))
if ((props.modelValue as ContextMenu)?.length || (props.modelValue as Ref<ContextMenu>)?.value?.length)
prepend.push({ label: '---' })
}
return [...prepend, ...(menuBaseSanitized.value as ContextMenuItem[])];
})
const sanitizeContextMenuItem = (item: ContextMenuItem): ContextMenuItemProp => {
let temp = Object.assign({}, item);
if (temp.label !== '---') {
if (!temp.hasOwnProperty('id') && temp.label !== "---") {
temp['id'] = generateQuickGuid();
}
if (!temp.hasOwnProperty('enabled')) temp['enabled'] = true;
if (!temp.hasOwnProperty('checked')) temp['checked'] = false;
if (!temp.hasOwnProperty('checkable')) temp['checkable'] = false;
if (temp.menu && temp.menu.length)
temp.menu = temp.menu.map((item: ContextMenuItem): ContextMenuItemProp => sanitizeContextMenuItem(item))
}
return temp as ContextMenuItemProp;
}
const findContextMenuItemById = (id: string, menu: ContextMenuItem[]): ContextMenuItem | undefined => {
for (const item of menu) {
if (item.id === id) return item;
if (item.menu) {
const foundInChildren = findContextMenuItemById(id, item.menu);
if (foundInChildren) {
return foundInChildren;
}
}
}
return undefined;
}
const contextClickHandler = (id: string) => {
if (props.debug) console.log(id)
const target = findContextMenuItemById(id, menuExtended.value)
if (target) {
emit('click', target)
}
if (target && target.callback) {
target.callback()
} else if (target && target.checkable) {
if (props.debug) {
console.log("Toggling checked property on target:")
console.log(target);
}
const mirror = JSON.parse(JSON.stringify(menuBaseSanitized.value))
const sibling = findContextMenuItemById(id, mirror);
if (sibling) {
sibling.checked = !sibling?.checked;
if (props.debug)
console.log("Updating sibling to toggled value:", sibling.checked)
const newValue = desanitizeMenuList(mirror, menuBase.value as ContextMenuItem[])
menuBase.value = newValue;
emit("update:modelValue", newValue); // Isn't working for computed getter?
}
} else if (props.debug) {
console.log("Target not found")
}
}
const hasContextMenu = computed(() => {
return ((menuExtended as Ref<ContextMenu>).value ?? props.modelValue).length
})
const setContextMenu = (value?: ContextMenuProp | ContextMenu) => {
if (props.debug) console.log("Setting context menu...")
if (value && props.debug) console.log(JSON.stringify(value))
else if (props.debug) console.log(JSON.stringify(menuExtended.value))
try {
window.__adobe_cep__.invokeAsync(
"setContextMenuByJSON",
JSON.stringify({
menu: value || menuExtended.value
}),
contextClickHandler
);
} catch (err) {
console.log(err)
}
}
onMounted(() => {
if (hasContextMenu.value && window.__adobe_cep__) {
setContextMenu(menuExtended.value)
watch(() => menuExtended.value, (newVal: ContextMenuProp | ContextMenu) => {
if (props.debug) console.log("Context menu change")
setContextMenu(newVal)
})
}
})
</script>
<template />
|
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { Facture } from '../../models/facture.model';
import { Factureitem } from '../../models/factureitem.model';
import { MatTableDataSource } from '@angular/material/table';
import { FactureService } from '../../services/facture.service';
import { FactureitemService } from '../../services/factureitem.service';
import { MatDialog } from '@angular/material/dialog';
import { FactureitemorderitemFormComponent } from '../factureitemorderitem-form/factureitemorderitem-form.component';
@Component({
selector: 'app-factureitem-table',
templateUrl: './factureitem-table.component.html',
styleUrls: ['./factureitem-table.component.scss']
})
export class FactureitemTableComponent implements OnInit {
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
@Input() projectIdFromParent: any = '';
@Input() factureFromParent: Facture;
@Input() factureIdFromParent: string;
factureItems!: MatTableDataSource<Factureitem>;
factureItemsArray: Factureitem[];
columnsToDisplay = ['id', 'order', 'orderitem', 'descEn', 'quantity', 'unit', 'unitPrice', 'totalPrice', 'factureitemannexe5s'];
factureId: string;
constructor(
private factureService: FactureService,
private factureitemService: FactureitemService,
private dialog: MatDialog,
) { }
ngOnInit(): void {
this.factureId = this.factureIdFromParent;
this.getFactureItems(this.factureId);
}
getFactureItems(factureId: string): void {
this.factureService.getFactureFactureItems(factureId)
.subscribe((factureItems: Factureitem[]) => {
console.log("factureItems fetched successfully")
this.factureItemsArray = factureItems;
this.factureItems = new MatTableDataSource(this.factureItemsArray);
// this.factureItems.sort = this.sort;
// this.factureItems.paginator = this.paginator;
});
}
openAddFactureItemOrderItemFormDialog(
factureItemId: string, factureItem: Factureitem,
orderId: string
) {
const dialogRef = this.dialog.open(FactureitemorderitemFormComponent, {
data: {
factureItemIdFromTable: factureItemId,
factureItemFromTable: factureItem,
orderIdFromTable: orderId,
projectIdFromTable: this.projectIdFromParent,
}
});
dialogRef.afterClosed().subscribe({
next: (updatedFactureItem) => {
// console.log("here is afterClosed");
// console.log(updatedFactureItem);
if (updatedFactureItem) {
console.log("new materialcard added to orderitem");
console.log(updatedFactureItem);
this.updateFactureItemsArrayAfterAdd(updatedFactureItem);
}
}
});
}
deleteFactureItemOrderItem(
factureItemId: string,
) {
this.factureitemService.deleteFactureItemOrderItem(factureItemId).subscribe((data: any) => {
console.log("deleted orderitem from factureitem");
this.updateFactureItemsArrayAfterDelete(factureItemId);
});
}
updateFactureItemsArrayAfterAdd(factureItem: Factureitem): void {
// Get the index of the item you want to remove
const index = this.factureItemsArray.findIndex(facture => facture.id === factureItem.id);
// Remove the item from the array
if (index !== -1) {
this.factureItemsArray.splice(index, 1);
this.factureItemsArray.splice(index, 0, factureItem);
this.factureItems = new MatTableDataSource(this.factureItemsArray);
}
}
updateFactureItemsArrayAfterDelete(factureItemId: string): void {
// Get the index of the item you want to remove
const index = this.factureItemsArray.findIndex(order => order.id === factureItemId);
// Remove the item from the array
if (index !== -1) {
this.factureItemsArray[index].orderitem = {"id":''};
this.factureItems = new MatTableDataSource(this.factureItemsArray);
}
}
}
|
/* Basic Reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100%; /* Essential for full height management */
margin: 0;
padding: 0;
display: flex;
flex-direction: column; /* Stack children vertically */
}
.content{
flex: 1; /* Consumes any available space */
display: flex;
flex-direction: column; /* Ensures content is aligned vertically */
min-height: 0; /* Fixes flexbox bugs in some browsers */
}
/**about css__start**/
.container {
display: flex;
flex-wrap: wrap;
height: 100vh;
}
.text-section, .image-section {
flex: 1 1 50%; /* Each section takes half of the container */
display: flex;
align-items: center;
justify-content: center;
padding: 25px;
}
.text-section {
order: 1; /* Text on the left */
}
.image-section {
order: 2; /* Image on the right */
background: url('../about.png') no-repeat center center;
background-size: cover;
transform: scale(0.7);
}
/* Responsive behavior */
@media (max-width: 600px) {
.nav-menu {
flex-direction: column; /* Stack links vertically on smaller screens */
padding: 20px; /* More padding in smaller viewports */
}
.nav-menu li {
text-align: center; /* Center align the text for vertical configuration */
width: 100%; /* Full width for easier tap targets */
}
}
@media (max-width: 800px) {
.text-section, .image-section {
flex: 1 1 100%;
order: 2; /* Image goes on top on smaller screens */
}
.text-section {
order: 1;
}
}
h1, h2 {
color: #2196F3; /* Example of a contrasting color for headers */
}
/**about css_end**/
/**NAV css__start**/
.navbar {
background-color: #333; /* Dark background for contrast */
color: white;
font-size: 1.6rem;
line-height: 1.5;
padding: 10px 20px; /* Sufficient padding for tap targets */
}
.nav-menu {
list-style-type: none;
display: flex;
justify-content: center; /* Centering the menu items horizontally */
align-items: center;
}
.nav-menu li {
padding: 10px 20px; /* Adequate padding for each link */
}
.nav-menu a {
text-decoration: none;
color: white;
transition: color 0.3s; /* Smooth transition for hover effect */
}
.intro-section {
height: 100vh; /* Full viewport height */
background-size: cover;
background-position: center;
display: flex;
align-items: center; /* Vertically center the text */
justify-content: center; /* Horizontally center the text */
}
.intro-text {
background-color: rgba(255, 255, 255, 0.8); /* Semi-transparent background for text for readability */
padding: 20px;
border-radius: 8px;
width: 90%; /* Responsive width */
max-width: 600px; /* Maximum width */
text-align: center;
}
h1 {
font-size: 2.5rem; /* Large, clear header size */
}
h2 {
margin-top: 0;
font-size: 2rem;
color: rgb(37, 45, 117);
}
h3 {
margin-top: 0;
font-size: 1.7rem;
color: #1d1835;
}
p {
font-size: 1.4rem;
color: #666;
}
.nav-menu a:hover,
.nav-menu a:focus {
color: #04AA6D; /* Highlight color on hover or focus for better user feedback */
}
/**NAV css__end**/
/**Header-block css__start**/
.header-block {
display: flex;
align-items: center;
background-color: #f0f0f069;
padding: 10px;
}
.logo-section, .header-name, .tooltip-section {
display: flex;
align-items: center;
justify-content: center;
}
.logo {
width: 50px;
height: auto;
opacity: 0.6;
cursor: pointer;
}
.logo:hover {
opacity: 1;
}
.vertical-text {
display: flex; /* Enables flexbox for the vertical text container */
flex-direction: column; /* Stacks children vertically */
font-size: 1.1rem; /* Sets the size of the font, adjust as needed */
cursor: pointer; /* Makes the text appear clickable */
}
.header-name {
flex: 1;
text-align: center;
font-size: 24px;
background-color: transparent;
}
.tooltip-section {
position: relative;
}
.settingsImg {
/* Styles for the image */
width: 70px; /* Sets the width of the icon */
height: auto; /* Maintains the aspect ratio of the icon */
display: block; /* Ensures the image does not have extra space around it */
}
.tooltip-button {
background-color: transparent; /* Sets a transparent background */
color: white;
border: none;
cursor: pointer;
padding: 10px 20px;
font-size: 16px;
opacity: 0.7;
}
.tooltip-button:hover {
opacity: 1;
}
.tooltip-content {
display: none; /* initially hidden */
background-color: black;
color: white;
text-align: center;
border-radius: 6px;
padding: 10px;
position: absolute;
z-index: 1;
top: 120%;
right: 0;
}
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(26px);
}
.label-text {
color: white;
margin-left: 10px;
}
/**Header-block css__end**/
/**footer css__start**/
.footer {
position: relative;
background-color: #333;
color: white;
padding: 20px;
text-align: left;
}
.platforms-tab {
position: absolute;
right: 20px;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
}
.tab-text {
background-color: #2196F3;
padding: 5px 10px;
border-radius: 5px;
}
.platforms-details {
visibility: hidden;
position: absolute;
right: 0;
bottom: 100%;
background-color: #2196F3;
color: white;
text-align: left;
padding: 10px;
border-radius: 5px;
white-space: nowrap;
z-index: 100;
}
.platforms-tab:hover .platforms-details {
visibility: visible;
}
.platforms-details ul {
list-style-type: none;
padding: 0;
}
.platforms-details li {
margin: 5px 0;
}
/**footer css__end**/
/**preview css___start**/
#app {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 50vh; /* Full viewport height */
width: 100vw; /* Full viewport width */
text-align: center;
transition: background-color 0.3s, color 0.3s; /* Smooth transitions for color changes */
}
body.high-contrast #app {
background-color: #000;
color: #FFF;
}
body.high-contrast .inner-circle,
body.high-contrast .progress-ring__circle {
stroke: white; /* Changes the stroke to white in high contrast mode */
}
body.high-contrast .inner-circle {
background-color: #333; /* Dark background for the inner circle */
}
.controls {
margin-bottom: 10px;
}
.loader-container {
position: relative;
width: 200px;
height: 200px;
}
.progress-ring {
transform: rotate(-90deg);
transform-origin: center;
}
.progress-ring__circle {
stroke: black;
stroke-width: 4;
fill: none;
r: 90;
cx: 100;
cy: 100;
stroke-dasharray: 565.48; /* Approximately 2 * π * 90 */
stroke-dashoffset: 565.48;
transition: stroke-dashoffset 0.3s linear;
}
.inner-circle {
position: absolute;
top: 50%;
left: 50%;
width: 160px;
height: 160px;
background-color: #fff;
border-radius: 50%;
transform: translate(-50%, -50%);
transition: background-color 0.5s;
}
button {
margin-top: 20px;
padding: 10px 20px;
font-size: 16px;
}
/**preview css___end**/
/**color legend__start*/
.color-legend {
justify-content: center;
display: flex;
align-items: center; /* Vertically align items in the legend */
gap: 10px; /* Space between color boxes and text */
padding: 10px; /* Padding around the legend for better spacing */
background: #f4f4f4; /* Light background for the legend */
border-radius: 5px; /* Rounded corners for the legend box */
font-size: 14px; /* Font size for the text */
}
.color-box {
width: 20px; /* Width of the color box */
height: 20px; /* Height of the color box */
border: 1px solid #ccc; /* Border around color box to enhance visibility */
}
/* High contrast styles */
.high-contrast .color-legend {
background-color: black;
color: white;
}
.high-contrast .color-box {
border-color: white; /* Make borders visible in high contrast */
}
/**color legend end**/
/**tooltips start**/
.tooltip {
position: relative;
cursor: pointer;
}
.tooltip::after {
content: attr(data-tooltip);
position: absolute;
width: 150px;
background-color: black;
color: white;
padding: 5px;
border-radius: 5px;
text-align: center;
bottom: 120%; /* Adjust as needed */
left: 50%;
transform: translateX(-50%);
white-space: nowrap;
opacity: 0;
visibility: hidden;
transition: opacity 0.3s, visibility 0.3s;
}
.tooltip.show::after {
visibility: visible;
opacity: 1;
}
/**tooltips end**/
|
import React from "react";
import { Routes, Route, Navigate } from "react-router-dom";
import HomePage from "./home/home";
import LoginPage from "./login/login";
import NotFoundPage from "./notFound/notFound";
import Author from "./author/author";
import SavedPosts from "./savedPosts/savedPosts";
import ProtectedRoute from "../components/protectedRoute/protectedRoute";
function Pages() {
return (
<div
data-name="pages-routes"
className="min-h-screen h-full min-w-full pt-18 pb-5 text-lg flex flex-row justify-center items-center
bg-gray-50 text-slate-800 dark:bg-slate-700 dark:text-white transition-03"
>
<div
data-name="pages-routes-container"
className="w-full h-full xs:max-w-xl sm:max-w-xl
md:max-w-3xl lg:max-w-5xl xl:max-w-6xl"
>
<Routes>
<Route index element={<HomePage />} />
<Route path="home" element={<Navigate to="/" />} />
<Route element={<ProtectedRoute />}>
<Route path="Author" element={<Author />} />
<Route path="saved-posts" element={<SavedPosts />} />
</Route>
<Route path="login" element={<LoginPage />} />
<Route path="register" element={<LoginPage />} />
<Route path="*" element={<NotFoundPage />} />
</Routes>
</div>
</div>
);
}
export default Pages;
|
using System;
using UnityEngine;
public class HoverEngine : MonoBehaviour
{
public SimpleVRLever leftLever;
public SimpleVRLever rightLever;
[SerializeField] double leftLeverValue;
[SerializeField] double rightLeverValue;
Rigidbody rb;
[Header("Power Variables")]
[SerializeField] float engineRevTime = 0.1f;
[SerializeField] float upForce = 2;
[SerializeField] float engineThrust;
[SerializeField] bool thrustOff;
[Header("Raycasting Properties")]
RaycastHit hit;
[SerializeField] float rayLength = 10;
[SerializeField] float maxHeight = 10;
[SerializeField] float maxGroundDistance;
[SerializeField] LayerMask groundLayer;
[Header("Engine State")]
[SerializeField] engineState state;
[Header("Ship Rotation")]
[SerializeField] float MinMaxAngle = 10;
float initialLeftAngle;
float initialRightAngle;
void Start()
{
rb = GetComponent<Rigidbody>();
// Store initial lever angles
initialLeftAngle = leftLever.currentAngle;
initialRightAngle = rightLever.currentAngle;
// Invoke Mono.Cecil-based modification here
ModifyScript();
}
private void Update()
{
leftLeverValue = leftLever.currentAngle;
rightLeverValue = rightLever.currentAngle;
switch (state)
{
case engineState.on:
enginePower();
driveMode();
break;
case engineState.off:
enginePower();
break;
}
}
void enginePower()
{
if (Physics.Raycast(transform.position, -transform.up, out hit, rayLength, groundLayer))
{
Debug.DrawRay(transform.position, transform.forward * hit.distance, Color.red);
}
}
private void FixedUpdate()
{
if (Physics.Raycast(transform.position, -transform.up, out hit, maxGroundDistance, groundLayer))
{
float distanceToGround = hit.distance;
float proportionalHeight = (maxHeight - distanceToGround) / maxHeight;
Vector3 appliedHoverForce = Vector3.up * proportionalHeight * upForce;
rb.AddForce(appliedHoverForce, ForceMode.Acceleration);
}
rotationStablization();
}
void driveMode()
{
// Calculate turning torque based on lever values
float leftLeverAngle = (float)(leftLever.currentAngle - initialLeftAngle) * Mathf.Rad2Deg;
float rightLeverAngle = (float)(rightLever.currentAngle - initialRightAngle) * Mathf.Rad2Deg;
float turningTorque = 0f;
// Check if levers are in default position
if (Mathf.Approximately(leftLeverAngle, 0f) && Mathf.Approximately(rightLeverAngle, 0f))
{
// Apply braking force or reduce velocity
rb.velocity *= 0.95f; // Reduce velocity by 5% each FixedUpdate
}
else
{
if (!thrustOff)
{
// Check which lever is more forward
if (Mathf.Abs(leftLeverAngle) > Mathf.Abs(rightLeverAngle))
{
// Apply turning torque based on the left lever angle
turningTorque = leftLeverAngle;
}
else
{
// Apply turning torque based on the right lever angle
turningTorque = -rightLeverAngle;
}
}
// Apply turning torque
rb.AddTorque(transform.up * turningTorque);
// Apply thrust if neither lever is significantly more forward
if (Mathf.Abs(leftLeverAngle - rightLeverAngle) < 5f)
{
rb.AddForce(transform.forward * engineThrust);
}
}
}
void rotationStablization()
{
// Get current angles
float X = transform.eulerAngles.x;
float Y = transform.eulerAngles.y;
float Z = transform.eulerAngles.z;
// Limit angles
float clampedX = Mathf.Clamp(X, -MinMaxAngle, MinMaxAngle);
float clampedZ = Mathf.Clamp(Z, -MinMaxAngle, MinMaxAngle);
float clampedY = Mathf.Clamp(Y, -MinMaxAngle, MinMaxAngle);
// Apply angles via Quaternion Euler to avoid Gimbal Lock
Quaternion stablelize = Quaternion.Euler(clampedX, clampedY, clampedZ);
transform.rotation = stablelize;
}
bool floorCondition(float distance, float max, GameObject floor)
{
return distance < max && floor != null;
}
bool greaterByPercent(double originalVal, double newVal, double percentage)
{
// Divide the original value by a percentage out of 100%
double thresholdCalc = originalVal * (1 + percentage / 100);
return newVal > thresholdCalc;
}
enum engineState
{
on,
off
}
void ModifyScript()
{
// Add your Mono.Cecil code here to dynamically modify the script at runtime
Debug.Log("Script modification using Mono.Cecil");
// Example: Inject code to compare lever values and adjust ship's behavior
// Note: This part requires Mono.Cecil implementation which can't be provided in this text-based interface.
}
}
|
import Video from '../models/Video';
export const home = async(req, res) => {
const videos = await Video.find({}).sort({createdAt: "asc"})
return res.render("home", {pageTitle: "Home", videos});
}
export const watch = async(req, res) => {
const {id} = req.params;
const video = await Video.findById(id);
if(!video){
return res.render("404", {pageTitle: "Video not found"});
}
return res.render("watch", {pageTitle: video.title , video});
}
export const getEdit = async(req, res) => {
const { id } = req.params;
const video = await Video.findById(id);
if(!video){
return res.render("404", {pageTitle: "Video not found"});
}
return res.render("edit", {pageTitle: `Edit ${video.title}`, video});
}
export const postEdit = async (req, res) => {
const { id } = req.params;
const {title, description, hashtags} = req.body;
const video = await Video.exists({_id: id});
if(!video){
return res.render("404", {pageTitle: "Video not found."});
}
await Video.findByIdAndUpdate(id, {
title,
description,
hashtags: Video.formatHashtags(hashtags),
// hashtags: hashtags.split(',').map((word) => (word.startsWith('#') ? word : `#${word}`)),
});
return res.redirect(`/videos/${id}`);
}
export const getUpload = (req, res) => {
return res.render("upload", {pageTitle: "Upload Video"});
}
export const postUpload = async(req, res) => {
const {title, description, hashtags} = req.body;
try{
await Video.create({
title,
description,
hashtags: Video.formatHashtags(hashtags),
// hashtags: hashtags.split(',').map((word) => (word.startsWith('#') ? word : `#${word}`)),
});
return res.redirect("/");
}catch(error){
return res.status(400).render("upload", {
pageTitle:"Upload Video",
errorMessage: error._message,
});
}
}
export const deleteVideo = async(req, res) => {
const {id} = req.params;
await Video.findByIdAndDelete(id);
//delete video
return res.redirect("/");
}
export const search = async (req, res) => {
const {keyword} = req.query;
let videos= [];
if(keyword){
videos = await Video.find({
title: {
$regex: new RegExp(keyword, "i")
}
});
}
return res.render("search", {pageTitle: "Search", videos});
}
|
package jwtext
import (
"errors"
"log"
"github.com/golang-jwt/jwt/v5"
"github.com/tanveerprottoy/stdlib-go-template/internal/pkg/config"
"github.com/tanveerprottoy/stdlib-go-template/pkg/timeext"
)
// Create the JWT key used to create the signature
var JwtKey = []byte(config.GetEnvValue("secret"))
// GenerateToken generates a new token
func GenerateToken(payload map[string]any) string {
/* RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(expirationTime),
IssuedAt: jwt.NewNumericDate(datetime.Now()),
NotBefore: jwt.NewNumericDate(datetime.Now()),
Issuer: "test",
Subject: "somebody",
ID: "1",
Audience: []string{"somebody_else"},
}, */
// Declare the expiration time of the token
// token := jwt.New(jwt.SigningMethodRS256)
claims := jwt.MapClaims{}
claims["exp"] = jwt.NewNumericDate(timeext.AddDate(0, 0, 3))
claims["authorized"] = true
claims["id"] = payload["id"]
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, _ := token.SignedString(JwtKey)
return tokenString
}
func Parse(tokenBody string) (*jwt.Token, error) {
token, err := jwt.Parse(
tokenBody,
func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodRSA); !ok {
return nil, errors.New("unexpected signing method")
}
return JwtKey, nil
},
)
if err != nil {
return nil, errors.New("malformed token")
}
if !token.Valid {
return nil, errors.New("invalid token")
}
return token, nil
}
func ParseClaims(token *jwt.Token) jwt.MapClaims {
if claims, ok := token.Claims.(jwt.MapClaims); ok {
return claims
} else {
log.Printf("Invalid JWT Token")
return nil
}
}
|
# MiniPaint Shapes
### 👨💻 [Download APK](https://drive.google.com/file/d/1FzUPBhkmacIGHRdfsjxPiqIPsZw8u1S_/view?usp=sharing)
<img src="https://img.shields.io/badge/code_style-standard-brightgreen.svg"> <img src="https://img.shields.io/badge/architecture-MVVM-blue">
<img src="https://img.shields.io/badge/minSdk-21-orange"> <img src="https://img.shields.io/badge/targetSdk-32-lightgrey">
<img src="https://img.shields.io/badge/version-1-yellow">
A simple android application, where user can draw different shapes and designs of different colors.
<img src="https://user-images.githubusercontent.com/54761454/153617211-43af18f6-7cc6-4b34-997d-ef8f597ab909.gif" width="240" height="500" />
---
## Requirements
For development, you will only need:
* Android Studio
* Android Device or Emulator installed along with Android Studio
* Minimum supported Android SDK
## Getting started
- [Install Android Studio](https://developer.android.com/studio/install.html)
- Download the project
```bash
git clone https://github.com/The-Pascal/MiniPaint_Shapes.git
```
- Open the project into Android Studio.
- Build the project and run the sample. You may need to update gradle and library versions.
- Follow the guidance provided by Android Studio.
- If you still not able to build the project try installing the [APK](https://drive.google.com/file/d/1FzUPBhkmacIGHRdfsjxPiqIPsZw8u1S_/view?usp=sharing) of the applicaiton
## Built With 🛠
- [Kotlin](https://kotlinlang.org/) - First class and official programming language for Android development.
- [Android Architecture Components](https://developer.android.com/topic/libraries/architecture) - Collection of libraries that help you design robust, testable, and maintainable apps.
- [LiveData](https://developer.android.com/topic/libraries/architecture/livedata) - Data objects that notify views when the underlying database changes.
- [Canvas](https://developer.android.com/reference/android/graphics/Canvas) - Canvas is a class in Android that performs 2D drawing of different objects onto the screen.
- [ViewModel](https://developer.android.com/topic/libraries/architecture/viewmodel) - Stores UI-related data that isn't destroyed on UI changes.
- [DataBinding](https://developer.android.com/topic/libraries/data-binding) - Allows to bind UI components in your XML layouts to data sources in your app using a declarative format rather than programmatically.
- [Material Components for Android](https://github.com/material-components/material-components-android) - Modular and customizable Material Design UI components for Android.
|
package com.fabrica.software.entities;
import java.io.Serializable;
import java.util.Objects;
import com.fabrica.software.entities.pk.ItemPedidoPK;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
@Entity
@Table(name= "itens_pedido")
public class ItensPedido implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private ItemPedidoPK id= new ItemPedidoPK();
private int quantidade;
private double preco;
public ItensPedido() {
}
public ItensPedido(Pedido pedido, Produto produto, int quantidade, double preco) {
id.setPedido(pedido);
id.setProduto(produto);
this.quantidade = quantidade;
this.preco = preco;
}
@JsonIgnore
public Pedido getPedido() {
return id.getPedido();
}
public void setPedido(Pedido pedido) {
id.setPedido(pedido);
}
public Produto getProduto() {
return id.getProduto();
}
public void setProduto(Produto produto) {
id.setProduto(produto);
}
public int getquantidade() {
return quantidade;
}
public void setquantidade(int quantidade) {
this.quantidade = quantidade;
}
public double getpreco() {
return preco;
}
public void setpreco(double preco) {
this.preco = preco;
}
public Double getTotal() {
return preco*quantidade;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ItensPedido other = (ItensPedido) obj;
return Objects.equals(id, other.id);
}
}
|
/** © Copyright 2022 CERN
*
* This software is distributed under the terms of the
* GNU Lesser General Public Licence version 3 (LGPL Version 3),
* copied verbatim in the file “LICENSE”
*
* In applying this licence, CERN does not waive the privileges
* and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*
* Author: Adrien Ledeul (HSE)
*
**/
#ifndef UTILS_HXX
#define UTILS_HXX
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
#include <future>
#include <chrono>
#include <iostream>
#include <cstring>
template <class T>
std::ostream& operator << (std::ostream& os, const std::vector<T>& iterable)
{
for (auto & i : iterable)
os << i << " ";
return os;
}
namespace Common {
using std::future;
using std::future_status;
using std::cout;
using std::exception;
using std::endl;
class Utils
{
public:
Utils() = delete;
static auto split(const std::string& str, char delimiter = '$') -> std::vector<std::string>
{
std::vector<std::string> result;
std::size_t previous = 0;
std::size_t current = 0;
while ((current = str.find(delimiter, previous))!= std::string::npos) {
result.emplace_back(str.substr(previous, current - previous));
previous = current + 1;
}
result.emplace_back(str.substr(previous));
return result;
}
template <typename T>
static T CopyNSwapBytes(const T& value)
{
T retVal;
std::memcpy(reinterpret_cast<void*>(&retVal), reinterpret_cast<const void*>(&value), sizeof(T));
std::reverse(reinterpret_cast<uint8_t*>(&retVal), reinterpret_cast<uint8_t*>(&retVal) + sizeof(T));
return retVal;
}
template <typename T>
static T CopyNSwapBytes(const void* value)
{
return CopyNSwapBytes(*reinterpret_cast<const T*>(value));
}
template <typename T>
static T CopyNSwapBytes(const char* value)
{
return CopyNSwapBytes(*static_cast<const T*>(static_cast<const void*>(value)));
}
};
}
#endif // UTILS_HXX
|
class BankAccount:
def __init__(self, int_rate=0.01, balance=0):
self.int_rate = int_rate
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance -= amount
return self
def display_account_info(self):
print(self.balance)
return self
def yield_interest(self):
self.balance += self.balance*self.int_rate
return self
class User: # here's what we have so far
def __init__(self, name, email):
self.name = name
self.email = email
self.account = BankAccount(int_rate=0.02, balance=0)
# adding the deposit method
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
self.account.balance.deposit(amount) # the specific user's account increases by the amount of the value received
def make_withdrawal(self, amount):
self.account.balance.withdraw(amount)
def display_user_balance(self):
print(self.account.balance)
def transfer_money(self, other_user, amount):
self.account.balance.withdraw(amount)
other_user.account.balance.deposit(amount)
|
"use client"
import { usePathname } from "next/navigation"
import { Audio } from "@/types"
import { playerStore } from "@/zustand/playerStore"
import { Download, Loader, Pause, Play } from "lucide-react"
import { playingType } from "@/types/player"
import { unslugify } from "@/lib/utils"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { TooltipButton } from "../ui/tooltip-button"
import AudioCardMenu from "./AudioCardMenu"
interface Props {
data: Audio
}
const AudioCard: React.FC<Props> = ({ data }) => {
return (
<div className="group relative flex cursor-pointer items-center justify-between rounded-md border border-gray-500 p-3 px-2 font-mono hover:border-0 hover:ring-1 hover:ring-[#2ca4ab]">
<div className="flex items-center space-x-2">
<Avatar className="ring-[#2ca4ab] group-hover:ring-2">
<AvatarImage src={data.reciter_info?.picture} />
<AvatarFallback>CN</AvatarFallback>
</Avatar>
<div>
<p className="truncate text-xs font-bold capitalize">
{unslugify(data.xassida_info.name)}
</p>
<span className="text-xs capitalize text-gray-500 group-hover:text-[#2ca4ab]">
{unslugify(data.reciter_info.name)}
</span>
</div>
</div>
<div className="flex items-center space-x-1">
<Controls data={data} />
</div>
</div>
)
}
const Controls: React.FC<Props> = ({ data }) => {
const pathname = usePathname()
const [isCurrentPlaying, playXassida, downloading, setDownloading] =
playerStore((state) => [
state.isCurrentPlaying,
state.playXassida,
state.downloading,
state.setDownloading,
])
const handleDownload = (id: number) => {
setDownloading(id)
const file = data.file
const splits = file.substring(file.lastIndexOf("/") + 1).split("?")
const [filename] = splits
const xhr = new XMLHttpRequest()
xhr.responseType = "blob"
xhr.onload = () => {
const a = document.createElement("a")
a.href = window.URL.createObjectURL(xhr.response)
a.download = filename
a.style.display = "none"
document.body.appendChild(a)
a.click()
setDownloading(null)
}
xhr.open("GET", file)
xhr.send()
}
return (
<>
<TooltipButton
onClick={() => playXassida(data)}
tooltip="Demarrer/Arreter"
>
{isCurrentPlaying(data.id, playingType.Audio) ? (
<Pause className="h-4 w-4 fill-primary text-primary" />
) : (
<Play className="h-4 w-4 fill-primary text-primary" />
)}
</TooltipButton>
{downloading == data.id ? (
<Loader size={16} className="animate-spin" />
) : (
<TooltipButton
onClick={() => handleDownload(data.id)}
tooltip="Telecharger"
>
<Download size={16} />
</TooltipButton>
)}
{pathname === "/dashboard" && <AudioCardMenu data={data} />}
</>
)
}
export default AudioCard
|
<?php
/**
* Blocks Initializer
*
* Enqueue CSS/JS of all the blocks.
*
* @since 1.0.0
* @package MightyBlocks
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Enqueue Gutenberg block assets for both frontend + backend.
*
* @since 1.0.0
*/
function mightyblocks_block_assets() {
// Styles.
wp_enqueue_style(
'font-awesome',
plugins_url( 'dist/fontawesome/fontawesome-all.css', dirname( __FILE__ ) )
);
wp_enqueue_style(
'mightyblocks-style-css',
plugins_url( 'dist/blocks.style.build.css', dirname( __FILE__ ) ),
array( 'wp-blocks' )
);
if ( ! is_admin() ) {
wp_enqueue_script(
'mightyblocks-block-js',
plugins_url( '/dist/public.js', dirname( __FILE__ ) ),
array( 'jquery' )
);
}
} // End function mightyblocks_block_assets().
// Hook: Frontend assets.
add_action( 'enqueue_block_assets', 'mightyblocks_block_assets' );
/**
* Enqueue Gutenberg block assets for backend editor.
*
* @since 1.0.0
*/
function mightyblocks_editor_assets() {
$options = array();
$options[ 'plugin_url' ] = plugins_url( '/', dirname( __FILE__ ) );
// Scripts.
wp_enqueue_script(
'mightyblocks-block-js',
plugins_url( '/dist/blocks.build.js', dirname( __FILE__ ) ),
array( 'wp-blocks' )
);
wp_localize_script(
'mightyblocks-block-js',
'mightyblocks',
$options
);
// Styles.
wp_enqueue_style(
'font-awesome',
plugins_url( 'dist/fontawesome/fontawesome-all.css', dirname( __FILE__ ) )
);
wp_enqueue_style(
'mightyblocks-block-editor-css',
plugins_url( 'dist/blocks.editor.build.css', dirname( __FILE__ ) ),
array( 'wp-edit-blocks' )
);
} // End function mightyblocks_editor_assets().
// Hook: Editor assets.
add_action( 'enqueue_block_editor_assets', 'mightyblocks_editor_assets', 11 );
function mightyblocks_plugin_template_path() {
return apply_filters(
'mightyblocks_plugin_template_path',
untrailingslashit( plugin_dir_path( dirname( __FILE__ ) ) )
);
}
function mightyblocks_plugin_template_url() {
return apply_filters(
'mightyblocks_plugin_template_url',
untrailingslashit( plugin_dir_url( dirname( __FILE__ ) ) )
);
}
function mightyblocks_locate_template( $template_name ) {
$template_path = '/mightyblocks/';
$plugin_path = mightyblocks_plugin_template_path() . '/mightyblocks/';
$plugin_url = mightyblocks_plugin_template_url() . '/mightyblocks/';
// Look within passed path within the theme - this is priority
$template = locate_template(
array(
$template_path . $template_name,
$template_name
)
);
if ( $template ) {
$template = untrailingslashit( get_stylesheet_directory_uri() ) . $template_path . $template_name;
}
if ( ! $template && file_exists( $plugin_path . $template_name ) ) {
$template = $plugin_url . $template_name;
}
// Return what we found
return $template;
}
include_once plugin_dir_path( dirname( __FILE__ ) ) . '/blocks/Video.php';
$MightyBlocksVideo = new MightyBlocksVideo();
include_once plugin_dir_path( dirname( __FILE__ ) ) . '/blocks/Button.php';
$MightyBlocksButton = new MightyBlocksButton();
include_once plugin_dir_path( dirname( __FILE__ ) ) . '/blocks/Icon.php';
$MightyBlocksIcon = new MightyBlocksIcon();
include_once plugin_dir_path( dirname( __FILE__ ) ) . '/blocks/ContentBox.php';
$MightyBlocksContentBox = new MightyBlocksContentBox();
|
import { Router } from 'express';
import TransactionsRepository from '../repositories/TransactionsRepository';
import CreateTransactionService from '../services/CreateTransactionService';
const transactionRouter = Router();
const transactionsRepository = new TransactionsRepository();
const createTransactionService = new CreateTransactionService(transactionsRepository);
transactionRouter.get('/', (request, response) => {
try {
const transactionList = transactionsRepository.all();
const balance = transactionsRepository.getBalance();
const responseElement = {
transactions: transactionList,
balance,
}
return response.status(200).json(responseElement);
} catch (err) {
return response.status(400).json({ error: err.message });
}
});
transactionRouter.post('/', (request, response) => {
try {
const { title, value, type } = request.body;
const createdTransaction = createTransactionService.execute({ title, value, type });
return response.status(200).json(createdTransaction);
} catch (err) {
return response.status(400).json({ error: err.message });
}
});
export default transactionRouter;
|
import mongoose from "mongoose";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
const UserSchema = new mongoose.Schema(
{
fullname: { type: String, required: true },
email: { type: String, required: true },
password: { type: String },
address: [{ detail: { type: String }, for: { type: String } }],
phoneNumber: [{ type: Number }],
},
{
timestamps: true,
}
);
UserSchema.methods.generateJwtToken = function () {
return jwt.sign({ user: this._id.toString() }, "ZomatoAPP"); //ZomatoAPP is the secret key to send the token to the user
};
UserSchema.statics.findByEmailAndPhone = async ({ email, phoneNumber }) => {
//check whether email exists
const checkUserByEmail = await UserModel.findOne({ email });
const checkUserByPhone = await UserModel.findOne({ phoneNumber });
if (checkUserByEmail || checkUserByPhone) {
throw new Error("User already exists!");
}
return false;
};
UserSchema.statics.findByEmailAndPassword = async ({ email, password }) => {
//check whether user exists
const user = await UserModel.findOne({ email });
if (!user) throw new Error("User does not exist!");
//compare password
const doesPasswordMatch = await bcrypt.compare(password, user.password);
if (!doesPasswordMatch) throw new Error("Invalid Password!");
return user;
};
UserSchema.pre("save", function (next) {
// pre function is used to run while in a state of mongoose. "save" indicated the state of creating a database
const user = this; //this refers to the object being created while creating database data object
if (!user.isModified("password")) return next(); // if password is not modified, return next function
//else, generate salt
bcrypt.genSalt(8, (error, salt) => {
if (error) return next(error);
//hash the password - library used is bcryptjs
bcrypt.hash(user.password, salt, (error, hash) => {
if (error) return next(error);
//assigning hashed password
user.password = hash;
return next();
});
}); //since it's an async function, we will use a callback inside it
}); //All the next methods are methods lined up inside mongoose.
export const UserModel = mongoose.model("Users", UserSchema);
|
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
// Variables para el movimiento de la imagen
let x = 0;
let y = 0;
let dx = 5;
let dy = 5;
// Broadcast a todos los clientes conectados
function broadcast(data) {
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
}
// Función para actualizar la posición de la imagen
function updatePosition() {
// Actualizar las coordenadas
x += dx;
y += dy;
// Invertir la dirección si la imagen alcanza los límites
if (x <= 0 || x >= 500) {
dx *= -1;
}
if (y <= 0 || y >= 500) {
dy *= -1;
}
// Enviar las nuevas coordenadas a todos los clientes
const positionData = JSON.stringify({ x, y });
broadcast(positionData);
}
// Ejecutar la función updatePosition cada 100ms (10 FPS)
setInterval(updatePosition, 100);
// Manejar la conexión de los clientes WebSocket
wss.on('connection', ws => {
// Enviar las coordenadas iniciales al cliente que se conecta
ws.send(JSON.stringify({ x, y }));
// Manejar los mensajes enviados por el cliente (si los hay)
ws.on('message', message => {
console.log(`Mensaje recibido: ${message}`);
});
});
console.log('Servidor WebSocket escuchando en el puerto 8080...');
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.